Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f018fddd3 | ||
|
|
908859b093 | ||
|
|
00c63ccf90 | ||
|
|
e18b21d83a | ||
|
|
67035d6e50 | ||
|
|
1d4290f347 | ||
|
|
307d51a988 | ||
|
|
2447ecead1 | ||
|
|
a40ab7fe53 | ||
|
|
73f0c4ca94 | ||
|
|
43185ce573 | ||
|
|
1a3aaed6b2 | ||
|
|
85e08b5ba3 | ||
|
|
2bc18a01ef | ||
|
|
a893c1dfbd | ||
|
|
d8391a38e2 | ||
|
|
7fa8c3da6e | ||
|
|
aef29e7cde | ||
|
|
1bbfd9bd54 | ||
|
|
cbfc1686fa | ||
|
|
63a525126e | ||
|
|
1c2d94b9bc | ||
|
|
fb9048fb03 | ||
|
|
e1e8f3c7c2 | ||
|
|
50af2b4969 | ||
|
|
e14626723a | ||
|
|
649c45e4bd | ||
|
|
d7610f9b12 | ||
|
|
e4822237fb | ||
|
|
5d18b2555e | ||
|
|
2ace729801 | ||
|
|
488f27e095 | ||
|
|
826a142fc0 | ||
|
|
d1b40285dd | ||
|
|
3ac28c3193 | ||
|
|
39dc8fc535 | ||
|
|
762ff36131 | ||
|
|
5894dceb98 | ||
|
|
92c371e5e0 | ||
|
|
936f2f49e4 | ||
|
|
9687a4b11c | ||
|
|
32bab7731e | ||
|
|
f64848ca9c | ||
|
|
94ab211431 | ||
|
|
e8b0e5b73c |
@@ -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:
|
||||
@@ -221,34 +221,9 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Stage pinned Windows skin runtime
|
||||
if: matrix.platform == 'windows-latest'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$version = '22.23.1'
|
||||
$expectedSha256 = '7df0bc9375723f4a86b3aa1b7cc73342423d9677a8df4538aca31a049e309c29'
|
||||
$archive = Join-Path $env:RUNNER_TEMP "node-v$version-win-x64.zip"
|
||||
$extractRoot = Join-Path $env:RUNNER_TEMP "codex-x-node-$version"
|
||||
$targetRoot = 'apps/desktop/src-tauri/runtime/windows/node'
|
||||
Invoke-WebRequest -Uri "https://nodejs.org/dist/v$version/node-v$version-win-x64.zip" -OutFile $archive
|
||||
$actualSha256 = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
if ($actualSha256 -cne $expectedSha256) {
|
||||
throw "Node.js archive checksum mismatch: $actualSha256"
|
||||
}
|
||||
Remove-Item -LiteralPath $extractRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Expand-Archive -LiteralPath $archive -DestinationPath $extractRoot
|
||||
$sourceRoot = Join-Path $extractRoot "node-v$version-win-x64"
|
||||
New-Item -ItemType Directory -Path $targetRoot -Force | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $sourceRoot 'node.exe') -Destination $targetRoot -Force
|
||||
Copy-Item -LiteralPath (Join-Path $sourceRoot 'LICENSE') -Destination $targetRoot -Force
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $targetRoot 'node.exe') -PathType Leaf)) {
|
||||
throw 'Pinned Windows Node.js runtime was not staged.'
|
||||
}
|
||||
|
||||
- name: Test Windows filesystem compatibility
|
||||
if: matrix.platform == 'windows-latest'
|
||||
run: cargo test --manifest-path apps/desktop/src-tauri/Cargo.toml --lib --locked
|
||||
run: cargo test --release --manifest-path apps/desktop/src-tauri/Cargo.toml --lib --locked -- --test-threads=1
|
||||
|
||||
- name: Import Apple signing certificate and notarization key
|
||||
if: matrix.macos
|
||||
@@ -341,7 +316,7 @@ jobs:
|
||||
releaseAssetNamePattern: ${{ matrix.asset_pattern }}
|
||||
uploadUpdaterJson: true
|
||||
uploadUpdaterSignatures: true
|
||||
updaterJsonPreferNsis: false
|
||||
updaterJsonPreferNsis: true
|
||||
retryAttempts: 3
|
||||
|
||||
- name: Verify updater signatures were generated
|
||||
@@ -353,6 +328,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: |
|
||||
@@ -380,17 +363,14 @@ jobs:
|
||||
rm -rf "$portable_root"
|
||||
mkdir -p "$portable_dir"
|
||||
cp apps/desktop/src-tauri/target/release/codex-x.exe "$portable_dir/Codex-X.exe"
|
||||
mkdir -p "$portable_dir/skin-runtime/node"
|
||||
cp apps/desktop/src-tauri/runtime/windows/node/node.exe "$portable_dir/skin-runtime/node/node.exe"
|
||||
cp apps/desktop/src-tauri/runtime/windows/node/LICENSE "$portable_dir/skin-runtime/node/LICENSE"
|
||||
cp THIRD_PARTY_NOTICES.md "$portable_dir/THIRD_PARTY_NOTICES.md"
|
||||
touch "$portable_dir/Codex-X.portable"
|
||||
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.
|
||||
Keep the skin-runtime directory beside Codex-X.exe; it contains the verified Windows skin runtime.
|
||||
Microsoft Edge WebView2 Runtime is required; Windows 10/11 usually already includes it.
|
||||
EOF
|
||||
powershell -NoProfile -Command "Compress-Archive -Path '${portable_dir}/*' -DestinationPath '${archive}' -Force"
|
||||
@@ -460,7 +440,10 @@ jobs:
|
||||
--manifest latest.json \
|
||||
--assets release-assets.json \
|
||||
--version "$VERSION" \
|
||||
--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
|
||||
|
||||
@@ -498,7 +481,9 @@ jobs:
|
||||
python3 scripts/validate_updater_release.py \
|
||||
--manifest published-latest.json \
|
||||
--assets release-assets.json \
|
||||
--version "$VERSION"
|
||||
--version "$VERSION" \
|
||||
--repository "$GITHUB_REPOSITORY" \
|
||||
--release-tag "$RELEASE_TAG"
|
||||
|
||||
python3 - <<'PY' > updater-urls.txt
|
||||
import json
|
||||
@@ -507,9 +492,11 @@ jobs:
|
||||
print(entry["url"])
|
||||
PY
|
||||
sort -u updater-urls.txt | while read -r url; do
|
||||
curl -fsSLI \
|
||||
curl -fsSL \
|
||||
--range 0-0 \
|
||||
--retry 5 \
|
||||
--retry-delay 3 \
|
||||
--retry-all-errors \
|
||||
"$url" >/dev/null
|
||||
"$url" \
|
||||
-o /dev/null
|
||||
done
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
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: cargo test --manifest-path apps/desktop/src-tauri/Cargo.toml --lib --locked -- --test-threads=1
|
||||
- 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
|
||||
@@ -1,379 +1,445 @@
|
||||
# Changelog
|
||||
# 更新日志
|
||||
|
||||
All notable changes to Codex-X will be documented here.
|
||||
记录 Codex-X 的新功能、体验改进和问题修复。
|
||||
|
||||
## [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、桌面设置等配置丢失的问题。
|
||||
- 修复内部任务被误同步,以及回退后的正常会话被误报异常的问题。
|
||||
|
||||
## [v0.3.18] - 2026-09-17
|
||||
|
||||
- 第三方模型映射后可在 Codex 中选择推理等级,并修复 DeepSeek 每次发送消息先报错、重试后才能使用的问题。
|
||||
- 新增后台配置检查:发现可能导致 Codex 无法使用的问题时提醒你,可选择修复,也可稍后到「设置 → 通用设置」处理。修复前会自动备份。
|
||||
- 会话支持导出为 Markdown,多选会话可打包下载;MCP 和 Skills 支持 ZIP 导出、重新导入,取消 Skills ZIP 的 20 MB 大小限制。
|
||||
- 修复「导入已有」弹窗的暗色显示、无效 MCP 重复出现,以及大日志记录被用量统计跳过的问题。
|
||||
|
||||
## [v0.3.17] - 2026-09-09
|
||||
|
||||
### 新增与优化
|
||||
|
||||
- 官方账号支持查看剩余额度、重置时间和可用重置次数,列表中显示邮箱、套餐和登录状态。
|
||||
- 新增 DeepSeek、MiniMax、小米 MiMo 等主流厂商预设和模型映射,方便在 Codex 中使用第三方模型,并保留已有配置。
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 修复编辑正在使用的供应商时保存报错、切换后出现重复供应商,以及部分第三方连接认证失败的问题。
|
||||
- 修复用量统计切换日期范围时页面闪白的问题。
|
||||
|
||||
## [v0.3.16] - 2026-09-09
|
||||
|
||||
### 新功能
|
||||
|
||||
- 支持保存多个官方 Codex 账号,并为每个账号起不同的名字,方便切换使用。
|
||||
- 官方账号和第三方供应商都支持一键复制,点击后直接生成副本。
|
||||
- 新增“开启 1M 上下文窗口”选项,可按需勾选使用(需要模型支持)。
|
||||
- 设置页新增“用量统计”,可以查看 Token 用量、每日趋势、模型分布和最近 10 个会话,并按日期、模型筛选。
|
||||
- AI 后台子任务的用量合并到主对话,聊天列表只显示主会话。最近会话显示聊天标题或项目名,更容易找到。
|
||||
|
||||
### 体验改进
|
||||
|
||||
- 提示词页面的标题统一为蓝色,设置页的标签切换加入过渡动画。
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 修复同步 GitHub 提示词模板时,供应商按钮暂时无法使用的问题。
|
||||
- 修复切换供应商后,原有的 CC Switch 供应商从列表消失的问题。
|
||||
|
||||
## [v0.3.15] - 2026-08-20
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 修复 Windows 点击“重启 Codex”后只隐藏窗口、未真正退出,以及再次重启时报错的问题。
|
||||
|
||||
## [v0.3.14] - 2026-08-20
|
||||
|
||||
### 更新
|
||||
|
||||
- MCP 和 Skills 支持添加自定义备注,方便区分用途。
|
||||
- 供应商支持复制,同一 API 平台可以保存多个模型或多份配置,副本放在列表末尾。
|
||||
- 简化供应商列表,不再重复显示模型信息。
|
||||
- 设置页新增“重启 Codex”按钮,支持 macOS 和 Windows。
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 修复相同供应商配置被覆盖,以及复制当前供应商后丢失启用状态的问题。
|
||||
- 修复 Codex 自动创建的子代理会话被错误标记为“待同步”的问题。
|
||||
|
||||
## [v0.3.13] - 2026-08-18
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 已归档的会话不再被标记为“待同步”,切换供应商时会继续保持归档状态。
|
||||
|
||||
## [v0.3.12] - 2026-08-11
|
||||
|
||||
### 更新
|
||||
|
||||
- 提升使用流畅度,修复部分问题。
|
||||
|
||||
## [v0.3.11] - 2026-08-11
|
||||
|
||||
### 更新
|
||||
|
||||
- 提升使用流畅度,修复部分问题。
|
||||
|
||||
## [v0.3.10] - 2026-08-11
|
||||
|
||||
### 更新
|
||||
|
||||
- 提升使用流畅度,修复部分问题。
|
||||
|
||||
## [v0.3.9] - 2026-08-11
|
||||
|
||||
### 更新
|
||||
|
||||
- 提升使用流畅度,修复部分问题。
|
||||
|
||||
## [v0.3.8] - 2026-08-03
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 修复部分使用问题。
|
||||
|
||||
## [v0.3.7] - 2026-08-02
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 修复部分使用问题。
|
||||
|
||||
## [v0.3.6] - 2026-07-31
|
||||
|
||||
### 更新
|
||||
|
||||
- 官方登录与第三方供应商切换后,新建会话即可使用,无需重启 Codex。
|
||||
- 关闭主窗口后,软件会留在 macOS 菜单栏或 Windows 托盘中,可从菜单恢复窗口或退出。
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 修复切换第三方供应商时丢失官方登录或官方 API Key 的问题,现在切回官方时可以恢复。
|
||||
- 修复编辑当前供应商时意外新增副本、重复导入 cc-switch 产生重复项的问题,并兼容旧版 cc-switch 的官方登录导入。
|
||||
- 修复同时操作供应商、提示词或其他设置时,配置被覆盖或损坏的问题。
|
||||
- 修复会话同步提示成功却未生效的问题,并改善对自定义会话存储位置的支持。
|
||||
- 修复旧记录被重复计入会话数量,以及同步时误改旧会话或项目位置的问题。
|
||||
|
||||
## [v0.3.5] - 2026-07-28
|
||||
|
||||
### 更新
|
||||
|
||||
- GitHub 提示词模板可以直接查看和编辑内容,名称和文件名仍跟随在线版本。
|
||||
- 编辑后的模板会标记为“本地已修改”,后续同步不会覆盖你的修改,新模板仍会正常下载;修改在下次启用模板时生效。
|
||||
- 仅查看模板或保存未改动的内容,不会影响后续在线更新。
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 修复同步 GitHub 模板时只能看到 5 个、无法获取完整 11 个模板的问题;网络异常时仍可使用已有缓存。
|
||||
- 修复使用第三方供应商时,概览页误报未找到官方登录信息的问题。
|
||||
|
||||
## [v0.3.4] - 2026-07-28
|
||||
|
||||
### 更新
|
||||
|
||||
- 在线模板库新增 6 套提示词,点击同步 GitHub 模板即可获取,不增加安装包体积。
|
||||
- 软件开发新增“长期维护工程师”“系统化调试与根因修复”“严格代码审查”。
|
||||
- 写作辅助新增“清晰表达与润色”“技术文档写作”“结构化长文起草”。新模板会自动分类,仍保留用户手动设置的分类。
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 修复切换第三方供应商或从 cc-switch 导入后,官方登录信息被覆盖、需要重新登录的问题。
|
||||
- “还原官方配置”不再自动切换当前供应商;新增“新建官方配置”,方便清除异常认证后重新登录。
|
||||
- 调整官方认证编辑框,长内容可以换行显示,更方便查看和选择。
|
||||
|
||||
## [v0.3.3] - 2026-07-26
|
||||
|
||||
### 调整
|
||||
|
||||
- 暂时下线皮肤中心,隐藏侧边栏入口,保留用户已保存的本地主题文件。
|
||||
- 升级后会自动关闭此前启用的皮肤,恢复 Codex 官方外观;若恢复失败,会显示原因。
|
||||
- 安装包不再附带“椎名真白·樱花画室”主题壁纸,减小下载体积。
|
||||
|
||||
## [v0.3.2] - 2026-07-25
|
||||
|
||||
### 问题修复
|
||||
|
||||
- 修复 Windows 启动 Codex 或进入新版首页、外观设置时,皮肤功能错误提示无法识别 Codex 的问题。
|
||||
- 皮肤出现异常时仍可点击“关闭皮肤”,恢复过程中会避免重复操作。
|
||||
|
||||
### 安全改进
|
||||
|
||||
- 皮肤功能仅用于已识别的官方 Codex 窗口,不会应用到普通网页。
|
||||
|
||||
## [v0.3.1] - 2026-07-24
|
||||
|
||||
### 更新
|
||||
|
||||
- 皮肤中心重新设计主题画廊:直接展示真实壁纸和侧边栏、会话区、输入框、按钮等整套界面效果,单个主题不再拉伸占满整行,并移除端点、目录、`theme.json` 路径和主题包结构等开发者信息。
|
||||
- 皮肤中心新增可管理的分类筛选并进一步压缩主题卡片密度;导出主题时改用系统“另存为”窗口选择目录和文件名。
|
||||
- 支持直接从图片创建自适应主题,并可编辑主题名称、简介和界面透明度;内置主题与图片主题共用相同的编辑与预览规格。
|
||||
- 主题画廊根据当前分类数量自适应 1 至 4 列,少量主题保持紧凑,多个主题充分利用可用宽度。
|
||||
- 实机换肤扩展到 Windows:动态校验官方 `OpenAI.Codex` Store 包,安全启动仅绑定回环地址的 CDP 会话,并在 Windows 发布包中附带固定校验的 Node.js 22 运行时;不修改 `WindowsApps`、`app.asar` 或权限。
|
||||
- 皮肤中心只保留“关闭皮肤”入口,移除与其重复的“恢复官方外观”按钮;底层完整恢复能力继续保留用于异常恢复。
|
||||
- 重新设计皮肤中心,可直接预览壁纸、侧边栏、会话区和输入框的整体效果,主题卡片更紧凑。
|
||||
- 支持主题分类筛选,卡片会根据数量自动调整为 1 至 4 列;导出主题可使用系统“另存为”窗口。
|
||||
- 支持从图片创建主题,并修改名称、简介和界面透明度。
|
||||
- 皮肤功能支持 Windows 官方商店版 Codex,无需修改 Codex 安装文件。
|
||||
- 合并重复的恢复按钮,统一使用“关闭皮肤”。
|
||||
|
||||
### 修复 Bug
|
||||
### 问题修复
|
||||
|
||||
- 修复 macOS 皮肤已经注入后 Codex-X 仍长期显示“应用中”、重开后无法识别当前主题的问题;单次注入现在会明确退出,外部命令带有硬超时,并可从经过验证的 Codex 主进程恢复遗失的本机调试端口。
|
||||
- 修复皮肤尚未运行时错误显示“重新应用”、刷新缺少明确反馈,以及提示词或皮肤卡片过多时页面无法继续向下滚动的问题。
|
||||
- 优化普通横图在新任务首页超宽横幅中的自动焦点,避免人物头部被居中 `cover` 裁掉;主题包仍可通过 `art.focusY` 显式覆盖自动位置。
|
||||
- 修复切换到中转供应商时覆盖官方 `auth.json` 的问题,官方登录凭据与供应商凭据现在分别保存和恢复。
|
||||
- 改进 Codex Desktop 检测,兼容更多安装路径、包标识和版本输出格式,减少部分用户错误显示“未检测到 Codex”的情况。
|
||||
- 修复启用皮肤后新会话输入框消失、输入框出现会话内容穿透,以及图片主题预览错误使用默认背景的问题。
|
||||
- 修复浅色主题的固定白色遮罩洗淡壁纸颜色的问题;壁纸保持原图色彩,卡片和项目选择区域跟随透明度,同时为输入框保留可读性下限。
|
||||
- 修复 macOS 应用皮肤后一直显示“应用中”,以及重开软件后无法识别当前主题的问题。
|
||||
- 修复皮肤按钮状态错误、刷新缺少反馈,以及提示词或主题较多时无法继续向下滚动的问题。
|
||||
- 优化横图壁纸的裁剪,减少人物头部被切掉的情况。
|
||||
- 修复切换第三方供应商时覆盖官方登录信息的问题。
|
||||
- 改善 Codex 安装检测,减少已安装却显示“未检测到 Codex”的情况。
|
||||
- 修复启用皮肤后输入框消失、聊天内容透过输入框,以及图片主题预览显示错误背景的问题。
|
||||
- 修复浅色主题下壁纸颜色发白的问题,并改善透明度调整和输入框文字的清晰度。
|
||||
|
||||
### 安全
|
||||
### 安全与来源
|
||||
|
||||
- 换肤运行时只连接经过签名、进程归属和页面标记验证的官方 Codex,并将 CDP 限制在 `127.0.0.1`;停止注入器前会核对 PID、启动时间、Node 路径、脚本路径和端口。
|
||||
- 主题导入增加 ZIP 越界、符号链接、重复文件、文件数量、图片大小和 Manifest 字段校验;运行时使用稳定快照,避免主题切换时配置与图片不一致。
|
||||
|
||||
### 开发
|
||||
|
||||
- 固定复用 Codex Dream Skin Studio `5fd8af532efbaa87d2d0092297fd2d45cd56574e` 的 MIT 注入实现,并加入 Rust 与 Node 专项回归测试;未包含上游声明为非 MIT 授权的真人主题素材。
|
||||
- 加强官方 Codex 识别、主题导入和切换检查。
|
||||
- 换肤功能使用 Codex Dream Skin Studio 的 MIT 授权代码,未包含其非 MIT 授权的真人主题素材。
|
||||
|
||||
## [v0.3.0] - 2026-07-16
|
||||
|
||||
### 更新
|
||||
|
||||
- 全面升级桌面界面,统一各页面布局、按钮、弹窗和 Toast,并加入深浅色模式与页面过渡动画。
|
||||
- 新增应用内更新:macOS、Windows MSI 和 Linux AppImage 可直接下载、安装并重新启动;发现更新时会在侧边栏显示入口和进度。
|
||||
- 完善供应商管理:删除增加二次确认,连接测试改用 `/v1/models`,添加或编辑时可获取并选择模型,同时简化 OpenAI Official 页面。
|
||||
- 完善指令提示词管理:新增分类功能,内置两套新模板,精简模板卡片,添加或编辑后只保存、不自动启用。
|
||||
- 在线提示词会在启动后后台同步并保存到本机;支持 CDN、GitHub 备用源和系统代理,离线时也能使用上次同步内容。
|
||||
- 简化会话管理:统一同步到当前供应商,取消启动时自动修改,并支持查看、选择和删除内部会话。
|
||||
- 优化 Skills/MCP 导入,自动排除已经导入的内容,没有新内容时不再弹出空窗口。
|
||||
- 全面更新界面,统一页面、按钮、弹窗和通知样式,加入深浅色模式与页面切换动画。
|
||||
- 新增应用内更新,macOS、Windows MSI 和 Linux AppImage 用户可直接下载、安装并重启;侧边栏会显示更新入口和进度。
|
||||
- 改进供应商连接测试,删除前增加确认,添加或编辑时可以获取并选择模型,官方登录页面更简洁。
|
||||
- 提示词新增分类和两套内置模板,卡片更简洁;添加或编辑后只保存,需要时再手动启用。
|
||||
- 启动后会在后台同步在线模板,网络异常时尝试备用下载来源;模板会保存到本机,离线时仍能使用,支持系统代理。
|
||||
- 会话统一同步到当前供应商,不再在启动时自动修改;支持查看、选择和删除内部会话。
|
||||
- 导入 Skills / MCP 时会跳过已有内容,没有新内容时不再弹出空窗口。
|
||||
|
||||
### 修复 Bug
|
||||
### 问题修复
|
||||
|
||||
- 修复旧提示词配置可能导致 Codex 报 `expected u32`,以及 Windows `.codex` 使用链接目录后无法正常读写的问题。
|
||||
- 修复会话同步可能改写聊天内容、出现 `invalid_id_prefix`、重复显示会话或覆盖正在写入记录的问题。
|
||||
- 修复深浅色模式下的文字、滚动条、复选框和弹窗显示异常,以及弹窗打开后背景仍能滚动的问题。
|
||||
- 修复提示词缓存延迟造成的重复同步、错误更新或误删除,并修复应用内更新失败后的错误状态提示。
|
||||
- 修复部分旧提示词配置导致 Codex 报错,以及 Windows 将配置文件夹链接到其他位置后无法读写的问题。
|
||||
- 修复会话同步报错、会话重复显示,以及聊天记录被误改或覆盖的问题。
|
||||
- 修复深浅色模式下部分文字和控件显示异常,以及打开弹窗后背景仍能滚动的问题。
|
||||
- 修复提示词重复同步、错误更新或误删除,以及应用更新失败后提示不准确的问题。
|
||||
- 完善安装包和更新的安全检查。
|
||||
|
||||
### 兼容说明
|
||||
|
||||
- `v0.3.0` 是首个支持应用内更新的版本,旧版用户需要手动安装本版本一次。
|
||||
- Windows 便携版和 Linux deb/rpm 继续手动更新;Windows MSI 首次安装仍可能出现 SmartScreen 提示。
|
||||
|
||||
### 开发
|
||||
|
||||
- 增加更新包签名、macOS 签名与公证,并完成后端模块拆分和发布流程安全加固。
|
||||
- Windows 便携版和 Linux deb/rpm 仍需手动更新;Windows MSI 首次安装可能出现系统安全提示(SmartScreen)。
|
||||
|
||||
## [v0.2.35] - 2026-07-13
|
||||
|
||||
### 更新
|
||||
|
||||
- 新增 `gpt-5.6-sol-unrestricted.md` 指令提示词模板,同步 GitHub 模板后即可在【指令提示词】页面启用。
|
||||
- 优化第三方供应商切换:切换后新建或重新打开 Codex 会话即可使用新的中转,无需重启整个 Codex 客户端。
|
||||
- 优化从 cc-switch 导入供应商的结果提示,现在会分别显示新增、更新、合并和跳过数量。
|
||||
|
||||
### 修复 Bug
|
||||
|
||||
- 修复相同 API 地址和 API Key 的供应商因名称、模型或其他配置不同而重复显示的问题;相同地址但不同 Key 的供应商仍会分别保留,升级后也会自动整理已有重复项。
|
||||
- 修复切换到其他供应商或切回 OpenAI Official 后,原供应商可能从列表中消失的问题;切换前会自动保存当前供应商。
|
||||
- 修复从 cc-switch 重复导入时可能覆盖 Codex-X 中已有供应商名称、模型或自定义配置的问题,并兼容旧版 cc-switch 数据。
|
||||
- 优化会话列表:Codex 自动创建的后台子会话不再重复显示为普通会话,项目数量和会话总数更加准确。
|
||||
- 优化会话编号显示,保留编号开头和结尾,减少多个会话看起来像同一个会话的情况。
|
||||
- 修复检测到的供应商与本地供应商同名时,编辑保存可能因 ID 冲突覆盖另一条记录的问题。
|
||||
- 新增 `gpt-5.6-sol-unrestricted.md` 提示词模板,同步 GitHub 模板后即可启用。
|
||||
- 切换第三方供应商后,新建或重新打开 Codex 会话即可使用新供应商,无需重启整个 Codex 客户端。
|
||||
- 自动整理 API 地址和密钥均相同的重复供应商;同一地址使用不同密钥的供应商仍分别保留。
|
||||
- 修复切换供应商或切回官方登录后,原供应商可能消失的问题。
|
||||
- 从 cc-switch 导入时,会显示新增、更新、合并和跳过数量;重复导入不再覆盖已有名称、模型和自定义配置,并兼容旧版 cc-switch 数据。
|
||||
- 会话列表不再重复展示 Codex 自动创建的后台子会话,项目和会话数量更准确;会话编号保留首尾,方便区分。
|
||||
- 修复编辑同名供应商时可能覆盖另一条记录的问题。
|
||||
|
||||
## [v0.2.34] - 2026-07-13
|
||||
|
||||
### 更新
|
||||
|
||||
- 会话管理新增指定会话永久删除:支持单选、多选,并在二次确认后从当前 Codex 存储中硬删除;操作不进入回收站、不创建新的删除备份,Codex-X 内无法撤销。
|
||||
- “按项目路径分组”新增项目级三态勾选,可一次选中某个项目在当前列表中加载的全部会话,也支持跨多个项目批量选择;搜索状态下会同时显示当前命中数与项目会话总数。
|
||||
- 重做会话列表为更克制的表格式布局,统一标题、更新时间、Provider、模型和 ID 列,降低高亮边框、彩色标签与重复装饰造成的视觉干扰。
|
||||
- 移除“已选 / 需修复、选择需同步、清空选择、修复选中”等按条修复控件,保留顶部“检查会话”和“同步 / 修复”用于全量处理。
|
||||
- 永久删除确认窗口会预览待删除会话,并要求确认已关闭正在使用相关会话的其他 Codex 窗口或 CLI;由所选会话派生的子会话也会一并处理。
|
||||
|
||||
### 修复 Bug
|
||||
|
||||
- 修复默认窗口大小下会话列表滚动条在下拉过程中消失、必须放大窗口才能继续查看的问题;列表现在使用稳定的内部滚动区域并阻止滚动穿透。
|
||||
- 修复同时存在当前 `state_*.sqlite` 与旧版 `sqlite/state_*.sqlite` 时,会话总数重复统计并混入旧会话的问题;现在优先使用当前活动会话数据库。
|
||||
- 修复批量删除部分失败时结果反馈不完整的问题,界面会保留未删除项并显示失败数量与原因,方便关闭占用进程后重试。
|
||||
|
||||
### 开发
|
||||
|
||||
- 永久删除优先调用 Codex App Server 官方 `thread/delete`,不可用时使用本地兼容清理,并复用跨平台 Codex 可执行文件探测与启动逻辑。
|
||||
- 本地兼容清理覆盖父子会话、当前及旧版会话数据库关联记录、活动/归档 Rollout、会话索引、历史记录、Shell 快照以及日志、记忆、目标和本地目录等关联数据。
|
||||
- 会话同步与删除共用维护锁,并增加 Rollout 规范路径校验与符号链接边界保护,避免并发维护或越界删除。
|
||||
- 增加活动数据库优先级、父子会话与重复库清理、关联记录清理、Rollout 越界拒绝及符号链接防护测试。
|
||||
- 会话管理支持单选或多选后永久删除,所选会话派生的子会话也会一并删除。删除不进入回收站、不创建新的备份,在 Codex-X 中无法撤销。
|
||||
- 删除前可预览待删除会话,并需确认已关闭其他正在使用这些会话的 Codex 窗口或命令行进程。
|
||||
- 支持按项目勾选当前已加载的会话,也可跨项目批量选择;搜索时同时显示匹配数量和项目会话总数。
|
||||
- 会话列表改为紧凑表格,标题、更新时间、供应商、模型和编号更清晰。检查与修复统一使用顶部的“检查会话”和“同步 / 修复”。
|
||||
- 修复默认窗口大小下会话列表无法继续向下滚动的问题。
|
||||
- 修复升级 Codex 后可能重复统计会话、混入旧会话的问题。
|
||||
- 批量删除部分失败时,会保留未删除项并显示失败数量和原因,方便处理后重试。
|
||||
|
||||
## [v0.2.33] - 2026-07-11
|
||||
|
||||
### 更新
|
||||
|
||||
- 重做【指令提示词】页面布局:当前状态、启用方式和模板列表使用统一的紧凑框架,模板来源与更新时间更容易查看。
|
||||
- GitHub 提示词目录改为权威同步:自动发现并缓存新增 `.md`,清理远端已删除模板和历史别名缓存;离线时仍可使用上次成功同步的内容。
|
||||
- GitHub `examples/` 新增 `海鸥3.0破甲.md`,并清理不再使用的旧示例模板。
|
||||
|
||||
### 修复 Bug
|
||||
|
||||
- 修复首次进入提示词页或切换导航返回时,会先显示历史缓存、随后再跳到 GitHub 最新模板的问题;同一次启动中会保留已同步状态,不再重复回退旧列表。
|
||||
- 修复提示词模板较多时列表溢出最外层边框的问题,外层面板现在会随完整列表正确增高。
|
||||
- 修复 GitHub 同步并发、部分模板下载失败和异常目录响应可能造成缓存状态错乱或误删的问题;失败后允许重新同步。
|
||||
- 修复远端模板已删除但仍在启用时,重启后可能无法识别和关闭的问题;当前生效模板会保留明确的关闭入口。
|
||||
- 删除 `gpt5.5-jeli.md` 介绍中多余的“测试生效”文案。
|
||||
- 修复 macOS Apple Silicon / Intel、Windows 和 Linux 应用图标外围出现大块白边的问题,重新生成全平台透明图标资源。
|
||||
|
||||
### 开发
|
||||
|
||||
- 增加 GitHub 模板动态发现、缓存去重、离线回退、过期缓存删除和异常目录保护测试,并为缓存刷新增加互斥与事务保护。
|
||||
- 修正发布脚本遗漏 `Cargo.lock` 的问题,确保 tag 内 Rust 包版本与应用版本一致。
|
||||
- 重新整理【指令提示词】页面,当前状态、启用方式、模板来源和更新时间更清晰,并简化模板说明。
|
||||
- 同步 GitHub 时会自动添加新模板、移除已删除模板;离线时仍可使用上次成功同步的内容。
|
||||
- 新增 `海鸥3.0破甲.md` 示例模板,清理不再使用的旧示例。
|
||||
- 修复返回提示词页面时列表先显示旧内容再跳到新内容,以及模板较多时列表超出边框的问题。
|
||||
- 修复同步或下载失败时模板列表可能出错、误删的问题,失败后可重新同步;正在使用的模板即使已从 GitHub 删除,重启后仍可正常关闭。
|
||||
- 修复 macOS、Windows 和 Linux 应用图标外围出现大块白边的问题。
|
||||
|
||||
## [v0.2.32] - 2026-07-11
|
||||
|
||||
### 更新
|
||||
|
||||
- 提示词页的“启用方式”新增问号说明,用户可以直接看到“保留原提示词 / 替换原提示词”对现有系统提示词和 `model_instructions_file` 的实际影响。
|
||||
- 提示词注入页面继续沿用统一的当前状态展示,方便判断当前模板与启用方式是否一致。
|
||||
|
||||
### 修复 Bug
|
||||
|
||||
- 修复提示词启用方式说明不够直观的问题,减少误操作风险。
|
||||
|
||||
### 修复 Bug
|
||||
|
||||
- 修复相同 Base URL、API Key、模型但 TOML 内容不同的供应商可能同时显示“当前”的问题;现在优先按完整 live TOML 匹配唯一配置,并避免重复展示 detected custom 卡片。
|
||||
- 修复追加提示词后禁用会误影响用户原有规则的风险;禁用只删除 Codex-X 管理的 AGENTS 区块或指令文件,用户其他内容保持不变。
|
||||
- 修复并发操作在同一毫秒创建备份时可能发生临时文件名冲突的问题。
|
||||
- 修复切换 Skill / MCP 开关后条目因启用状态排序而跳到列表其他位置的问题。
|
||||
- 修复 macOS Overlay 标题栏无法拖动的问题:补齐 Tauri 2 的 `core:window:allow-start-dragging` capability,并统一顶部拖动区域样式。
|
||||
- 修复 Windows 桌面应用环境中因 PATH 不完整或 `codex.cmd` 无法直接执行而检测不到 Codex CLI 版本的问题;新增 npm、ChatGPT、Cursor、VS Code 和常见安装目录探测。
|
||||
|
||||
### 开发
|
||||
|
||||
- 将 `AGENTS.md` 纳入 Codex-X 备份与恢复流程。
|
||||
- 增加受管区块合并/卸载、GitHub 动态模板发现、完整 TOML 供应商匹配、追加/替换模式和 AGENTS 恢复测试。
|
||||
- 提示词“启用方式”增加说明,方便了解“保留原提示词”和“替换原提示词”的区别,并核对当前启用状态。
|
||||
- 修复配置相近的多个供应商可能同时显示“当前启用”、重复显示供应商卡片的问题。
|
||||
- 关闭追加的提示词时会保留用户原有规则,自定义规则也支持备份和恢复。
|
||||
- 修复多项操作同时备份时可能失败的问题。
|
||||
- 修复切换 Skill 或 MCP 开关后,条目跳到列表其他位置的问题。
|
||||
- 修复 macOS 窗口顶部无法拖动的问题,并改善 Windows 上 Codex 版本的识别。
|
||||
|
||||
## [v0.2.31] - 2026-07-09
|
||||
|
||||
### 更新
|
||||
|
||||
- 调整 macOS Toast 展示位置:Toast 现在直接挂在窗口根层,不再被内容区域下移影响,提示位置更靠上、更自然。
|
||||
- 优化 Skills ZIP 安装体验:从 ZIP 安装 Skill 时会读取 `SKILL.md` 里的真实 `name` / `description`,不再显示 `skill-zip-时间戳` 这类临时目录名。
|
||||
- Skills 页面刷新时会自动识别旧版 `skill-zip-*` 目录,并尝试重命名为 Skill 自身名称。
|
||||
|
||||
### 修复 Bug
|
||||
|
||||
- 修复启用第三方供应商后,关闭并重新打开 Codex-X 不再显示“当前启用”的问题。
|
||||
- 修复 Windows / Linux 上供应商编辑页无法正常下拉滚动的问题,编辑 `config.toml` 时不再需要用 PageDown 绕过。
|
||||
- 修复 Toast 受内容容器 `contain` 影响导致 macOS 位置调整不生效的问题。
|
||||
|
||||
### 开发
|
||||
|
||||
- 增加 Skill 元数据读取与旧 ZIP Skill 目录自动修正的单元测试。
|
||||
- 调整 macOS 顶部通知的位置,避免提示随页面内容下移。
|
||||
- 从 ZIP 安装 Skill 后显示其实际名称和说明;刷新时会尝试修正旧版安装留下的临时名称。
|
||||
- 修复启用第三方供应商后,重新打开 Codex-X 不再显示“当前启用”的问题。
|
||||
- 修复 Windows 和 Linux 供应商编辑页无法正常向下滚动的问题。
|
||||
|
||||
## [v0.2.30] - 2026-07-09
|
||||
|
||||
### 更新
|
||||
|
||||
- 优化会话管理页面布局:同步状态、目标 Provider、聊天总数、已展示数量、需修复数量合并为紧凑信息栏,把更多空间留给会话列表。
|
||||
- 会话管理新增“启动自动修复”开关:开启后,Codex-X 启动时会在后台检查本地会话完整性,发现未同步会自动修复,不阻塞界面。
|
||||
- 优化按钮点击体验:移除容易造成 WebView 闪烁/掉帧的水波纹、位移和 filter 效果,点击反馈更轻、更稳。
|
||||
|
||||
### 修复 Bug
|
||||
|
||||
- 修复同名供应商可能同时显示为“当前启用”的问题;Codex-X 现在会记录最后启用的供应商 ID,避免第三方 live Provider 都是 `custom` 时出现双亮。
|
||||
- 修复新增同名供应商时 ID 冲突的问题;新建供应商会自动生成唯一 ID。
|
||||
- 修复提示词管理中同名/同文件名 md 可能同时显示为启用的问题;新增或导入提示词会自动生成唯一文件名,当前状态按实际启用文件精确匹配。
|
||||
- 修复会话管理中会话选择反馈不明显的问题;已选数量和可修复数量会实时展示。
|
||||
|
||||
### 体验
|
||||
|
||||
- 进一步降低供应商、提示词、TOML、会话管理等页面滚动时的闪烁和低帧率感。
|
||||
|
||||
- 精简会话管理顶部信息栏,为会话列表留出更多空间;选择会话时实时显示已选数量和可修复数量。
|
||||
- 新增“启动自动修复”开关,开启后会在启动时后台检查会话,并自动修复未同步的会话,不影响界面操作。
|
||||
- 减少按钮点击和页面滚动时的闪烁、卡顿。
|
||||
- 修复同名供应商可能同时显示“当前启用”,以及新增同名供应商发生冲突的问题。
|
||||
- 修复同名提示词可能同时显示为启用的问题。
|
||||
|
||||
## [v0.2.29] - 2026-07-07
|
||||
|
||||
### 更新
|
||||
|
||||
- 优化 Toast 提示样式:改为窗口顶部居中的产品化通知卡片,减少遮挡右上角操作按钮。
|
||||
- Provider 连接测试文案改为简洁结果:成功显示“连接正常(耗时)”,失败显示 HTTP 状态与耗时。
|
||||
- 第三方供应商编辑页支持保存 TOML 模板;点击“保存”只保存配置,点击“启用”时才写入 Codex live config。
|
||||
- 技能和 MCP 页面“导入已有”改为先展示预览确认弹窗,列出将导入的 Skills / MCP,用户确认后才执行导入。
|
||||
|
||||
### 修复 Bug
|
||||
|
||||
- 修复 Codex 第三方 API auth 写入错误:`auth.json` 现在写入 Codex 实际识别的 `auth_mode = "apikey"`,避免桌面端回到登录页。
|
||||
- 修复官方认证编辑页打开时会静默加载 cc-switch 旧 token,导致新登录账号 token 显示不更新的问题;现在默认读取 live `~/.codex/auth.json`,并提供“刷新当前 auth.json”。
|
||||
- 修复切换到 OpenAI Official 时可能覆盖当前 live auth.json 的问题,避免把旧账号登录态写回。
|
||||
- 修复 Provider 测试把 HTTP 403 误判为“连接正常”的问题;现在只有 2xx 状态会显示成功。
|
||||
- 修复从 cc-switch 导入 Provider 时同名同 URL 供应商可能产生重复卡片的问题。
|
||||
- 修复 SQLite 轻量迁移重复执行时 `duplicate column name: toml_config` 导致启动报错的问题。
|
||||
|
||||
### 开发
|
||||
|
||||
- 增加 Provider/auth 相关单元测试,覆盖第三方切换、官方 auth 保留、403 判定和 cc-switch 导入串台场景。
|
||||
|
||||
- 通知改为顶部居中显示,减少对右上角按钮的遮挡;供应商连接测试结果更简洁,显示连接状态和耗时。
|
||||
- 第三方供应商支持保存配置模板:“保存”只保存配置,点击“启用”后才应用到 Codex。
|
||||
- Skills 和 MCP 的“导入已有”增加预览,确认列表后才执行导入。
|
||||
- 修复切换第三方供应商后 Codex 可能回到登录页的问题。
|
||||
- 官方认证编辑页默认读取当前登录信息,并提供“刷新当前 auth.json”;修复切回官方登录时可能恢复成旧账号的问题。
|
||||
- 修复连接测试将“访问被拒绝”误报为连接正常,以及从 cc-switch 导入时出现重复供应商卡片的问题。
|
||||
- 修复部分用户升级后无法启动的问题。
|
||||
|
||||
## [v0.2.28] - 2026-07-07
|
||||
|
||||
- 修复从 cc-switch 导入 Codex Provider 时可能把供应商名称、base_url 与 API Key 串台的问题。
|
||||
- 导入 cc-switch Provider 时改为先扫描所有 `[model_providers.<id>]` section,再按 provider row id 精确匹配,避免使用过期的 `model_provider` active 值。
|
||||
- 兼容 cc-switch legacy `custom` provider 模板,同时保留 `experimental_bearer_token` 兜底。
|
||||
- 增加复现 Sky2api / MagicAI 交叉配置的单元测试,防止 Provider 切换再次出现“看起来切了但实际没切对”的问题。
|
||||
- 修复从 cc-switch 导入供应商时,名称、API 地址和密钥可能相互混淆的问题,避免启用后实际使用了其他供应商。
|
||||
- 改善旧版 cc-switch 供应商配置的导入兼容性。
|
||||
|
||||
## [v0.2.27] - 2026-07-07
|
||||
|
||||
- 优化【指令提示词】页面为 Skills/MCP 风格的简洁列表:左侧显示模板名称与说明,右侧使用开启/关闭切换;自定义/导入的 md 提示词增加编辑与删除图标。
|
||||
- 优化【供应商】页面操作区:移除“官方配置 / 本地保存 / gpt-5.5 / 不支持路由”等冗余信息,将切换改为“启用”,编辑/删除/测试连接改为图标按钮。
|
||||
- 新增供应商 base_url 连通性测试按钮,方便切换前检查第三方 API 地址是否可达。
|
||||
- 修复第三方 Provider 切换后可能未真正生效的问题:切换和保存 TOML 时会写入 Codex 实际读取的 `experimental_bearer_token`。
|
||||
- 对齐 cc-switch 的 Codex Provider live config 思路:从 cc-switch 导入时会识别 `experimental_bearer_token`,并避免使用 Codex 内置保留 provider id。
|
||||
- 优化启动加载链路:启动诊断、备份列表、会话同步状态改为后台刷新,减少首屏等待。
|
||||
- 提示词页面改为简洁列表,名称和说明更清晰,右侧可直接开关;自定义和导入的提示词支持编辑、删除。
|
||||
- 精简供应商操作区,将“切换”改为“启用”,编辑、删除和连接测试改为图标按钮。
|
||||
- 新增供应商连接测试,方便启用前检查第三方 API 地址是否可用。
|
||||
- 修复第三方供应商切换后可能未真正生效的问题,并改善从 cc-switch 导入配置的兼容性。
|
||||
- 减少启动等待,检查、备份列表和会话状态在后台加载。
|
||||
|
||||
## [v0.2.26] - 2026-07-07
|
||||
|
||||
- 修复第三方 Provider 切换后可能“看起来已切换但实际未按新供应商生效”的问题:不再把所有第三方都写成 `model_provider = "custom"`,而是写入供应商自己的稳定 ID。
|
||||
- 修复从官方 ChatGPT 登录态切到第三方 API Key 时 `auth.json` 仍保留 `auth_mode = "chatgpt"` 的问题;写入 API Key 时会同步设置 `auth_mode = "apikey"`。
|
||||
- 第三方供应商默认不再要求 OpenAI 登录态,避免新建/导入 Provider 时错误继承官方 auth 语义。
|
||||
- 增加 Provider 切换单元测试,覆盖真实 provider key 和 API Key auth mode 的落盘结果。
|
||||
- 修复第三方供应商显示已切换、实际却未生效的问题。
|
||||
- 修复从官方登录切换到第三方 API 密钥后,仍沿用官方登录方式的问题。
|
||||
- 新增或导入第三方供应商时,默认不再要求 OpenAI 官方登录。
|
||||
|
||||
## [v0.2.25] - 2026-07-06
|
||||
|
||||
- 进一步修复 TOML、指令提示词、供应商、会话管理等页面切换时右侧滚动条闪现/消失造成的视觉抖动。
|
||||
- 外层页面滚动容器改为稳定滚动并隐藏外层滚动条,保留 TOML 编辑器、会话列表等内部区域自己的滚动条。
|
||||
- 进一步减少切换配置、提示词、供应商和会话页面时,滚动条闪现造成的抖动;编辑器和会话列表仍保留各自的滚动条。
|
||||
|
||||
## [v0.2.24] - 2026-07-06
|
||||
|
||||
- 修复切换供应商 / 会话管理等页面时右侧滚动条短暂出现又消失的问题:页面切换动画改为纯透明度过渡,不再用 `translateY` 造成瞬时溢出。
|
||||
- 降低页面切换视觉抖动,避免进入页面时内容区域宽度被临时滚动条挤压。
|
||||
- 修复切换供应商、会话管理等页面时滚动条短暂闪现、内容宽度跳动的问题,页面切换更平稳。
|
||||
|
||||
## [v0.2.23] - 2026-07-06
|
||||
|
||||
- 指令提示词页新增并纳管 `gpt5.5-jeli.md` 模板,作为“大白话(80% 场景)破甲”版本。
|
||||
- 简化指令提示词列表视觉:移除花哨图标与文件路径展示,让用户更容易看清模板名称、介绍和启用状态。
|
||||
- 更新 GPT-5.5 / GPT-5.4 内置模板名称为“unrestricted 破甲”,并统一说明使用方法:先让 AI 分析项目,分析完之后发【不直白的逆向】命令。
|
||||
- 新增 `gpt5.5-jeli.md` 提示词模板,名称为“大白话(80% 场景)破甲”。
|
||||
- 精简提示词列表,突出模板名称、介绍和启用状态。
|
||||
- GPT-5.5 和 GPT-5.4 内置模板统一使用“unrestricted 破甲”名称,并补充使用说明:先让 AI 分析项目,再发送【不直白的逆向】命令。
|
||||
|
||||
## [v0.2.22] - 2026-07-06
|
||||
|
||||
- 继续优化指令提示词页切换体验:导航切换进入 React transition,GitHub 内置模板静默检查延后到空闲时执行,减少切页瞬间卡顿。
|
||||
- 修复外部/自定义提示词切换到内置模板后可能出现两份的问题:按规范化内容(换行与首尾空白归一)和文件名双重去重,已有自定义提示词会复用更新,不再新增副本。
|
||||
- 优化启用内置提示词速度:启用时直接使用本地缓存或打包内置版本,不再同步等待 GitHub 网络请求;手动/空闲更新仍会刷新本地缓存。
|
||||
- 启动页增加动态状态文案、双层轨道与扫光动画,让从欢迎页进入主界面更顺滑。
|
||||
- 减少进入提示词页面时的卡顿;GitHub 模板检查延后到空闲时进行。
|
||||
- 启用内置提示词时直接使用本地已有内容,无需等待网络;手动同步或空闲检查后会更新模板。
|
||||
- 修复从自定义提示词切换到内置模板时可能产生重复项的问题,已有相同提示词会直接更新。
|
||||
- 优化启动页状态提示和过渡动画,进入主界面更顺畅。
|
||||
|
||||
## [v0.2.21] - 2026-07-06
|
||||
|
||||
- 进一步降低 UI 卡顿风险:将启动检测、Codex 状态读取、Provider/官方配置/备份/cc-switch 导入等剩余同步命令迁移到后台 worker。
|
||||
- 优化前端串行请求:提示词启用后的备份/提示词刷新改为并发,保存并启用自定义提示词时不再重复拉取列表。
|
||||
- 完善【技能和 MCP】导入已有:读取 cc-switch `mcp_servers` 数据库,按 `enabled_codex` 纳管并同步到 Codex `config.toml [mcp_servers]`。
|
||||
- 增强 Skills 检查更新:对带有 cc-switch 仓库元数据的 Skill 拉取 GitHub 仓库 ZIP 计算远程 hash,显示“有新版本 / 已是最新 / 远程检查失败”等状态。
|
||||
- 减少启动、供应商操作、备份和导入时的卡顿,并加快提示词保存、启用后的刷新。
|
||||
- “导入已有”支持从 cc-switch 导入已为 Codex 启用的 MCP,并应用到 Codex。
|
||||
- 来自 cc-switch 且保留仓库信息的 Skill 可检查 GitHub 更新,显示“有新版本”“已是最新”或“远程检查失败”。
|
||||
|
||||
## [v0.2.20] - 2026-07-06
|
||||
|
||||
- 继续优化指令提示词页性能:提示词列表/状态读取、保存、导入、启用、禁用等后端操作改为后台 worker,避免切页或启用模板时阻塞 UI。
|
||||
- 修复外部自定义提示词重复保存问题:切换到内置模板前会按文件名与内容双重去重,并自动清理历史 `external-*` 重复项。
|
||||
- 优化启动加载体验:启动页增加最短展示、退出淡出与动态过渡,避免从欢迎页突然跳到主页。
|
||||
- 改善提示词页面响应速度,减少切换页面、保存、导入和开关模板时的卡顿。
|
||||
- 修复从自定义提示词切换到内置模板后重复保存的问题,并自动整理已有的此类重复项。
|
||||
- 优化启动页展示和退出动画,避免突然跳到主页。
|
||||
|
||||
## [v0.2.19] - 2026-07-06
|
||||
|
||||
- 新增【技能和 MCP】页面:展示 Codex 当前已安装 Skills 与 MCP,支持导入已有、从 ZIP 安装 Skill、启用/禁用 Skill、启用/禁用 MCP。
|
||||
- MCP 管理会读写 `~/.codex/config.toml` 的 `[mcp_servers]`,禁用后保留到 Codex-X SQLite,后续可一键重新启用。
|
||||
- Skills 管理会扫描 `~/.codex/skills`,并可从 `~/.agents/skills`、`~/.cc-switch/skills` 导入到 Codex;禁用后移动到 Codex-X 禁用目录,避免直接删除。
|
||||
- 优化多个潜在卡顿点:指令提示词 GitHub 检查改为延迟后台执行,远程拉取、会话扫描/同步、Skills/MCP 扫描均放入后台 blocking worker。
|
||||
- 修复外部自定义提示词切换到内置提示词后重复出现的问题,并自动清理同名 `external-*` 重复项。
|
||||
- 增加页面切换过渡、启动页动态光效和首次启动向导退出动画,降低页面突然跳转感。
|
||||
- 新增【技能和 MCP】页面,可查看已安装内容、导入已有配置、从 ZIP 安装 Skill,以及启用或禁用 Skill 和 MCP。
|
||||
- 禁用 Skill 或 MCP 后仍保留原有内容,可随时重新启用;支持导入本机已有的 Skill 和 cc-switch 中的技能。
|
||||
- 减少 GitHub 模板检查、会话检查与同步、Skills 和 MCP 加载时的卡顿。
|
||||
- 修复从自定义提示词切换到内置模板后出现重复项的问题,并自动整理已有的同名重复项。
|
||||
- 优化页面切换、启动页和首次启动向导的过渡动画。
|
||||
|
||||
## [v0.2.18] - 2026-07-05
|
||||
|
||||
- 指令提示词内置模板支持从 GitHub `examples/` 实时检查更新,并缓存到本地;启用内置模板时优先使用 GitHub 最新版本,离线时自动回退本地缓存或打包内置版本。
|
||||
- 指令提示词页面新增“更新内置模板”状态与来源展示,可看到模板来自 GitHub 最新、本地缓存或打包内置。
|
||||
- 继续保留导入 `.md` 提示词、外部提示词自动记忆、会话管理交互优化和 API Key 可见切换等体验改进。
|
||||
- 内置提示词支持从 GitHub 检查更新,启用时优先使用最新模板;离线时可使用本地缓存或随应用提供的模板。
|
||||
- 提示词页面新增更新状态和模板来源提示。
|
||||
|
||||
## [v0.2.17] - 2026-07-04
|
||||
|
||||
- 修复 macOS Intel Release 构建 runner:从已不可用/长时间排队的 `macos-13` 切换为 `macos-15-intel`。
|
||||
- 继续保留 macOS Apple Silicon / macOS Intel / Windows MSI / Windows portable ZIP / Linux deb/rpm 多平台产物。
|
||||
- 修复 Intel Mac 安装包发布失败或长时间等待的问题。
|
||||
|
||||
## [v0.2.16] - 2026-07-04
|
||||
|
||||
- Release 新增 macOS Intel 构建,Intel Mac 用户可下载 x64 DMG。
|
||||
- macOS Release 现在同时提供 Apple Silicon 与 Intel 两种 DMG。
|
||||
- Windows Release 新增 portable ZIP,包含可直接运行的 `Codex-X.exe`,无需 MSI 安装。
|
||||
- 发布流程支持上传 `.zip` portable 产物,并更新 README 下载说明。
|
||||
- 新增 Intel Mac 版 DMG,macOS 用户可按芯片类型选择 Intel 或 Apple Silicon 安装包。
|
||||
- 新增 Windows 免安装 ZIP,解压后即可运行,无需安装 MSI。
|
||||
|
||||
## [v0.2.15] - 2026-07-04
|
||||
|
||||
- 会话管理页移除 CODEX_HOME 与 Provider Sync 备份位置展示,页面信息更简洁。
|
||||
- 优化 Windows 打开下载页体验:后端改为后台线程 spawn 浏览器,不再等待 `cmd /C start`,避免 WebView 卡顿 2-3 秒。
|
||||
- 统一所有外部链接按钮走异步打开逻辑,打开项目主页、反馈页、下载页都不会阻塞界面。
|
||||
- 修复 macOS 顶部 toast 被 Overlay 标题栏遮挡的问题,toast 自动下移到标题栏安全区下方。
|
||||
- 精简会话管理页面,移除不常用的配置和备份位置说明。
|
||||
- 修复 Windows 打开下载页、项目主页等外部链接时界面短暂卡顿的问题。
|
||||
- 修复 macOS 顶部提示消息被标题栏遮挡的问题。
|
||||
|
||||
## [v0.2.14] - 2026-07-04
|
||||
|
||||
- 修复 macOS Overlay 标题栏遮挡内容的问题,为红黄绿窗口按钮预留完整安全区。
|
||||
- 调整侧边栏、内容区、Provider/TOML/指令提示词/会话管理页高度计算,避免顶部内容被标题栏压住。
|
||||
- 加高 macOS 顶部拖拽区域并保持深色渐变,窗口顶部继续和应用色系统一。
|
||||
- 修复 macOS 标题栏和窗口按钮遮挡页面内容的问题。
|
||||
- 增大窗口顶部拖拽区域,并统一深色外观。
|
||||
|
||||
## [v0.2.13] - 2026-07-04
|
||||
|
||||
- macOS 窗口标题栏改为深色融合样式,避免顶部出现系统白色标题条。
|
||||
- 会话管理页面移除多余外层玻璃边框,统一为完整内容容器。
|
||||
- 优化会话列表边界与滚动区域,避免列表像卡在外层框外面。
|
||||
- macOS 标题栏改为与应用一致的深色样式。
|
||||
- 简化会话管理页面边框,改善列表布局和滚动体验。
|
||||
|
||||
## [v0.2.12] - 2026-07-04
|
||||
|
||||
- Windows MSI 安装器回退为默认简洁样式,移除上一版过重的自定义安装界面图。
|
||||
- 【会话管理】页面新增会话列表,展示标题、Provider、模型、工作目录、更新时间、归档/需同步状态。
|
||||
- 会话扫描会从 Codex 本地 SQLite threads 表读取最近会话,方便用户直接判断哪些历史 thread 需要同步修复。
|
||||
- Windows MSI 恢复简洁的安装界面。
|
||||
- 会话管理新增历史会话列表,可查看标题、供应商、模型、工作目录、更新时间,以及归档和待同步状态。
|
||||
|
||||
## [v0.2.11] - 2026-07-04
|
||||
|
||||
- 调整首次启动自动检查更新体验:不再弹出居中的强提醒窗口。
|
||||
- 自动检测到新版本时仅显示轻量 toast,并保留概览页顶部“发现新版本”提示条。
|
||||
- 只有用户在【关于】页面主动点击“检查更新”时,检测到新版本才弹出“现在下载 / 稍后”窗口。
|
||||
- 启动时发现新版本改为轻量提示,概览页仍保留更新提示条。
|
||||
- 仅在“关于”页面主动检查更新并发现新版本时,弹出“现在下载 / 稍后”窗口。
|
||||
|
||||
## [v0.2.10] - 2026-07-04
|
||||
|
||||
- 修复 Release 发布任务上传 Linux 产物时误把 `deb/`、`rpm/` 目录当作资产上传的问题。
|
||||
- 发布任务现在只收集 `.dmg` / `.msi` / `.deb` / `.rpm` 文件并统一上传。
|
||||
- 补齐稳定的三平台 Release 自动发布流程。
|
||||
- 修复 Linux 安装包上传失败的问题,完善 macOS、Windows 和 Linux 安装包发布。
|
||||
|
||||
## [v0.2.9] - 2026-07-04
|
||||
|
||||
- 修复 GitHub Actions Release 发布流程:不再由三平台矩阵并发创建 Release,改为先上传构建产物,再由单独发布任务统一创建/更新 Release。
|
||||
- 修复 `Resource not accessible by integration` 导致 Release 创建失败的问题。
|
||||
- Release 仍会从 `CHANGELOG.md` 自动读取当前 tag 的更新日志,并上传 macOS / Windows / Linux 安装包。
|
||||
- 修复 GitHub 版本发布失败的问题。
|
||||
|
||||
## [v0.2.8] - 2026-07-04
|
||||
|
||||
- 更新页进一步产品化:去掉资源/仓库调试信息,将“有更新”改为更明显的绿色标签。
|
||||
- 概览页顶部新增轻量“发现新版本”提示条,可直接打开 Releases 页面。
|
||||
- 新增【会话管理】页面:检查 Codex 本地 sessions / archived_sessions 与 SQLite threads 是否和当前 Provider 同步。
|
||||
- 新增一键 Provider Sync / 修复历史会话:写入前备份到 `~/.codex/backups_state/provider-sync/`,并保留最近 5 份备份。
|
||||
- 简化更新页面,使用醒目的绿色标签标示新版本;概览页新增可直接打开下载页的更新提示条。
|
||||
- 新增“会话管理”页面,可检查历史会话是否与当前供应商匹配,并一键同步修复。
|
||||
- 修复会话前自动备份,保留最近 5 份备份。
|
||||
|
||||
## [v0.2.7] - 2026-07-04
|
||||
|
||||
- 简化更新检查页展示。
|
||||
- “打开下载页”改为打开 GitHub Releases 页面。
|
||||
- 更新弹窗保持简洁,仅提示版本差异。
|
||||
- 首次启动自动检查更新并弹窗提醒。
|
||||
- 简化更新页面和弹窗,“打开下载页”直接前往 GitHub 版本下载页面。
|
||||
- 首次启动自动检查更新,发现新版本时弹窗提醒。
|
||||
|
||||
## [v0.2.5] - 2026-07-04
|
||||
|
||||
- Windows 版双击启动不再额外弹出终端窗口。
|
||||
- 改进 Windows MSI 安装器品牌展示与图标。
|
||||
- About 页面外部链接改为系统默认浏览器打开。
|
||||
- Release 流程加入 Rust cache,后续构建更快。
|
||||
- 修复 Windows 双击启动时额外弹出终端窗口的问题。
|
||||
- 改善 Windows MSI 安装界面的应用名称和图标展示。
|
||||
- “关于”页面的外部链接使用系统默认浏览器打开。
|
||||
|
||||
## [v0.2.4] - 2026-07-04
|
||||
|
||||
- 美化 Windows MSI 安装器横幅与对话图。
|
||||
- Windows 安装包加入应用图标。
|
||||
- 美化 Windows MSI 安装界面,并为安装包加入应用图标。
|
||||
|
||||
## [v0.2.3] - 2026-07-04
|
||||
|
||||
- 修复 macOS DMG 中应用图标缺失问题。
|
||||
- 补充 macOS 安装说明。
|
||||
- Release 流程加入基础缓存优化。
|
||||
- 修复 macOS DMG 中应用图标缺失的问题,并补充安装说明。
|
||||
|
||||
## [v0.2.2] - 2026-07-04
|
||||
|
||||
- macOS / Linux / Windows 首次三平台 Release。
|
||||
- Linux 产物改为 `deb` / `rpm`,避免 AppImage 图标问题。
|
||||
- 首次提供 macOS、Linux 和 Windows 三个平台的安装包。
|
||||
- Linux 改为提供 DEB 和 RPM 安装包。
|
||||
|
||||
## [v0.2.1] - 2026-07-04
|
||||
|
||||
- 首次加入应用图标与 GitHub Release 自动发布。
|
||||
- 首次加入应用图标,并通过 GitHub 提供版本下载。
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
**Codex Prompts · API / Providers · Sessions · Skills / MCP in One Place**
|
||||
|
||||
A cross-platform desktop tool for **OpenAI Codex Desktop / Codex CLI**. Manage prompt templates, switch third-party APIs, organize / repair / permanently delete local sessions, manage Skills / MCP, apply macOS / Windows skins, and inspect TOML and login credentials without repeatedly editing configuration files by hand.
|
||||
A cross-platform desktop tool for **OpenAI Codex Desktop / Codex CLI**. Manage prompt templates, switch third-party APIs, organize / repair / permanently delete local sessions, manage Skills / MCP, and inspect TOML and login credentials without repeatedly editing configuration files by hand.
|
||||
|
||||
<p>
|
||||
<img src="https://img.shields.io/github/v/release/yynxxxxx/Codex-X?label=version&color=blue" alt="version" />
|
||||
@@ -37,9 +37,10 @@ When you use Codex Desktop, the CLI, third-party APIs, and multiple prompts toge
|
||||
You can use it to:
|
||||
|
||||
- Choose from the prompt library or import your own `.md`, then keep the existing prompt or replace it
|
||||
- Save, test, and switch between OpenAI Official and third-party APIs, including Providers imported from cc-switch
|
||||
- Manage multiple named official Codex login profiles and third-party APIs, duplicate or switch them with a click, and import Providers from cc-switch
|
||||
- Search and organize local sessions by project, check / automatically repair problems, and precisely delete sessions you no longer need
|
||||
- Manage Skills and MCP in one place, and inspect the current `config.toml`, `auth.json`, and operation backups
|
||||
- Explore token usage by date and model in Settings, with subagent usage attributed to its main conversation
|
||||
|
||||
## Preview
|
||||
|
||||
@@ -117,7 +118,7 @@ You can use it to:
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">⚡ <b>Switch APIs / relays</b></td>
|
||||
<td align="left">Save, test, and enable multiple third-party Providers, or import them from cc-switch; entries with the same endpoint and Key are merged automatically. Create or reopen a session after switching to apply the change without restarting the entire Codex client.</td>
|
||||
<td align="left">Save multiple named official Codex login profiles alongside third-party Providers, with one-click duplication and switching. Third-party Providers support connection checks, model discovery / testing, and imports from cc-switch.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">💬 <b>Organize local sessions</b></td>
|
||||
@@ -129,11 +130,11 @@ You can use it to:
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">📝 <b>Manage config and login</b></td>
|
||||
<td align="left">Inspect the active Codex <code>config.toml</code> and <code>auth.json</code> in one place, with a clear distinction between official login credentials and third-party API Keys. Important writes are backed up automatically and can be restored when needed.</td>
|
||||
<td align="left">Inspect <code>config.toml</code> and <code>auth.json</code> in one place. Both official and third-party profile editors offer an “Enable 1M context window” checkbox beside <code>config.toml>; it applies on save and requires model support. Important writes are backed up automatically.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">🎨 <b>Apply macOS / Windows skins</b></td>
|
||||
<td align="left">Use the bundled Shiina Mashiro art-studio theme with real-wallpaper, full-interface previews. Import or export packs, hot-switch themes, and turn the skin off directly. The runtime is built into Codex-X; the separate Codex Dream Skin engine is not required.</td>
|
||||
<td align="center">📊 <b>Track token usage</b></td>
|
||||
<td align="left">Switch between General and Usage statistics in Settings. Filter local usage by date and model, explore daily trends, cache hit rate, and model distribution, and view the 10 most recent main conversations. Subagent usage is attributed to its main conversation and does not count as a separate session.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">📦 <b>Use it across platforms</b></td>
|
||||
@@ -147,7 +148,7 @@ You can use it to:
|
||||
### 1. Prompt Template Center
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/Template_library-5_total-2563eb?style=flat-square" alt="5 templates in the current library" />
|
||||
<img src="https://img.shields.io/badge/Template_library-11_total-2563eb?style=flat-square" alt="11 templates in the current library" />
|
||||
<img src="https://img.shields.io/badge/Bundled_offline-5_templates-16a34a?style=flat-square" alt="5 templates bundled for offline use" />
|
||||
<img src="https://img.shields.io/badge/GitHub_sync-Automatic_updates-f59e0b?style=flat-square" alt="Automatic GitHub template sync" />
|
||||
</p>
|
||||
@@ -155,7 +156,7 @@ You can use it to:
|
||||
> [!TIP]
|
||||
> **Ready after installation, automatically expanded when online.**
|
||||
>
|
||||
> The app bundle includes all 5 current templates for offline use. After launch, it synchronizes updates and newly added templates from GitHub `examples/` in the background, without waiting for the **Prompt** page to open. Successfully synchronized online versions are cached locally and remain available during temporary network outages.
|
||||
> The app bundle includes 5 templates for offline use. After launch, it synchronizes 6 additional software-development and writing templates, plus later updates, from GitHub `examples/` in the background without waiting for the **Prompt** page to open. Successfully synchronized online versions are cached locally and remain available during temporary network outages.
|
||||
|
||||
<div align="center">
|
||||
<table>
|
||||
@@ -189,6 +190,36 @@ You can use it to:
|
||||
<td align="left">A Chinese technical-operator persona with routing for coding, CTF, reverse engineering, memory, and protocol work</td>
|
||||
<td align="center">Bundled offline<br />GitHub updates</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/software-development-maintainer.md"><code>software-development-maintainer.md</code></a></td>
|
||||
<td align="left">Long-term maintenance with reuse, minimal changes, safety, testing, and maintainability</td>
|
||||
<td align="center">GitHub sync</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/software-development-debugging.md"><code>software-development-debugging.md</code></a></td>
|
||||
<td align="left">Evidence-driven debugging from reliable reproduction to root-cause repair and regression checks</td>
|
||||
<td align="center">GitHub sync</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/software-development-code-review.md"><code>software-development-code-review.md</code></a></td>
|
||||
<td align="left">Severity-ranked review of defects, regressions, security risks, and test gaps</td>
|
||||
<td align="center">GitHub sync</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/writing-clarity-editor.md"><code>writing-clarity-editor.md</code></a></td>
|
||||
<td align="left">Chinese and English editing that preserves the author's meaning and facts</td>
|
||||
<td align="center">GitHub sync</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/writing-technical-docs.md"><code>writing-technical-docs.md</code></a></td>
|
||||
<td align="left">Source-grounded README, guide, API, architecture, and release documentation</td>
|
||||
<td align="center">GitHub sync</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/writing-structured-draft.md"><code>writing-structured-draft.md</code></a></td>
|
||||
<td align="left">Turns scattered material into a structured report, proposal, retrospective, or article draft</td>
|
||||
<td align="center">GitHub sync</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -212,7 +243,8 @@ A backup is created automatically before every enable or disable action. In addi
|
||||
> [!NOTE]
|
||||
> After enabling a new third-party Provider, create or reopen a Codex session to use the new relay. You do not need to restart the entire Codex client.
|
||||
|
||||
- Save multiple third-party Providers and always see which one is currently active
|
||||
- Save multiple named official Codex login profiles and third-party Providers, and always see which one is currently active
|
||||
- Duplicate a profile immediately with one click, without a confirmation dialog or opening the editor; rename it whenever needed
|
||||
- Test an API endpoint before switching, and save or enable a configuration separately
|
||||
- Edit the Base URL, API Key, Model, Wire API, and complete TOML on the same page
|
||||
- cc-switch imports report added, updated, merged, and skipped entries; the same URL + Key is no longer shown more than once
|
||||
@@ -375,15 +407,6 @@ pnpm --dir apps/desktop tauri build
|
||||
|
||||
## Desktop Installation Notes
|
||||
|
||||
### Skin Center security boundary
|
||||
|
||||
- Live skin application supports macOS and Windows. Linux can still manage, import, and export packs but is never reported as applied.
|
||||
- macOS uses only the signed Node.js bundled with the official Codex app and validates its bundle and process identity. Windows dynamically validates the current user's registered `OpenAI.Codex` Store package and uses the pinned Node.js 22 runtime shipped with Codex-X releases.
|
||||
- CDP binds only to `127.0.0.1`; Codex-X does not modify the official `.app`, `WindowsApps`, `app.asar`, code signature, directory permissions, or `config.toml`.
|
||||
- First application usually asks to restart Codex. Turn off skin removes the live interface skin immediately, and any theme can be applied again later.
|
||||
- Themes adapt cropping from image dimensions and content. Subject-focused artwork can use `art.focusX`, `art.focusY` (`0` to `1`), and `art.safeArea` in `theme.json` for precise framing without generating duplicate images for the same theme.
|
||||
- Injection is based on the MIT-licensed [Fei-Away/Codex-Dream-Skin](https://github.com/Fei-Away/Codex-Dream-Skin) source. The pinned source and license notice are in `apps/desktop/src-tauri/resources/skin-runtime/NOTICE.md`.
|
||||
|
||||
If you see “app is damaged” when opening an unsigned / unnotarized DMG, this is normal macOS Gatekeeper behavior.
|
||||
|
||||
- Best option: sign and notarize with an Apple Developer ID
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
**Codex 可视化提示词注入 · Provider · 会话 · Skills / MCP 管理工具**
|
||||
|
||||
一款面向 **OpenAI Codex 桌面端 / Codex CLI** 的跨平台桌面工具。把提示词模板、自定义 Prompt、第三方 API 供应商、会话同步、Skills / MCP、macOS / Windows 皮肤和 TOML 配置都放进可视化界面里,不用反复手改文件。
|
||||
一款面向 **OpenAI Codex 桌面端 / Codex CLI** 的跨平台桌面工具。把提示词模板、自定义 Prompt、第三方 API 供应商、会话同步、Skills / MCP 和 TOML 配置都放进可视化界面里,不用反复手改文件。
|
||||
|
||||
<p>
|
||||
<img src="https://img.shields.io/github/v/release/yynxxxxx/Codex-X?label=version&color=blue" alt="version" />
|
||||
@@ -38,9 +38,10 @@
|
||||
|
||||
- 像管理插件一样管理提示词:分类、导入 Markdown、自定义编辑、一键启用 / 禁用
|
||||
- 内置 5 套提示词模板,同时支持用户把自己的提示词变成可视化模板库
|
||||
- 保存、测试并切换 OpenAI Official 与第三方 API,还能从 cc-switch 导入现有供应商
|
||||
- 管理多个可命名的官方 Codex 登录与第三方 API,一键复制、切换,并从 cc-switch 导入现有供应商
|
||||
- 同步、检查、搜索和删除本地会话,按项目路径整理 Codex 历史记录
|
||||
- 集中管理 Skills 与 MCP,查看当前 `config.toml`、`auth.json` 和操作备份
|
||||
- 在设置中按日期、模型查看 Token 用量趋势,子代理用量归入所属主会话
|
||||
|
||||
## 软件预览
|
||||
|
||||
@@ -97,7 +98,7 @@
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><b>Provider / API</b></td>
|
||||
<td align="left">添加、编辑、启用、删除第三方供应商;支持连接检测、模型获取 / 测试、从 cc-switch 导入,并可在 OpenAI Official 与中转 API 之间切换。</td>
|
||||
<td align="left">保存多个可命名的官方 Codex 登录配置,与第三方供应商统一管理、一键复制和切换;第三方供应商支持连接检测、模型获取 / 测试及从 cc-switch 导入。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><b>会话管理</b></td>
|
||||
@@ -109,15 +110,15 @@
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><b>配置与登录</b></td>
|
||||
<td align="left">集中查看 Codex 当前使用的 <code>config.toml</code> 与 <code>auth.json</code>,区分官方登录态和第三方 API Key;重要写入前自动备份。</td>
|
||||
<td align="left">集中查看 <code>config.toml</code> 与 <code>auth.json</code>;官方登录和第三方供应商编辑页均可在 <code>config.toml</code> 旁勾选“开启 1M 上下文窗口”,保存后生效,需模型支持;重要写入前自动备份。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><b>macOS / Windows 皮肤中心</b></td>
|
||||
<td align="left">内置“椎名真白·樱花画室”主题,以真实壁纸和完整界面缩略图展示主题效果,支持导入 / 导出、热切换和关闭皮肤;换肤运行时已经内置在 Codex-X 中,无需另装 Codex Dream Skin 引擎。</td>
|
||||
<td align="center"><b>用量统计</b></td>
|
||||
<td align="left">设置页提供“通用设置 / 用量统计”标签,按日期与模型筛选本地 Token 用量,查看每日趋势、缓存命中率、模型分布及最近 10 个主会话;子代理用量归入所属主会话,不单独计为会话。</td>
|
||||
</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>
|
||||
@@ -127,7 +128,7 @@
|
||||
### 1. 可视化提示词注入中心
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/当前模板库-5_套-2563eb?style=flat-square" alt="当前模板库 5 套" />
|
||||
<img src="https://img.shields.io/badge/当前模板库-11_套-2563eb?style=flat-square" alt="当前模板库 11 套" />
|
||||
<img src="https://img.shields.io/badge/离线内置-5_套-16a34a?style=flat-square" alt="离线内置 5 套" />
|
||||
<img src="https://img.shields.io/badge/GitHub_同步-自动更新-f59e0b?style=flat-square" alt="GitHub 自动同步" />
|
||||
<img src="https://img.shields.io/badge/自定义提示词-支持导入_编辑-7c3aed?style=flat-square" alt="支持自定义提示词" />
|
||||
@@ -136,7 +137,7 @@
|
||||
> [!TIP]
|
||||
> **安装后就能用,联网后自动补齐,也能维护自己的提示词库。**
|
||||
>
|
||||
> 安装包离线自带当前全部 5 套模板;软件启动后可同步 GitHub `examples/` 的更新和新增模板。同步成功的在线版本会缓存到本地,临时离线仍可继续使用。你也可以导入自己的 `.md`、新增分类、编辑说明,并像切换插件一样启用或禁用任意提示词。
|
||||
> 安装包离线自带 5 套模板;软件启动后会从 GitHub `examples/` 同步另外 6 套软件开发与写作辅助模板,以及后续更新。同步成功的在线版本会缓存到本地,临时离线仍可继续使用。你也可以导入自己的 `.md`、新增分类、编辑说明,并像切换插件一样启用或禁用任意提示词。
|
||||
|
||||
Codex-X 现在不只是“几套内置 Prompt”的启动器,而是一个可视化提示词注入与管理工具:
|
||||
|
||||
@@ -178,6 +179,36 @@ Codex-X 现在不只是“几套内置 Prompt”的启动器,而是一个可
|
||||
<td align="left">中文技术操作员人格,覆盖 coding、CTF、逆向、内存与协议任务路由</td>
|
||||
<td align="center">离线内置<br />GitHub 更新</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/software-development-maintainer.md"><code>software-development-maintainer.md</code></a></td>
|
||||
<td align="left">长期维护正式项目,强调复用、最小改动、安全、测试与可维护性</td>
|
||||
<td align="center">GitHub 在线同步</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/software-development-debugging.md"><code>software-development-debugging.md</code></a></td>
|
||||
<td align="left">从稳定复现和证据采集推进到根因修复与回归验证</td>
|
||||
<td align="center">GitHub 在线同步</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/software-development-code-review.md"><code>software-development-code-review.md</code></a></td>
|
||||
<td align="left">按严重级别审查缺陷、回归、安全风险和测试缺口</td>
|
||||
<td align="center">GitHub 在线同步</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/writing-clarity-editor.md"><code>writing-clarity-editor.md</code></a></td>
|
||||
<td align="left">在保留原意和事实的前提下润色中英文表达</td>
|
||||
<td align="center">GitHub 在线同步</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/writing-technical-docs.md"><code>writing-technical-docs.md</code></a></td>
|
||||
<td align="left">基于代码与事实编写 README、指南、API 和发布文档</td>
|
||||
<td align="center">GitHub 在线同步</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples/writing-structured-draft.md"><code>writing-structured-draft.md</code></a></td>
|
||||
<td align="left">将零散材料组织成报告、方案、复盘或文章初稿</td>
|
||||
<td align="center">GitHub 在线同步</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -204,7 +235,8 @@ Codex-X 现在不只是“几套内置 Prompt”的启动器,而是一个可
|
||||
> [!NOTE]
|
||||
> 启用新的第三方供应商后,新建或重新打开 Codex 会话即可使用新的中转,不需要重启整个 Codex 客户端。
|
||||
|
||||
- 保存多个第三方供应商,随时查看当前正在使用哪一个
|
||||
- 保存多个可命名的官方 Codex 登录配置与第三方供应商,随时查看当前正在使用哪一个
|
||||
- 点击“复制”直接新增独立副本,无需确认或进入编辑页;名称可稍后修改
|
||||
- 切换前可检测连接,并可获取模型进行测试
|
||||
- 在同一页面编辑 Base URL、API Key、Model、Wire API 和完整 TOML
|
||||
- 从 cc-switch 导入时自动区分新增、更新、合并与跳过;相同 URL + Key 不再重复显示
|
||||
@@ -303,7 +335,7 @@ Codex-X 现在不只是“几套内置 Prompt”的启动器,而是一个可
|
||||
|
||||
- macOS Apple Silicon `.dmg`
|
||||
- macOS Intel `.dmg`
|
||||
- Windows `.msi`
|
||||
- Windows `.exe`(安装到当前用户,后续更新无需管理员权限)
|
||||
- Windows Portable `.zip`
|
||||
- Linux `.deb` / `.rpm` / `.AppImage`
|
||||
- GitHub Releases 自动构建发布
|
||||
@@ -364,15 +396,6 @@ pnpm --dir apps/desktop tauri build
|
||||
|
||||
## 桌面端安装说明
|
||||
|
||||
### 皮肤中心安全边界
|
||||
|
||||
- 实机换肤支持 macOS 和 Windows;Linux 仍可管理、导入和导出主题包,但不会显示为已应用。
|
||||
- macOS 只使用官方 Codex 内置且签名一致的 Node.js,并校验 Bundle ID、代码签名和进程归属;Windows 动态校验当前用户注册的 `OpenAI.Codex` Store 包,并使用发布包内固定校验的 Node.js 22 运行时。
|
||||
- CDP 仅绑定 `127.0.0.1`,不修改官方 `.app`、`WindowsApps`、`app.asar`、代码签名、目录权限或 `config.toml`。
|
||||
- 首次应用通常需要确认重启 Codex;“关闭皮肤”会立即移除当前界面皮肤,之后可随时重新应用主题。
|
||||
- 主题默认会根据图片尺寸和内容自适应裁切;人物或主体构图可在 `theme.json` 使用 `art.focusX`、`art.focusY`(`0` 到 `1`)和 `art.safeArea` 精确控制,无需为同一主题重复生成图片。
|
||||
- 注入实现基于 [Fei-Away/Codex-Dream-Skin](https://github.com/Fei-Away/Codex-Dream-Skin) 的 MIT 源码,固定来源和许可见 `apps/desktop/src-tauri/resources/skin-runtime/NOTICE.md`。
|
||||
|
||||
如果你在未签名 / 未公证的 DMG 中看到“软件已损坏”提示,这是 macOS Gatekeeper 的正常行为。
|
||||
|
||||
- 最佳方式:使用 Apple Developer ID 签名并 notarize
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# Third-party notices
|
||||
|
||||
## CC Switch
|
||||
|
||||
Source: https://github.com/farion1231/cc-switch
|
||||
|
||||
Reference commit: `06082e189d65e6d6dbadc35dacdac1ce6c79d89a`.
|
||||
|
||||
Codex-X adapts the circuit-breaker implementation and Codex routing, failover, timeout and configuration behavior from CC Switch. The blocking/local HTTP integration, application state and UI styling are adapted to this project. Relevant source files carry provenance comments.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Jason Young
|
||||
|
||||
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.
|
||||
|
||||
## 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.1",
|
||||
"version": "0.3.24",
|
||||
"private": true,
|
||||
"description": "Codex Switch & Instruct desktop manager",
|
||||
"type": "module",
|
||||
@@ -10,12 +10,10 @@
|
||||
"tauri": "tauri",
|
||||
"dev:renderer": "vite --host 127.0.0.1 --port 1420",
|
||||
"build:renderer": "vite build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test:skin-runtime": "node src-tauri/resources/skin-runtime/tests/run-tests.mjs"
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.8.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.7.2",
|
||||
"@tauri-apps/plugin-process": "^2.3.1",
|
||||
"@tauri-apps/plugin-updater": "^2.10.1",
|
||||
"lucide-react": "^0.542.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Codex Dream Skin Studio contributors
|
||||
Copyright (c) 2023 LobeHub
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -0,0 +1,16 @@
|
||||
# Provider brand marks
|
||||
|
||||
These six unmodified SVG assets are from [Lobe Icons](https://github.com/lobehub/lobe-icons), licensed under the MIT License. The upstream copyright and permission notice is included in [LICENSE](./LICENSE).
|
||||
|
||||
Pinned upstream commit: `a94750e3f5f8fc33757b839d85030e742284e43a`.
|
||||
|
||||
| Local file | Upstream source |
|
||||
| --- | --- |
|
||||
| `deepseek.svg` | [packages/static-svg/icons/deepseek.svg](https://github.com/lobehub/lobe-icons/blob/a94750e3f5f8fc33757b839d85030e742284e43a/packages/static-svg/icons/deepseek.svg) |
|
||||
| `minimax.svg` | [packages/static-svg/icons/minimax.svg](https://github.com/lobehub/lobe-icons/blob/a94750e3f5f8fc33757b839d85030e742284e43a/packages/static-svg/icons/minimax.svg) |
|
||||
| `mimo.svg` | [packages/static-svg/icons/xiaomimimo.svg](https://github.com/lobehub/lobe-icons/blob/a94750e3f5f8fc33757b839d85030e742284e43a/packages/static-svg/icons/xiaomimimo.svg) |
|
||||
| `kimi.svg` | [packages/static-svg/icons/kimi.svg](https://github.com/lobehub/lobe-icons/blob/a94750e3f5f8fc33757b839d85030e742284e43a/packages/static-svg/icons/kimi.svg) |
|
||||
| `glm.svg` | [packages/static-svg/icons/zhipu.svg](https://github.com/lobehub/lobe-icons/blob/a94750e3f5f8fc33757b839d85030e742284e43a/packages/static-svg/icons/zhipu.svg) |
|
||||
| `qwen.svg` | [packages/static-svg/icons/qwen.svg](https://github.com/lobehub/lobe-icons/blob/a94750e3f5f8fc33757b839d85030e742284e43a/packages/static-svg/icons/qwen.svg) |
|
||||
|
||||
The monochrome SVGs are rendered as CSS masks so their color follows the preset card state. Brand names and marks identify their respective providers; they do not imply endorsement.
|
||||
@@ -0,0 +1 @@
|
||||
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>DeepSeek</title><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z"></path></svg>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
@@ -0,0 +1 @@
|
||||
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Zhipu</title><path d="M11.991 23.503a.24.24 0 00-.244.248.24.24 0 00.244.249.24.24 0 00.245-.249.24.24 0 00-.22-.247l-.025-.001zM9.671 5.365a1.697 1.697 0 011.099 2.132l-.071.172-.016.04-.018.054c-.07.16-.104.32-.104.498-.035.71.47 1.279 1.186 1.314h.366c1.309.053 2.338 1.173 2.286 2.523-.052 1.332-1.152 2.38-2.478 2.327h-.174c-.715.018-1.274.64-1.239 1.368 0 .124.018.23.053.337.209.373.54.658.96.8.75.23 1.517-.125 1.9-.782l.018-.035c.402-.64 1.17-.96 1.92-.711.854.284 1.378 1.226 1.099 2.167a1.661 1.661 0 01-2.077 1.102 1.711 1.711 0 01-.907-.711l-.017-.035c-.2-.323-.463-.58-.851-.711l-.056-.018a1.646 1.646 0 00-1.954.746 1.66 1.66 0 01-1.065.764 1.677 1.677 0 01-1.989-1.279c-.209-.906.332-1.83 1.257-2.043a1.51 1.51 0 01.296-.035h.018c.68-.071 1.151-.622 1.116-1.333a1.307 1.307 0 00-.227-.693 2.515 2.515 0 01-.366-1.403 2.39 2.39 0 01.366-1.208c.14-.195.21-.444.227-.693.018-.71-.506-1.261-1.186-1.332l-.07-.018a1.43 1.43 0 01-.299-.07l-.05-.019a1.7 1.7 0 01-1.047-2.114 1.68 1.68 0 012.094-1.101zm-5.575 10.11c.26-.264.639-.367.994-.27.355.096.633.379.728.74.095.362-.007.748-.267 1.013-.402.41-1.053.41-1.455 0a1.062 1.062 0 010-1.482zm14.845-.294c.359-.09.738.024.992.297.254.274.344.665.237 1.025-.107.36-.396.634-.756.718-.551.128-1.1-.22-1.23-.781a1.05 1.05 0 01.757-1.26zm-.064-4.39c.314.32.49.753.49 1.206 0 .452-.176.886-.49 1.206-.315.32-.74.5-1.185.5-.444 0-.87-.18-1.184-.5a1.727 1.727 0 010-2.412 1.654 1.654 0 012.369 0zm-11.243.163c.364.484.447 1.128.218 1.691a1.665 1.665 0 01-2.188.923c-.855-.36-1.26-1.358-.907-2.228a1.68 1.68 0 011.33-1.038c.593-.08 1.183.169 1.547.652zm11.545-4.221c.368 0 .708.2.892.524.184.324.184.724 0 1.048a1.026 1.026 0 01-.892.524c-.568 0-1.03-.47-1.03-1.048 0-.579.462-1.048 1.03-1.048zm-14.358 0c.368 0 .707.2.891.524.184.324.184.724 0 1.048a1.026 1.026 0 01-.891.524c-.569 0-1.03-.47-1.03-1.048 0-.579.461-1.048 1.03-1.048zm10.031-1.475c.925 0 1.675.764 1.675 1.706s-.75 1.705-1.675 1.705-1.674-.763-1.674-1.705c0-.942.75-1.706 1.674-1.706zm-2.626-.684c.362-.082.653-.356.761-.718a1.062 1.062 0 00-.238-1.028 1.017 1.017 0 00-.996-.294c-.547.14-.881.7-.752 1.257.13.558.675.907 1.225.783zm0 16.876c.359-.087.644-.36.75-.72a1.062 1.062 0 00-.237-1.019 1.018 1.018 0 00-.985-.301 1.037 1.037 0 00-.762.717c-.108.361-.017.754.239 1.028.245.263.606.377.953.305l.043-.01zM17.19 3.5a.631.631 0 00.628-.64c0-.355-.279-.64-.628-.64a.631.631 0 00-.628.64c0 .355.28.64.628.64zm-10.38 0a.631.631 0 00.628-.64c0-.355-.28-.64-.628-.64a.631.631 0 00-.628.64c0 .355.279.64.628.64zm-5.182 7.852a.631.631 0 00-.628.64c0 .354.28.639.628.639a.63.63 0 00.627-.606l.001-.034a.62.62 0 00-.628-.64zm5.182 9.13a.631.631 0 00-.628.64c0 .355.279.64.628.64a.631.631 0 00.628-.64c0-.355-.28-.64-.628-.64zm10.38.018a.631.631 0 00-.628.64c0 .355.28.64.628.64a.631.631 0 00.628-.64c0-.355-.279-.64-.628-.64zm5.182-9.148a.631.631 0 00-.628.64c0 .354.279.639.628.639a.631.631 0 00.628-.64c0-.355-.28-.64-.628-.64zm-.384-4.992a.24.24 0 00.244-.249.24.24 0 00-.244-.249.24.24 0 00-.244.249c0 .142.122.249.244.249zM11.991.497a.24.24 0 00.245-.248A.24.24 0 0011.99 0a.24.24 0 00-.244.249c0 .133.108.236.223.247l.021.001zM2.011 6.36a.24.24 0 00.245-.249.24.24 0 00-.244-.249.24.24 0 00-.244.249.24.24 0 00.244.249zm0 11.263a.24.24 0 00-.243.248.24.24 0 00.244.249.24.24 0 00.244-.249.252.252 0 00-.244-.248zm19.995-.018a.24.24 0 00-.245.248.24.24 0 00.245.25.24.24 0 00.244-.25.252.252 0 00-.244-.248z"></path></svg>
|
||||
|
After Width: | Height: | Size: 3.5 KiB |
@@ -0,0 +1 @@
|
||||
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Kimi</title><path d="M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z"></path><path d="M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z"></path></svg>
|
||||
|
After Width: | Height: | Size: 786 B |
@@ -0,0 +1 @@
|
||||
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>XiaomiMiMo</title><path d="M.958 15.936a.459.459 0 01.459.44v2.729a.46.46 0 01-.918 0v-2.729a.459.459 0 01.459-.44zm4.814-2.035a.46.46 0 01.553.45v4.754a.458.458 0 11-.918 0V15.48L3.74 17.202a.462.462 0 01-.655.016.462.462 0 01-.065-.082L.628 14.67a.459.459 0 01.658-.637l2.124 2.187 2.127-2.188a.46.46 0 01.235-.13zm2.068.004a.46.46 0 01.458.445v4.755a.46.46 0 01-.458.458.459.459 0 01-.458-.458V14.35a.459.459 0 01.458-.445zm1.973 2.014a.46.46 0 01.46.457v2.729a.46.46 0 01-.784.324.46.46 0 01-.134-.324v-2.729a.46.46 0 01.458-.458zm.002-2.045a.458.458 0 01.328.157l2.127 2.19 2.125-2.19a.459.459 0 01.784.318v4.756a.46.46 0 01-.455.458.46.46 0 01-.458-.458V15.48l-1.667 1.723a.46.46 0 01-.65.008l-.005-.005c0-.002-.002-.002-.004-.003l-2.455-2.534a.46.46 0 01-.008-.667.461.461 0 01.338-.128zm6.797 1.206a.46.46 0 01.53.651A1.966 1.966 0 0019.81 18.4a.462.462 0 01.623.18.46.46 0 01-.181.624 2.863 2.863 0 01-1.38.353l-.142-.004a2.88 2.88 0 01-2.393-4.263.461.461 0 01.274-.21zm.864-.931a2.884 2.884 0 013.915 3.914.46.46 0 01-.402.24l-.057-.004a.458.458 0 01-.164-.055.46.46 0 01-.182-.622 1.967 1.967 0 00-2.669-2.67.459.459 0 11-.441-.803zM9.59 6.368c1.481 0 1.696 1.202 1.696 1.654v2.648h-.917v-.432c-.26.346-.792.535-1.36.535-.133 0-1.289-.03-1.384-1.136-.082-.932.675-1.61 2.053-1.61h.691c0-.563-.367-.886-.983-.886-.44.013-.864.174-1.2.458l-.36-.664c.484-.379 1.012-.567 1.764-.567zm4.427.1c1.263 0 2.082.97 2.083 2.15 0 1.181-.824 2.154-2.083 2.154-1.26 0-2.084-.972-2.084-2.152 0-1.18.82-2.153 2.084-2.153zm6.801.015c.68 0 1.202.465 1.197 1.548v2.642H21.1V8.29c0-.312-.002-.98-.63-.98s-.628.667-.628.838v2.524h-.89V8.148c0-.17-.001-.838-.63-.838-.628 0-.628.668-.628.98v2.383h-.917v-4.03h.917V7a1.22 1.22 0 01.947-.516c.398 0 .76.193.982.686a1.321 1.321 0 011.195-.686zm-18.093.872l1.457-1.772H5.32L3.311 8.07l2.14 2.602H4.24L2.725 8.796 1.21 10.672H0L2.138 8.07.13 5.583h1.138l1.458 1.772zm4.149 3.317h-.916V6.644h.916v4.028zm16.99 0h-.916V6.644h.916v4.028zM9.925 8.71c-1.055 0-1.359.412-1.326.742.032.329.324.537.757.537a1.013 1.013 0 001.014-.968l.002-.31h-.447zM14.018 7.3c-.663 0-1.184.487-1.184 1.32 0 .832.52 1.32 1.184 1.32.662 0 1.182-.49 1.182-1.32 0-.832-.52-1.32-1.182-1.32zM6.417 5.001a.568.568 0 01.587.582.588.588 0 01-1.175 0A.57.57 0 016.417 5zm16.991 0a.57.57 0 01.592.582.588.588 0 01-1.174 0 .57.57 0 01.357-.542.572.572 0 01.225-.04z"></path></svg>
|
||||
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1 @@
|
||||
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Minimax</title><path d="M16.278 2c1.156 0 2.093.927 2.093 2.07v12.501a.74.74 0 00.744.709.74.74 0 00.743-.709V9.099a2.06 2.06 0 012.071-2.049A2.06 2.06 0 0124 9.1v6.561a.649.649 0 01-.652.645.649.649 0 01-.653-.645V9.1a.762.762 0 00-.766-.758.762.762 0 00-.766.758v7.472a2.037 2.037 0 01-2.048 2.026 2.037 2.037 0 01-2.048-2.026v-12.5a.785.785 0 00-.788-.753.785.785 0 00-.789.752l-.001 15.904A2.037 2.037 0 0113.441 22a2.037 2.037 0 01-2.048-2.026V18.04c0-.356.292-.645.652-.645.36 0 .652.289.652.645v1.934c0 .263.142.506.372.638.23.131.514.131.744 0a.734.734 0 00.372-.638V4.07c0-1.143.937-2.07 2.093-2.07zm-5.674 0c1.156 0 2.093.927 2.093 2.07v11.523a.648.648 0 01-.652.645.648.648 0 01-.652-.645V4.07a.785.785 0 00-.789-.78.785.785 0 00-.789.78v14.013a2.06 2.06 0 01-2.07 2.048 2.06 2.06 0 01-2.071-2.048V9.1a.762.762 0 00-.766-.758.762.762 0 00-.766.758v3.8a2.06 2.06 0 01-2.071 2.049A2.06 2.06 0 010 12.9v-1.378c0-.357.292-.646.652-.646.36 0 .653.29.653.646V12.9c0 .418.343.757.766.757s.766-.339.766-.757V9.099a2.06 2.06 0 012.07-2.048 2.06 2.06 0 012.071 2.048v8.984c0 .419.343.758.767.758.423 0 .766-.339.766-.758V4.07c0-1.143.937-2.07 2.093-2.07z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1 @@
|
||||
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Qwen</title><path d="M12.604 1.34c.393.69.784 1.382 1.174 2.075a.18.18 0 00.157.091h5.552c.174 0 .322.11.446.327l1.454 2.57c.19.337.24.478.024.837-.26.43-.513.864-.76 1.3l-.367.658c-.106.196-.223.28-.04.512l2.652 4.637c.172.301.111.494-.043.77-.437.785-.882 1.564-1.335 2.34-.159.272-.352.375-.68.37-.777-.016-1.552-.01-2.327.016a.099.099 0 00-.081.05 575.097 575.097 0 01-2.705 4.74c-.169.293-.38.363-.725.364-.997.003-2.002.004-3.017.002a.537.537 0 01-.465-.271l-1.335-2.323a.09.09 0 00-.083-.049H4.982c-.285.03-.553-.001-.805-.092l-1.603-2.77a.543.543 0 01-.002-.54l1.207-2.12a.198.198 0 000-.197 550.951 550.951 0 01-1.875-3.272l-.79-1.395c-.16-.31-.173-.496.095-.965.465-.813.927-1.625 1.387-2.436.132-.234.304-.334.584-.335a338.3 338.3 0 012.589-.001.124.124 0 00.107-.063l2.806-4.895a.488.488 0 01.422-.246c.524-.001 1.053 0 1.583-.006L11.704 1c.341-.003.724.032.9.34zm-3.432.403a.06.06 0 00-.052.03L6.254 6.788a.157.157 0 01-.135.078H3.253c-.056 0-.07.025-.041.074l5.81 10.156c.025.042.013.062-.034.063l-2.795.015a.218.218 0 00-.2.116l-1.32 2.31c-.044.078-.021.118.068.118l5.716.008c.046 0 .08.02.104.061l1.403 2.454c.046.081.092.082.139 0l5.006-8.76.783-1.382a.055.055 0 01.096 0l1.424 2.53a.122.122 0 00.107.062l2.763-.02a.04.04 0 00.035-.02.041.041 0 000-.04l-2.9-5.086a.108.108 0 010-.113l.293-.507 1.12-1.977c.024-.041.012-.062-.035-.062H9.2c-.059 0-.073-.026-.043-.077l1.434-2.505a.107.107 0 000-.114L9.225 1.774a.06.06 0 00-.053-.031zm6.29 8.02c.046 0 .058.02.034.06l-.832 1.465-2.613 4.585a.056.056 0 01-.05.029.058.058 0 01-.05-.029L8.498 9.841c-.02-.034-.01-.052.028-.054l.216-.012 6.722-.012z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
@@ -68,6 +68,137 @@ dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-broadcast"
|
||||
version = "0.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
|
||||
dependencies = [
|
||||
"event-listener",
|
||||
"event-listener-strategy",
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-channel"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
|
||||
dependencies = [
|
||||
"concurrent-queue",
|
||||
"event-listener-strategy",
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-executor"
|
||||
version = "1.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
|
||||
dependencies = [
|
||||
"async-task",
|
||||
"concurrent-queue",
|
||||
"fastrand",
|
||||
"futures-lite",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-io"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"cfg-if",
|
||||
"concurrent-queue",
|
||||
"futures-io",
|
||||
"futures-lite",
|
||||
"parking",
|
||||
"polling",
|
||||
"rustix",
|
||||
"slab",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-lock"
|
||||
version = "3.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
|
||||
dependencies = [
|
||||
"event-listener",
|
||||
"event-listener-strategy",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-process"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
"async-lock",
|
||||
"async-signal",
|
||||
"async-task",
|
||||
"blocking",
|
||||
"cfg-if",
|
||||
"event-listener",
|
||||
"futures-lite",
|
||||
"rustix",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-recursion"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-signal"
|
||||
version = "0.2.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
|
||||
dependencies = [
|
||||
"async-io",
|
||||
"async-lock",
|
||||
"atomic-waker",
|
||||
"cfg-if",
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"rustix",
|
||||
"signal-hook-registry",
|
||||
"slab",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-task"
|
||||
version = "4.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.89"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atk"
|
||||
version = "0.18.2"
|
||||
@@ -163,6 +294,19 @@ dependencies = [
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "blocking"
|
||||
version = "1.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-task",
|
||||
"futures-io",
|
||||
"futures-lite",
|
||||
"piper",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli"
|
||||
version = "8.0.4"
|
||||
@@ -294,6 +438,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
"libc",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
@@ -346,12 +492,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "codex-x"
|
||||
version = "0.3.1"
|
||||
version = "0.3.24"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"dirs 5.0.1",
|
||||
"flate2",
|
||||
"getrandom 0.2.17",
|
||||
"httparse",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"rfd",
|
||||
"rusqlite",
|
||||
"rustls",
|
||||
"semver",
|
||||
@@ -360,13 +511,17 @@ dependencies = [
|
||||
"sha2",
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"tauri-plugin-dialog",
|
||||
"tauri-plugin-process",
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-updater",
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"toml_edit 0.22.27",
|
||||
"ureq",
|
||||
"windows-sys 0.61.2",
|
||||
"zip 2.4.2",
|
||||
"zstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -379,6 +534,15 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "concurrent-queue"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.1"
|
||||
@@ -791,6 +955,33 @@ version = "1.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"
|
||||
|
||||
[[package]]
|
||||
name = "endi"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
|
||||
|
||||
[[package]]
|
||||
name = "enumflags2"
|
||||
version = "0.7.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
|
||||
dependencies = [
|
||||
"enumflags2_derive",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "enumflags2_derive"
|
||||
version = "0.7.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -818,6 +1009,26 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "event-listener"
|
||||
version = "5.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
|
||||
dependencies = [
|
||||
"parking",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "event-listener-strategy"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
|
||||
dependencies = [
|
||||
"event-listener",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fallible-iterator"
|
||||
version = "0.3.0"
|
||||
@@ -962,6 +1173,19 @@ version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
|
||||
|
||||
[[package]]
|
||||
name = "futures-lite"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"parking",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-macro"
|
||||
version = "0.3.32"
|
||||
@@ -1334,6 +1558,12 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
|
||||
|
||||
[[package]]
|
||||
name = "hex"
|
||||
version = "0.4.3"
|
||||
@@ -1383,12 +1613,6 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-range"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "21dec9db110f5f872ed9699c3ecf50cf16f423502706ba5c72462e28d3157573"
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
@@ -1739,6 +1963,16 @@ dependencies = [
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
version = "0.1.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.103"
|
||||
@@ -2252,6 +2486,16 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
|
||||
|
||||
[[package]]
|
||||
name = "ordered-stream"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "osakit"
|
||||
version = "0.3.1"
|
||||
@@ -2291,6 +2535,12 @@ dependencies = [
|
||||
"system-deps",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking"
|
||||
version = "2.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.5"
|
||||
@@ -2379,6 +2629,17 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "piper"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"fastrand",
|
||||
"futures-io",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.33"
|
||||
@@ -2424,6 +2685,26 @@ dependencies = [
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "polling"
|
||||
version = "3.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"concurrent-queue",
|
||||
"hermit-abi",
|
||||
"pin-project-lite",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pollster"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.5"
|
||||
@@ -2664,26 +2945,26 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rfd"
|
||||
version = "0.16.0"
|
||||
version = "0.17.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"
|
||||
checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220"
|
||||
dependencies = [
|
||||
"block2",
|
||||
"dispatch2",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gtk-sys",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"log",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
"percent-encoding",
|
||||
"pollster",
|
||||
"raw-window-handle",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3124,6 +3405,16 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||
dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.9"
|
||||
@@ -3435,7 +3726,6 @@ dependencies = [
|
||||
"gtk",
|
||||
"heck 0.5.0",
|
||||
"http",
|
||||
"http-range",
|
||||
"jni 0.21.1",
|
||||
"libc",
|
||||
"log",
|
||||
@@ -3548,48 +3838,6 @@ dependencies = [
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-dialog"
|
||||
version = "2.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2d3c1dbe38037e7f590cdf2492594d5ceebe031e7bc7e827509b22a999d2940"
|
||||
dependencies = [
|
||||
"log",
|
||||
"raw-window-handle",
|
||||
"rfd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tauri-plugin",
|
||||
"tauri-plugin-fs",
|
||||
"thiserror 2.0.18",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-fs"
|
||||
version = "2.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7ecc274121aca0c036a2b42d1cbe83d368d348f54e0bb8a735c2b1548e8f371"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"dunce",
|
||||
"glob",
|
||||
"log",
|
||||
"objc2-foundation",
|
||||
"percent-encoding",
|
||||
"schemars 0.8.22",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_repr",
|
||||
"tauri",
|
||||
"tauri-plugin",
|
||||
"tauri-utils",
|
||||
"thiserror 2.0.18",
|
||||
"toml 1.1.2+spec-1.1.0",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-process"
|
||||
version = "2.3.1"
|
||||
@@ -3600,6 +3848,22 @@ dependencies = [
|
||||
"tauri-plugin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-single-instance"
|
||||
version = "2.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b3214becf9ef5783c0ae99a3bb25adf5353a7a16ebf53e74b909e29205735c6c"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows-sys 0.60.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-updater"
|
||||
version = "2.10.1"
|
||||
@@ -4078,9 +4342,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"pin-project-lite",
|
||||
"tracing-attributes",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-attributes"
|
||||
version = "0.1.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.36"
|
||||
@@ -4130,6 +4406,17 @@ version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "uds_windows"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
|
||||
dependencies = [
|
||||
"memoffset",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-char-property"
|
||||
version = "0.9.0"
|
||||
@@ -5181,6 +5468,67 @@ dependencies = [
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus"
|
||||
version = "5.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe18fb60dc696039e738717b76eaea21e7a4489bbb1885020b43c94236d7e98a"
|
||||
dependencies = [
|
||||
"async-broadcast",
|
||||
"async-executor",
|
||||
"async-io",
|
||||
"async-lock",
|
||||
"async-process",
|
||||
"async-recursion",
|
||||
"async-task",
|
||||
"async-trait",
|
||||
"blocking",
|
||||
"enumflags2",
|
||||
"event-listener",
|
||||
"futures-core",
|
||||
"futures-lite",
|
||||
"hex",
|
||||
"libc",
|
||||
"ordered-stream",
|
||||
"rustix",
|
||||
"serde",
|
||||
"serde_repr",
|
||||
"tracing",
|
||||
"uds_windows",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"winnow 1.0.3",
|
||||
"zbus_macros",
|
||||
"zbus_names",
|
||||
"zvariant",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus_macros"
|
||||
version = "5.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe96480bed92df2b442a1a30df364e12d08eed03aeb061f2b8dc6afb2be91119"
|
||||
dependencies = [
|
||||
"proc-macro-crate 3.5.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
"zbus_names",
|
||||
"zvariant",
|
||||
"zvariant_utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus_names"
|
||||
version = "4.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"winnow 1.0.3",
|
||||
"zvariant",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.52"
|
||||
@@ -5307,3 +5655,71 @@ dependencies = [
|
||||
"log",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd"
|
||||
version = "0.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
|
||||
dependencies = [
|
||||
"zstd-safe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-safe"
|
||||
version = "7.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882"
|
||||
dependencies = [
|
||||
"zstd-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-sys"
|
||||
version = "2.1.0+zstd.1.5.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zvariant"
|
||||
version = "5.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bee2a0bcd2a907786a456fff45aaaaf54c9ba5f50b71ae9ec1a4edd200c94911"
|
||||
dependencies = [
|
||||
"endi",
|
||||
"enumflags2",
|
||||
"serde",
|
||||
"winnow 1.0.3",
|
||||
"zvariant_derive",
|
||||
"zvariant_utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zvariant_derive"
|
||||
version = "5.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38a708216a18780796770bfe3f4739c7c83a3e8f789b755534bbbc06e4e23e12"
|
||||
dependencies = [
|
||||
"proc-macro-crate 3.5.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
"zvariant_utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zvariant_utils"
|
||||
version = "3.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "90cb9383f9b45290407a1258b202d3f8f01db719eb60b4e4055c6375af4fc7c7"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde",
|
||||
"syn 2.0.118",
|
||||
"winnow 1.0.3",
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "codex-x"
|
||||
version = "0.3.1"
|
||||
version = "0.3.24"
|
||||
description = "Codex Switch & Instruct desktop manager"
|
||||
authors = ["yynxxxxx"]
|
||||
license = "MIT"
|
||||
@@ -11,18 +11,16 @@ rust-version = "1.89.0"
|
||||
name = "codexx_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[features]
|
||||
windows-runtime-check = []
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.4.0", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2.8.2", features = ["protocol-asset"] }
|
||||
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"
|
||||
base64 = "0.22"
|
||||
toml_edit = "0.22"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
dirs = "5.0"
|
||||
@@ -40,4 +38,14 @@ rustls = { version = "0.23", default-features = false, features = ["ring"] }
|
||||
sha2 = "0.10"
|
||||
percent-encoding = "2.3"
|
||||
zip = { version = "2.2", default-features = false, features = ["deflate"] }
|
||||
tauri-plugin-dialog = "2"
|
||||
rfd = { version = "=0.17.2", default-features = false, features = ["xdg-portal"] }
|
||||
tauri-plugin-single-instance = "=2.4.3"
|
||||
httparse = "1"
|
||||
getrandom = "0.2"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "time", "net"] }
|
||||
flate2 = "1"
|
||||
zstd = "0.13"
|
||||
tempfile = "3.27"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }
|
||||
|
||||
@@ -6,11 +6,7 @@
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-start-dragging",
|
||||
"dialog:allow-save",
|
||||
"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.
|
||||
|
Before Width: | Height: | Size: 1.7 MiB |
@@ -1,32 +0,0 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "shiina-mashiro-blossom",
|
||||
"name": "椎名真白·樱花画室",
|
||||
"brandSubtitle": "椎名真白主题",
|
||||
"tagline": "椎名真白在白樱画室里安静作画。",
|
||||
"projectPrefix": "选择项目 · ",
|
||||
"projectLabel": "◉ 选择项目",
|
||||
"statusText": "椎名真白主题运行中",
|
||||
"quote": "安静创作,也会发光",
|
||||
"image": "background.png",
|
||||
"appearance": "light",
|
||||
"surfaceOpacity": 0.62,
|
||||
"art": {
|
||||
"focusX": 0.28,
|
||||
"focusY": 0.26,
|
||||
"safeArea": "right",
|
||||
"taskMode": "ambient"
|
||||
},
|
||||
"colors": {
|
||||
"background": "#f9f4f7",
|
||||
"panel": "#fffafd",
|
||||
"panelAlt": "#fff1f7",
|
||||
"accent": "#ef7da4",
|
||||
"accentAlt": "#ffadc9",
|
||||
"secondary": "#f5c2d6",
|
||||
"highlight": "#c95f8a",
|
||||
"text": "#2a2026",
|
||||
"muted": "#8d7180",
|
||||
"line": "rgba(239, 125, 164, .26)"
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
# Codex Dream Skin Runtime Notice
|
||||
|
||||
The files in this directory are adapted from Codex Dream Skin Studio:
|
||||
|
||||
- Source: https://github.com/Fei-Away/Codex-Dream-Skin
|
||||
- Pinned source commit: `5fd8af532efbaa87d2d0092297fd2d45cd56574e`
|
||||
- Upstream runtime version: `1.2.0`
|
||||
- License: MIT, reproduced in `LICENSE`
|
||||
|
||||
Codex-X embeds these runtime sources and manages them itself. It does not require
|
||||
the separate Codex Dream Skin Studio installer or its `~/.codex` engine directory.
|
||||
The Windows release also bundles Node.js 22.23.1 from nodejs.org, verified against
|
||||
SHA-256 `7df0bc9375723f4a86b3aa1b7cc73342423d9677a8df4538aca31a049e309c29`;
|
||||
its upstream license is distributed beside `node.exe`.
|
||||
|
||||
Only the upstream software source and procedurally generated abstract presets are
|
||||
included. The Arina Hashimoto preset and other assets excluded by the upstream
|
||||
notice are intentionally not distributed with Codex-X.
|
||||
|
||||
Codex Dream Skin Studio and Codex-X are unofficial projects and are not affiliated
|
||||
with, endorsed by, or sponsored by OpenAI. Codex and related trademarks belong to
|
||||
their respective owners.
|
||||
@@ -1,796 +0,0 @@
|
||||
((cssText, artDataUrl, themeConfig) => {
|
||||
const STATE_KEY = "__CODEX_DREAM_SKIN_STATE__";
|
||||
const DISABLED_KEY = "__CODEX_DREAM_SKIN_DISABLED__";
|
||||
const STYLE_ID = "codex-dream-skin-style";
|
||||
const CHROME_ID = "codex-dream-skin-chrome";
|
||||
const SHELL_ATTR = "data-dream-shell";
|
||||
const ART_ATTRS = [
|
||||
"data-dream-art-wide", "data-dream-art-safe", "data-dream-task-mode",
|
||||
"data-dream-art-safe-area", "data-dream-art-task-mode", "data-dream-art-aspect",
|
||||
"data-dream-art-ready",
|
||||
];
|
||||
const VERSION = __DREAM_SKIN_VERSION_JSON__;
|
||||
const STYLE_REVISION = __DREAM_SKIN_STYLE_REVISION_JSON__;
|
||||
const THEME = themeConfig && typeof themeConfig === "object" ? themeConfig : {};
|
||||
const ART = THEME.art && typeof THEME.art === "object" ? THEME.art : {};
|
||||
const ART_METADATA = THEME.artMetadata && typeof THEME.artMetadata === "object"
|
||||
? THEME.artMetadata : null;
|
||||
const ANALYSIS_CACHE_KEY = "__CODEX_DREAM_SKIN_ANALYSIS_CACHE__";
|
||||
const THEME_VARIABLES = [
|
||||
"--ds-bg", "--ds-panel", "--ds-panel-2", "--ds-green", "--ds-lime",
|
||||
"--ds-cyan", "--ds-purple", "--ds-text", "--ds-muted", "--ds-line",
|
||||
"--ds-bg-rgb", "--ds-panel-rgb", "--ds-panel-2-rgb", "--ds-accent-rgb",
|
||||
"--ds-accent-alt-rgb", "--ds-secondary-rgb", "--ds-highlight-rgb",
|
||||
"--ds-text-rgb", "--ds-muted-rgb", "--ds-line-rgb", "--ds-surface-opacity",
|
||||
"--dream-art-focus-x", "--dream-art-focus-y", "--dream-art-position",
|
||||
"--dream-skin-focus-x", "--dream-skin-focus-y", "--dream-skin-art-position",
|
||||
"--dream-skin-home-art-position",
|
||||
"--dream-skin-name", "--dream-skin-tagline", "--dream-skin-project-prefix",
|
||||
"--dream-skin-project-label",
|
||||
];
|
||||
const installToken = {};
|
||||
const existingAnalysisCache = window[ANALYSIS_CACHE_KEY];
|
||||
const analysisCache = existingAnalysisCache && typeof existingAnalysisCache.get === "function" &&
|
||||
typeof existingAnalysisCache.set === "function" ? existingAnalysisCache : new Map();
|
||||
window[ANALYSIS_CACHE_KEY] = analysisCache;
|
||||
let artAnalysis = typeof THEME.artKey === "string" ? analysisCache.get(THEME.artKey) ?? null : null;
|
||||
let analysisTimer = null;
|
||||
let samplingNativeShell = false;
|
||||
let rootObserver = null;
|
||||
const now = () => typeof performance === "object" && typeof performance.now === "function"
|
||||
? performance.now() : Date.now();
|
||||
const metrics = {
|
||||
ensureCalls: 0,
|
||||
rootPasses: 0,
|
||||
routePasses: 0,
|
||||
layoutReads: 0,
|
||||
attributeWrites: 0,
|
||||
styleWrites: 0,
|
||||
textWrites: 0,
|
||||
analysisRuns: 0,
|
||||
analysisCacheHits: artAnalysis ? 1 : 0,
|
||||
firstEnsureMs: null,
|
||||
analysisMs: null,
|
||||
};
|
||||
window[DISABLED_KEY] = false;
|
||||
|
||||
const previous = window[STATE_KEY];
|
||||
const artUrl = (() => {
|
||||
const comma = artDataUrl.indexOf(",");
|
||||
const mime = /^data:([^;,]+)/.exec(artDataUrl)?.[1] || "image/png";
|
||||
const binary = atob(artDataUrl.slice(comma + 1));
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
||||
return URL.createObjectURL(new Blob([bytes], { type: mime }));
|
||||
})();
|
||||
|
||||
if (previous?.observer) previous.observer.disconnect();
|
||||
if (previous?.rootObserver) previous.rootObserver.disconnect();
|
||||
if (previous?.resizeObserver) previous.resizeObserver.disconnect();
|
||||
if (previous?.timer) clearInterval(previous.timer);
|
||||
if (previous?.scheduler?.timeout) clearTimeout(previous.scheduler.timeout);
|
||||
if (previous?.scheduler?.frame != null && typeof cancelAnimationFrame === "function") {
|
||||
cancelAnimationFrame(previous.scheduler.frame);
|
||||
}
|
||||
if (previous?.analysisTimer) clearTimeout(previous.analysisTimer);
|
||||
if (previous?.resizeHandler) window.removeEventListener("resize", previous.resizeHandler);
|
||||
if (previous?.mediaHandler && previous?.mediaQuery) {
|
||||
try { previous.mediaQuery.removeEventListener("change", previous.mediaHandler); } catch {}
|
||||
}
|
||||
|
||||
const cssString = (value) => JSON.stringify(String(value ?? ""));
|
||||
|
||||
const setStyleProperty = (root, name, value) => {
|
||||
if (root.style.getPropertyValue(name) !== value) {
|
||||
root.style.setProperty(name, value);
|
||||
metrics.styleWrites += 1;
|
||||
}
|
||||
};
|
||||
|
||||
const setAttribute = (root, name, value) => {
|
||||
const normalized = String(value);
|
||||
if (root.getAttribute(name) !== normalized) {
|
||||
root.setAttribute(name, normalized);
|
||||
metrics.attributeWrites += 1;
|
||||
}
|
||||
};
|
||||
|
||||
const setTextContent = (node, value) => {
|
||||
if (node && node.textContent !== value) {
|
||||
node.textContent = value;
|
||||
metrics.textWrites += 1;
|
||||
}
|
||||
};
|
||||
|
||||
const parseRgb = (value) => {
|
||||
if (!value || value === "transparent") return null;
|
||||
const hex = String(value).trim().match(/^#([0-9a-f]{6})$/i);
|
||||
if (hex) {
|
||||
const number = Number.parseInt(hex[1], 16);
|
||||
return { r: number >> 16, g: (number >> 8) & 255, b: number & 255 };
|
||||
}
|
||||
const m = String(value).match(/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i);
|
||||
if (!m) return null;
|
||||
return { r: Number(m[1]), g: Number(m[2]), b: Number(m[3]) };
|
||||
};
|
||||
|
||||
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
|
||||
|
||||
const rgbString = (value) => {
|
||||
const rgb = parseRgb(value);
|
||||
return rgb ? `${Math.round(rgb.r)} ${Math.round(rgb.g)} ${Math.round(rgb.b)}` : null;
|
||||
};
|
||||
|
||||
const rgbToHex = ({ r, g, b }) => `#${[r, g, b]
|
||||
.map((value) => clamp(Math.round(value), 0, 255).toString(16).padStart(2, "0"))
|
||||
.join("")}`;
|
||||
|
||||
const rgbToHsl = ({ r, g, b }) => {
|
||||
const values = [r, g, b].map((value) => value / 255);
|
||||
const max = Math.max(...values);
|
||||
const min = Math.min(...values);
|
||||
const lightness = (max + min) / 2;
|
||||
if (max === min) return { h: 0, s: 0, l: lightness };
|
||||
const delta = max - min;
|
||||
const saturation = lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min);
|
||||
let hue;
|
||||
if (max === values[0]) hue = (values[1] - values[2]) / delta + (values[1] < values[2] ? 6 : 0);
|
||||
else if (max === values[1]) hue = (values[2] - values[0]) / delta + 2;
|
||||
else hue = (values[0] - values[1]) / delta + 4;
|
||||
return { h: hue * 60, s: saturation, l: lightness };
|
||||
};
|
||||
|
||||
const hslToRgb = ({ h, s, l }) => {
|
||||
const hue = ((h % 360) + 360) % 360 / 360;
|
||||
if (s === 0) {
|
||||
const neutral = Math.round(l * 255);
|
||||
return { r: neutral, g: neutral, b: neutral };
|
||||
}
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
const channel = (offset) => {
|
||||
let t = hue + offset;
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
return { r: channel(1 / 3) * 255, g: channel(0) * 255, b: channel(-1 / 3) * 255 };
|
||||
};
|
||||
|
||||
const luminance = ({ r, g, b }) => {
|
||||
const lin = [r, g, b].map((c) => {
|
||||
const x = c / 255;
|
||||
return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
|
||||
});
|
||||
return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2];
|
||||
};
|
||||
|
||||
/** Detect Codex app light/dark shell for CSS branching. */
|
||||
const detectShellMode = () => {
|
||||
const root = document.documentElement;
|
||||
const body = document.body;
|
||||
const cls = `${root.className || ""} ${body?.className || ""}`.toLowerCase();
|
||||
|
||||
if (/\b(dark|theme-dark|appearance-dark)\b/.test(cls)) return "dark";
|
||||
if (/\b(light|theme-light|appearance-light)\b/.test(cls)) return "light";
|
||||
|
||||
const dataTheme = (
|
||||
root.getAttribute("data-theme") ||
|
||||
root.getAttribute("data-appearance") ||
|
||||
root.getAttribute("data-color-mode") ||
|
||||
body?.getAttribute("data-theme") ||
|
||||
body?.getAttribute("data-appearance") ||
|
||||
""
|
||||
).toLowerCase();
|
||||
if (dataTheme.includes("dark")) return "dark";
|
||||
if (dataTheme.includes("light")) return "light";
|
||||
|
||||
// Radios in profile menu (if present in DOM)
|
||||
const checked = document.querySelector('input[name="appearance-theme"]:checked');
|
||||
if (checked) {
|
||||
const label = (checked.getAttribute("aria-label") || checked.value || "").toLowerCase();
|
||||
if (label.includes("暗") || label.includes("dark")) return "dark";
|
||||
if (label.includes("浅") || label.includes("light")) return "light";
|
||||
if (label.includes("系统") || label.includes("system")) {
|
||||
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
||||
}
|
||||
}
|
||||
|
||||
// The skin itself declares color-scheme on :root. Once installed,
|
||||
// reading getComputedStyle(root) directly would therefore keep `auto`
|
||||
// themes locked to the previous shell mode. Temporarily remove only our
|
||||
// own root class/attribute, sample the native computed scheme, then restore
|
||||
// synchronously. Mutation records created by this probe are drained below
|
||||
// so the root observer does not schedule a redundant ensure pass.
|
||||
try {
|
||||
const hadSkin = root.classList.contains("codex-dream-skin");
|
||||
const savedShell = root.getAttribute(SHELL_ATTR);
|
||||
samplingNativeShell = true;
|
||||
if (hadSkin) root.classList.remove("codex-dream-skin");
|
||||
if (savedShell !== null) root.removeAttribute(SHELL_ATTR);
|
||||
let colorScheme = "";
|
||||
try {
|
||||
colorScheme = getComputedStyle(root).colorScheme || "";
|
||||
} finally {
|
||||
if (hadSkin) root.classList.add("codex-dream-skin");
|
||||
if (savedShell !== null) root.setAttribute(SHELL_ATTR, savedShell);
|
||||
rootObserver?.takeRecords?.();
|
||||
samplingNativeShell = false;
|
||||
}
|
||||
if (colorScheme.includes("dark") && !colorScheme.includes("light")) return "dark";
|
||||
if (colorScheme.includes("light") && !colorScheme.includes("dark")) return "light";
|
||||
} catch {
|
||||
samplingNativeShell = false;
|
||||
}
|
||||
|
||||
try {
|
||||
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
||||
} catch {}
|
||||
|
||||
// Only use surface luminance before the skin owns those surfaces. Sampling
|
||||
// our own translucent layers would create route-dependent light/dark flips.
|
||||
if (!root.classList.contains("codex-dream-skin")) {
|
||||
const samples = [
|
||||
body,
|
||||
document.querySelector("main.main-surface"),
|
||||
document.querySelector("aside.app-shell-left-panel"),
|
||||
].filter(Boolean);
|
||||
let votesLight = 0;
|
||||
let votesDark = 0;
|
||||
for (const el of samples) {
|
||||
try {
|
||||
const rgb = parseRgb(getComputedStyle(el).backgroundColor);
|
||||
if (!rgb) continue;
|
||||
const L = luminance(rgb);
|
||||
if (L >= 0.55) votesLight += 1;
|
||||
else if (L <= 0.25) votesDark += 1;
|
||||
} catch {}
|
||||
}
|
||||
if (votesLight > votesDark) return "light";
|
||||
if (votesDark > votesLight) return "dark";
|
||||
}
|
||||
return "light";
|
||||
};
|
||||
|
||||
const makeAdaptivePalette = (sample, shell) => {
|
||||
const source = sample || { r: 108, g: 126, b: 136 };
|
||||
const hsl = rgbToHsl(source);
|
||||
const hue = hsl.s < 0.12 ? 214 : hsl.h;
|
||||
const saturation = clamp(hsl.s, 0.38, 0.72);
|
||||
const accent = hslToRgb({ h: hue, s: saturation, l: shell === "light" ? 0.42 : 0.66 });
|
||||
const accentAlt = hslToRgb({ h: hue + 12, s: saturation * 0.82, l: shell === "light" ? 0.52 : 0.73 });
|
||||
const secondary = hslToRgb({ h: hue - 24, s: saturation * 0.64, l: shell === "light" ? 0.56 : 0.62 });
|
||||
const highlight = hslToRgb({ h: hue + 24, s: saturation * 0.76, l: shell === "light" ? 0.36 : 0.58 });
|
||||
const neutral = (lightness, chroma = 0.08) => rgbToHex(hslToRgb({ h: hue, s: chroma, l: lightness }));
|
||||
return shell === "light" ? {
|
||||
background: neutral(0.965, 0.07),
|
||||
panel: neutral(0.987, 0.035),
|
||||
panelAlt: neutral(0.945, 0.09),
|
||||
accent: rgbToHex(accent),
|
||||
accentAlt: rgbToHex(accentAlt),
|
||||
secondary: rgbToHex(secondary),
|
||||
highlight: rgbToHex(highlight),
|
||||
text: neutral(0.13, 0.10),
|
||||
muted: neutral(0.42, 0.08),
|
||||
line: `rgba(${Math.round(accent.r)}, ${Math.round(accent.g)}, ${Math.round(accent.b)}, .24)`,
|
||||
} : {
|
||||
background: neutral(0.055, 0.045),
|
||||
panel: neutral(0.085, 0.04),
|
||||
panelAlt: neutral(0.125, 0.05),
|
||||
accent: rgbToHex(accent),
|
||||
accentAlt: rgbToHex(accentAlt),
|
||||
secondary: rgbToHex(secondary),
|
||||
highlight: rgbToHex(highlight),
|
||||
text: neutral(0.93, 0.025),
|
||||
muted: neutral(0.69, 0.03),
|
||||
line: `rgba(${Math.round(accent.r)}, ${Math.round(accent.g)}, ${Math.round(accent.b)}, .28)`,
|
||||
};
|
||||
};
|
||||
|
||||
const resolvedShell = () => {
|
||||
if (THEME.appearance === "light" || THEME.appearance === "dark") return THEME.appearance;
|
||||
// Image luminance may tune accents and scrims, but auto appearance follows
|
||||
// Codex/ChatGPT (or the OS fallback) so a bright wallpaper cannot flip a
|
||||
// native dark session back to a light shell after analysis.
|
||||
return detectShellMode();
|
||||
};
|
||||
|
||||
const applyTheme = (root, shell) => {
|
||||
const colors = THEME.colors || {};
|
||||
const explicit = new Set(Array.isArray(THEME.explicitColorKeys) ? THEME.explicitColorKeys : []);
|
||||
const adaptive = makeAdaptivePalette(artAnalysis?.accentRgb, shell);
|
||||
const legacyLight = !THEME.appearance && shell === "light";
|
||||
const structural = new Set(["background", "panel", "panelAlt", "text", "muted"]);
|
||||
const pick = (name) => {
|
||||
const allowExplicit = explicit.has(name) && !(legacyLight && structural.has(name));
|
||||
return allowExplicit && typeof colors[name] === "string" ? colors[name] : adaptive[name];
|
||||
};
|
||||
const accent = pick("accent");
|
||||
const accentAlt = explicit.has("accentAlt") ? pick("accentAlt") : (explicit.has("accent") ? accent : adaptive.accentAlt);
|
||||
const variables = {
|
||||
"--ds-bg": pick("background"),
|
||||
"--ds-panel": pick("panel"),
|
||||
"--ds-panel-2": pick("panelAlt"),
|
||||
"--ds-green": accent,
|
||||
"--ds-lime": accentAlt,
|
||||
"--ds-cyan": pick("secondary"),
|
||||
"--ds-purple": pick("highlight"),
|
||||
"--ds-text": pick("text"),
|
||||
"--ds-muted": pick("muted"),
|
||||
"--ds-line": explicit.has("line") && typeof colors.line === "string" ? colors.line : adaptive.line,
|
||||
};
|
||||
const surfaceOpacity = Number.isFinite(Number(THEME.surfaceOpacity))
|
||||
? clamp(Number(THEME.surfaceOpacity), 0.35, 1)
|
||||
: 1;
|
||||
setStyleProperty(root, "--ds-surface-opacity", surfaceOpacity.toFixed(2));
|
||||
|
||||
for (const [name, value] of Object.entries(variables)) {
|
||||
if (typeof value === "string" && value) setStyleProperty(root, name, value);
|
||||
}
|
||||
const rgbVariables = {
|
||||
"--ds-bg-rgb": variables["--ds-bg"],
|
||||
"--ds-panel-rgb": variables["--ds-panel"],
|
||||
"--ds-panel-2-rgb": variables["--ds-panel-2"],
|
||||
"--ds-accent-rgb": variables["--ds-green"],
|
||||
"--ds-accent-alt-rgb": variables["--ds-lime"],
|
||||
"--ds-secondary-rgb": variables["--ds-cyan"],
|
||||
"--ds-highlight-rgb": variables["--ds-purple"],
|
||||
"--ds-text-rgb": variables["--ds-text"],
|
||||
"--ds-muted-rgb": variables["--ds-muted"],
|
||||
"--ds-line-rgb": variables["--ds-line"],
|
||||
};
|
||||
for (const [name, value] of Object.entries(rgbVariables)) {
|
||||
const rgb = rgbString(value);
|
||||
if (rgb) setStyleProperty(root, name, rgb);
|
||||
}
|
||||
setStyleProperty(root, "--dream-skin-name", cssString(THEME.name || "Codex Dream Skin"));
|
||||
setStyleProperty(root, "--dream-skin-tagline", cssString(THEME.tagline || "Make something wonderful."));
|
||||
setStyleProperty(root, "--dream-skin-project-prefix", cssString(THEME.projectPrefix || "选择项目 · "));
|
||||
setStyleProperty(root, "--dream-skin-project-label", cssString(THEME.projectLabel || "◉ 选择项目"));
|
||||
};
|
||||
|
||||
const applyArtMetadata = (root) => {
|
||||
const profile = artAnalysis || ART_METADATA;
|
||||
const inferredSafe = profile?.safeArea || "center";
|
||||
const safeArea = ART.safeArea && ART.safeArea !== "auto" ? ART.safeArea : inferredSafe;
|
||||
const canonicalSafe = ["left", "right", "center", "none"].includes(safeArea)
|
||||
? safeArea : "center";
|
||||
const focusX = typeof ART.focusX === "number" ? ART.focusX
|
||||
: profile?.focusX ?? (safeArea === "left" ? 0.72 : safeArea === "right" ? 0.28 : 0.5);
|
||||
const focusY = typeof ART.focusY === "number" ? ART.focusY : profile?.focusY ?? 0.5;
|
||||
const explicitFocusY = typeof ART.focusY === "number";
|
||||
const taskMode = ART.taskMode && ART.taskMode !== "auto"
|
||||
? ART.taskMode : profile?.taskMode || "ambient";
|
||||
const wide = profile?.wide || false;
|
||||
const aspect = profile?.aspect || "unknown";
|
||||
const homeFocusY = !explicitFocusY && !wide && ["wide", "landscape"].includes(aspect)
|
||||
? Math.min(focusY, 0.28) : focusY;
|
||||
const focusXValue = `${(clamp(focusX, 0, 1) * 100).toFixed(2)}%`;
|
||||
const focusYValue = `${(clamp(focusY, 0, 1) * 100).toFixed(2)}%`;
|
||||
const homeFocusYValue = `${(clamp(homeFocusY, 0, 1) * 100).toFixed(2)}%`;
|
||||
|
||||
setAttribute(root, "data-dream-art-wide", wide ? "true" : "false");
|
||||
setAttribute(root, "data-dream-art-safe", canonicalSafe);
|
||||
setAttribute(root, "data-dream-task-mode", taskMode);
|
||||
setAttribute(root, "data-dream-art-safe-area", safeArea);
|
||||
setAttribute(root, "data-dream-art-task-mode", taskMode);
|
||||
setAttribute(root, "data-dream-art-aspect", aspect);
|
||||
setAttribute(root, "data-dream-art-ready", artAnalysis ? "true" : "false");
|
||||
setStyleProperty(root, "--dream-art-focus-x", focusXValue);
|
||||
setStyleProperty(root, "--dream-art-focus-y", focusYValue);
|
||||
setStyleProperty(root, "--dream-art-position", `${focusXValue} ${focusYValue}`);
|
||||
setStyleProperty(root, "--dream-skin-focus-x", focusXValue);
|
||||
setStyleProperty(root, "--dream-skin-focus-y", focusYValue);
|
||||
setStyleProperty(root, "--dream-skin-art-position", `${focusXValue} ${focusYValue}`);
|
||||
setStyleProperty(root, "--dream-skin-home-art-position", `${focusXValue} ${homeFocusYValue}`);
|
||||
};
|
||||
|
||||
const analyzeArt = () => new Promise((resolve) => {
|
||||
const startedAt = now();
|
||||
metrics.analysisRuns += 1;
|
||||
if (typeof window.Image !== "function" || !document?.createElement) {
|
||||
metrics.analysisMs = Number((now() - startedAt).toFixed(3));
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
const image = new window.Image();
|
||||
let settled = false;
|
||||
const finish = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (analysisTimer) clearTimeout(analysisTimer);
|
||||
analysisTimer = null;
|
||||
metrics.analysisMs = Number((now() - startedAt).toFixed(3));
|
||||
resolve(value);
|
||||
};
|
||||
analysisTimer = setTimeout(() => finish(null), 6000);
|
||||
image.onerror = () => finish(null);
|
||||
image.onload = () => {
|
||||
try {
|
||||
const ratio = image.naturalWidth / image.naturalHeight;
|
||||
if (!Number.isFinite(ratio) || ratio <= 0) throw new Error("Invalid image dimensions");
|
||||
const maxDimension = 96;
|
||||
const width = Math.max(16, Math.round(ratio >= 1 ? maxDimension : maxDimension * ratio));
|
||||
const height = Math.max(16, Math.round(ratio >= 1 ? maxDimension / ratio : maxDimension));
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const context = canvas.getContext?.("2d", { willReadFrequently: true });
|
||||
if (!context) throw new Error("Canvas is unavailable");
|
||||
context.drawImage(image, 0, 0, width, height);
|
||||
const data = context.getImageData(0, 0, width, height).data;
|
||||
const samples = new Array(width * height);
|
||||
const bins = Array.from({ length: 24 }, () => ({ weight: 0, r: 0, g: 0, b: 0 }));
|
||||
let lightTotal = 0;
|
||||
let count = 0;
|
||||
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
const offset = (y * width + x) * 4;
|
||||
if (data[offset + 3] < 32) continue;
|
||||
const rgb = { r: data[offset], g: data[offset + 1], b: data[offset + 2] };
|
||||
const light = (0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b) / 255;
|
||||
const hsl = rgbToHsl(rgb);
|
||||
samples[y * width + x] = { light, saturation: hsl.s };
|
||||
lightTotal += light;
|
||||
count += 1;
|
||||
if (hsl.s >= 0.16 && hsl.l >= 0.16 && hsl.l <= 0.86) {
|
||||
const bin = bins[Math.min(23, Math.floor(hsl.h / 15))];
|
||||
const weight = hsl.s * (1 - Math.abs(hsl.l - 0.52) * 0.85);
|
||||
bin.weight += weight;
|
||||
bin.r += rgb.r * weight;
|
||||
bin.g += rgb.g * weight;
|
||||
bin.b += rgb.b * weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!count) throw new Error("Image has no visible pixels");
|
||||
const brightness = lightTotal / count;
|
||||
const information = (start, end) => {
|
||||
let total = 0;
|
||||
let totalSquared = 0;
|
||||
let edges = 0;
|
||||
let edgeCount = 0;
|
||||
let pixels = 0;
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
for (let x = start; x < end; x += 1) {
|
||||
const sample = samples[y * width + x];
|
||||
if (!sample) continue;
|
||||
total += sample.light;
|
||||
totalSquared += sample.light * sample.light;
|
||||
pixels += 1;
|
||||
const previous = x > start ? samples[y * width + x - 1] : null;
|
||||
const above = y > 0 ? samples[(y - 1) * width + x] : null;
|
||||
if (previous) { edges += Math.abs(sample.light - previous.light); edgeCount += 1; }
|
||||
if (above) { edges += Math.abs(sample.light - above.light); edgeCount += 1; }
|
||||
}
|
||||
}
|
||||
const mean = pixels ? total / pixels : 0;
|
||||
const variance = pixels ? Math.max(0, totalSquared / pixels - mean * mean) : 1;
|
||||
return Math.sqrt(variance) * 0.58 + (edgeCount ? edges / edgeCount : 1) * 0.42;
|
||||
};
|
||||
const zoneWidth = Math.max(1, Math.floor(width * 0.38));
|
||||
const leftInformation = information(0, zoneWidth);
|
||||
const rightInformation = information(width - zoneWidth, width);
|
||||
let safeArea = "center";
|
||||
if (leftInformation < rightInformation * 0.86) safeArea = "left";
|
||||
else if (rightInformation < leftInformation * 0.86) safeArea = "right";
|
||||
|
||||
let saliencyTotal = 0;
|
||||
let saliencyX = 0;
|
||||
let saliencyY = 0;
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
const sample = samples[y * width + x];
|
||||
if (!sample) continue;
|
||||
const previous = x > 0 ? samples[y * width + x - 1] : null;
|
||||
const above = y > 0 ? samples[(y - 1) * width + x] : null;
|
||||
const edge = (previous ? Math.abs(sample.light - previous.light) : 0) +
|
||||
(above ? Math.abs(sample.light - above.light) : 0);
|
||||
const weight = 0.01 + Math.abs(sample.light - brightness) * 0.48 +
|
||||
sample.saturation * 0.34 + edge * 0.28;
|
||||
saliencyTotal += weight;
|
||||
saliencyX += (x + 0.5) / width * weight;
|
||||
saliencyY += (y + 0.5) / height * weight;
|
||||
}
|
||||
}
|
||||
let focusX = saliencyTotal ? saliencyX / saliencyTotal : 0.5;
|
||||
let focusY = saliencyTotal ? saliencyY / saliencyTotal : 0.5;
|
||||
if (safeArea === "left") focusX = Math.max(0.64, focusX);
|
||||
if (safeArea === "right") focusX = Math.min(0.36, focusX);
|
||||
focusX = clamp(focusX, 0.12, 0.88);
|
||||
focusY = clamp(focusY, 0.18, 0.82);
|
||||
|
||||
const accentBin = bins.reduce((best, candidate) => candidate.weight > best.weight ? candidate : best, bins[0]);
|
||||
const accentRgb = accentBin.weight > 0 ? {
|
||||
r: accentBin.r / accentBin.weight,
|
||||
g: accentBin.g / accentBin.weight,
|
||||
b: accentBin.b / accentBin.weight,
|
||||
} : null;
|
||||
const aspect = ratio >= 2.25 ? "ultrawide" : ratio >= 1.45 ? "wide"
|
||||
: ratio >= 1.08 ? "landscape" : ratio >= 0.9 ? "square" : "portrait";
|
||||
finish({
|
||||
width: image.naturalWidth,
|
||||
height: image.naturalHeight,
|
||||
ratio,
|
||||
wide: ratio >= 1.75,
|
||||
aspect,
|
||||
brightness,
|
||||
shell: brightness >= 0.58 ? "light" : "dark",
|
||||
safeArea,
|
||||
focusX,
|
||||
focusY,
|
||||
taskMode: ratio >= 2.25 ? "banner" : "ambient",
|
||||
accentRgb,
|
||||
});
|
||||
} catch {
|
||||
finish(null);
|
||||
}
|
||||
};
|
||||
image.src = artUrl;
|
||||
});
|
||||
|
||||
let chromeParts = null;
|
||||
let observedShellMain = null;
|
||||
let resizeObserver = null;
|
||||
|
||||
const ensureStyle = (root) => {
|
||||
let style = document.getElementById(STYLE_ID);
|
||||
if (!style) {
|
||||
style = document.createElement("style");
|
||||
style.id = STYLE_ID;
|
||||
style.textContent = cssText;
|
||||
style.dataset.dreamSkinVersion = VERSION;
|
||||
(document.head || root).appendChild(style);
|
||||
} else if (style.dataset.dreamSkinStyleRevision !== STYLE_REVISION) {
|
||||
style.textContent = cssText;
|
||||
}
|
||||
style.dataset.dreamSkinVersion = VERSION;
|
||||
style.dataset.dreamSkinStyleRevision = STYLE_REVISION;
|
||||
return style;
|
||||
};
|
||||
|
||||
const applyRootState = (root) => {
|
||||
metrics.rootPasses += 1;
|
||||
ensureStyle(root);
|
||||
const shell = resolvedShell();
|
||||
setAttribute(root, SHELL_ATTR, shell);
|
||||
setStyleProperty(root, "--dream-skin-art", `url("${artUrl}")`);
|
||||
applyTheme(root, shell);
|
||||
applyArtMetadata(root);
|
||||
root.classList.add("codex-dream-skin");
|
||||
return shell;
|
||||
};
|
||||
|
||||
const syncRouteState = (shell, { layout = false } = {}) => {
|
||||
metrics.routePasses += 1;
|
||||
const root = document.documentElement;
|
||||
if (!root) return;
|
||||
shell ||= root.getAttribute(SHELL_ATTR) || resolvedShell();
|
||||
const shellMain = document.querySelector("main.main-surface") || document.querySelector("main");
|
||||
const homeIndicator = document.querySelector('[data-testid="home-icon"]');
|
||||
const home = homeIndicator?.closest('[role="main"]') ||
|
||||
[...document.querySelectorAll('[role="main"]')].find((candidate) =>
|
||||
candidate.querySelector('[data-feature="game-source"]') &&
|
||||
candidate.querySelector('[data-codex-composer-root]')) || null;
|
||||
for (const candidate of document.querySelectorAll('[role="main"].dream-skin-home')) {
|
||||
if (candidate !== home) candidate.classList.remove("dream-skin-home");
|
||||
}
|
||||
if (home) home.classList.add("dream-skin-home");
|
||||
const homeUtilityBars = new Set(home
|
||||
? home.querySelectorAll('[class*="_homeUtilityBar_"]')
|
||||
: []);
|
||||
for (const candidate of document.querySelectorAll(".dream-skin-home-utility")) {
|
||||
if (!homeUtilityBars.has(candidate)) candidate.classList.remove("dream-skin-home-utility");
|
||||
}
|
||||
for (const candidate of homeUtilityBars) candidate.classList.add("dream-skin-home-utility");
|
||||
|
||||
if (!shellMain || !document.body) return;
|
||||
if (observedShellMain !== shellMain) {
|
||||
resizeObserver?.disconnect();
|
||||
resizeObserver?.observe(shellMain);
|
||||
observedShellMain = shellMain;
|
||||
layout = true;
|
||||
}
|
||||
shellMain.classList.toggle("dream-skin-home-shell", Boolean(home));
|
||||
let chrome = document.getElementById(CHROME_ID);
|
||||
let created = false;
|
||||
if (!chrome || chrome.parentElement !== document.body) {
|
||||
chrome?.remove();
|
||||
chrome = document.createElement("div");
|
||||
chrome.id = CHROME_ID;
|
||||
chrome.setAttribute("aria-hidden", "true");
|
||||
chrome.innerHTML = `
|
||||
<div class="dream-skin-brand">
|
||||
<span class="dream-skin-portal-mark">◉</span>
|
||||
<span><b></b><small></small></span>
|
||||
</div>
|
||||
<div class="dream-skin-status"><i></i><span></span></div>
|
||||
<div class="dream-skin-quote"></div>
|
||||
<div class="dream-skin-particles"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div>
|
||||
<div class="dream-skin-orbit"></div>`;
|
||||
document.body.appendChild(chrome);
|
||||
created = true;
|
||||
chromeParts = null;
|
||||
}
|
||||
if (!chromeParts || chromeParts.chrome !== chrome) {
|
||||
chromeParts = {
|
||||
chrome,
|
||||
name: chrome.querySelector(".dream-skin-brand b"),
|
||||
subtitle: chrome.querySelector(".dream-skin-brand small"),
|
||||
status: chrome.querySelector(".dream-skin-status span"),
|
||||
quote: chrome.querySelector(".dream-skin-quote"),
|
||||
};
|
||||
}
|
||||
setTextContent(chromeParts.name, THEME.name || "Codex Dream Skin");
|
||||
setTextContent(chromeParts.subtitle, THEME.brandSubtitle || "CODEX DREAM SKIN");
|
||||
setTextContent(chromeParts.status, THEME.statusText || "DREAM SKIN ONLINE");
|
||||
setTextContent(chromeParts.quote, THEME.quote || "MAKE SOMETHING WONDERFUL");
|
||||
if (layout || created) {
|
||||
metrics.layoutReads += 1;
|
||||
const shellBox = shellMain.getBoundingClientRect();
|
||||
setStyleProperty(chrome, "left", `${Math.round(shellBox.left)}px`);
|
||||
setStyleProperty(chrome, "top", `${Math.round(shellBox.top)}px`);
|
||||
setStyleProperty(chrome, "width", `${Math.round(shellBox.width)}px`);
|
||||
setStyleProperty(chrome, "height", `${Math.round(shellBox.height)}px`);
|
||||
}
|
||||
chrome.classList.toggle("dream-skin-home-shell", Boolean(home));
|
||||
if (chrome.dataset.dreamShell !== shell) {
|
||||
chrome.dataset.dreamShell = shell;
|
||||
metrics.attributeWrites += 1;
|
||||
}
|
||||
};
|
||||
|
||||
const ensure = ({ root: rootPass = true, route = true, layout = true } = {}) => {
|
||||
if (window[DISABLED_KEY]) return;
|
||||
const root = document.documentElement;
|
||||
if (!root) return;
|
||||
metrics.ensureCalls += 1;
|
||||
const shell = rootPass ? applyRootState(root) : null;
|
||||
if (route) syncRouteState(shell, { layout });
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
const state = window[STATE_KEY];
|
||||
if (state?.installToken !== installToken) return false;
|
||||
window[DISABLED_KEY] = true;
|
||||
document.documentElement?.classList.remove("codex-dream-skin");
|
||||
document.documentElement?.removeAttribute(SHELL_ATTR);
|
||||
for (const name of ART_ATTRS) document.documentElement?.removeAttribute(name);
|
||||
document.documentElement?.style.removeProperty("--dream-skin-art");
|
||||
for (const name of THEME_VARIABLES) document.documentElement?.style.removeProperty(name);
|
||||
document.querySelectorAll(".dream-skin-home").forEach((node) => node.classList.remove("dream-skin-home"));
|
||||
document.querySelectorAll(".dream-skin-home-shell").forEach((node) => node.classList.remove("dream-skin-home-shell"));
|
||||
document.querySelectorAll(".dream-skin-home-utility").forEach((node) => node.classList.remove("dream-skin-home-utility"));
|
||||
document.getElementById(STYLE_ID)?.remove();
|
||||
document.getElementById(CHROME_ID)?.remove();
|
||||
state?.observer?.disconnect();
|
||||
state?.rootObserver?.disconnect();
|
||||
state?.resizeObserver?.disconnect();
|
||||
if (state?.timer) clearInterval(state.timer);
|
||||
if (state?.scheduler?.timeout) clearTimeout(state.scheduler.timeout);
|
||||
if (state?.scheduler?.frame != null && typeof cancelAnimationFrame === "function") {
|
||||
cancelAnimationFrame(state.scheduler.frame);
|
||||
}
|
||||
if (analysisTimer) clearTimeout(analysisTimer);
|
||||
if (state?.resizeHandler) window.removeEventListener("resize", state.resizeHandler);
|
||||
if (state?.mediaHandler && state?.mediaQuery) {
|
||||
try { state.mediaQuery.removeEventListener("change", state.mediaHandler); } catch {}
|
||||
}
|
||||
if (state?.artUrl) URL.revokeObjectURL(state.artUrl);
|
||||
delete window[STATE_KEY];
|
||||
return true;
|
||||
};
|
||||
|
||||
const scheduler = { timeout: null, frame: null, root: false, route: false, layout: false };
|
||||
const flushScheduledEnsure = () => {
|
||||
if (scheduler.frame !== null && typeof cancelAnimationFrame === "function") {
|
||||
cancelAnimationFrame(scheduler.frame);
|
||||
}
|
||||
if (scheduler.timeout) clearTimeout(scheduler.timeout);
|
||||
scheduler.frame = null;
|
||||
scheduler.timeout = null;
|
||||
const pending = { root: scheduler.root, route: scheduler.route, layout: scheduler.layout };
|
||||
scheduler.root = false;
|
||||
scheduler.route = false;
|
||||
scheduler.layout = false;
|
||||
ensure(pending);
|
||||
};
|
||||
const scheduleEnsure = ({ root = false, route = true, layout = false } = {}) => {
|
||||
scheduler.root ||= root;
|
||||
scheduler.route ||= route;
|
||||
scheduler.layout ||= layout;
|
||||
if (scheduler.timeout || scheduler.frame !== null) return;
|
||||
if (typeof requestAnimationFrame === "function") {
|
||||
scheduler.frame = requestAnimationFrame(flushScheduledEnsure);
|
||||
scheduler.timeout = setTimeout(flushScheduledEnsure, 96);
|
||||
} else {
|
||||
scheduler.timeout = setTimeout(flushScheduledEnsure, 64);
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(() => scheduleEnsure({ route: true }));
|
||||
rootObserver = new MutationObserver(() => {
|
||||
if (samplingNativeShell) return;
|
||||
scheduleEnsure({ root: true, route: true });
|
||||
});
|
||||
const resizeHandler = () => scheduleEnsure({ route: true, layout: true });
|
||||
if (typeof ResizeObserver === "function") {
|
||||
resizeObserver = new ResizeObserver(() => scheduleEnsure({ route: true, layout: true }));
|
||||
}
|
||||
|
||||
let mediaQuery = null;
|
||||
let mediaHandler = null;
|
||||
try {
|
||||
mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
mediaHandler = () => scheduleEnsure({ root: true, route: true });
|
||||
} catch {}
|
||||
|
||||
window[STATE_KEY] = {
|
||||
ensure,
|
||||
cleanup,
|
||||
observer,
|
||||
rootObserver,
|
||||
resizeObserver,
|
||||
timer: null,
|
||||
scheduler,
|
||||
resizeHandler,
|
||||
mediaQuery,
|
||||
mediaHandler,
|
||||
artUrl,
|
||||
installToken,
|
||||
analysis: artAnalysis,
|
||||
artMetadata: ART_METADATA,
|
||||
metrics,
|
||||
version: VERSION,
|
||||
themeId: THEME.id || "custom",
|
||||
detectShellMode,
|
||||
};
|
||||
const firstEnsureStartedAt = now();
|
||||
ensure({ layout: !previous || !document.getElementById(CHROME_ID) });
|
||||
metrics.firstEnsureMs = Number((now() - firstEnsureStartedAt).toFixed(3));
|
||||
if (previous?.artUrl && previous.artUrl !== artUrl) URL.revokeObjectURL(previous.artUrl);
|
||||
|
||||
observer.observe(document.documentElement, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
rootObserver.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ["class", "data-theme", "data-appearance", "data-color-mode", "style"],
|
||||
});
|
||||
if (document.body) {
|
||||
rootObserver.observe(document.body, {
|
||||
attributes: true,
|
||||
attributeFilter: ["class", "data-theme", "data-appearance", "data-color-mode", "style"],
|
||||
});
|
||||
}
|
||||
const timer = setInterval(() => ensure(), 4000);
|
||||
window[STATE_KEY].timer = timer;
|
||||
window.addEventListener("resize", resizeHandler, { passive: true });
|
||||
if (mediaHandler && mediaQuery) {
|
||||
mediaQuery.addEventListener("change", mediaHandler);
|
||||
}
|
||||
const analysisPromise = artAnalysis ? Promise.resolve(null) : analyzeArt();
|
||||
window[STATE_KEY].analysisTimer = analysisTimer;
|
||||
analysisPromise.then((analysis) => {
|
||||
const state = window[STATE_KEY];
|
||||
if (!analysis || state?.installToken !== installToken || window[DISABLED_KEY]) return;
|
||||
artAnalysis = analysis;
|
||||
state.analysis = analysis;
|
||||
if (typeof THEME.artKey === "string") {
|
||||
analysisCache.set(THEME.artKey, analysis);
|
||||
while (analysisCache.size > 8) analysisCache.delete(analysisCache.keys().next().value);
|
||||
}
|
||||
ensure({ root: true, route: false, layout: false });
|
||||
}).catch(() => {});
|
||||
return {
|
||||
installed: true,
|
||||
version: VERSION,
|
||||
themeId: THEME.id || "custom",
|
||||
shell: resolvedShell(),
|
||||
analysis: artAnalysis,
|
||||
};
|
||||
})(__DREAM_SKIN_CSS_JSON__, __DREAM_SKIN_ART_JSON__, __DREAM_SKIN_THEME_JSON__)
|
||||
@@ -1,131 +0,0 @@
|
||||
const SOF_MARKERS = new Set([
|
||||
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7,
|
||||
0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
|
||||
]);
|
||||
export const MAX_IMAGE_DIMENSION = 16384;
|
||||
export const MAX_IMAGE_PIXELS = 50_000_000;
|
||||
|
||||
function uint16be(bytes, offset) {
|
||||
return bytes[offset] * 256 + bytes[offset + 1];
|
||||
}
|
||||
|
||||
function uint16le(bytes, offset) {
|
||||
return bytes[offset] + bytes[offset + 1] * 256;
|
||||
}
|
||||
|
||||
function uint24le(bytes, offset) {
|
||||
return bytes[offset] + bytes[offset + 1] * 256 + bytes[offset + 2] * 65536;
|
||||
}
|
||||
|
||||
function uint32be(bytes, offset) {
|
||||
return bytes[offset] * 0x1000000 + bytes[offset + 1] * 0x10000 +
|
||||
bytes[offset + 2] * 0x100 + bytes[offset + 3];
|
||||
}
|
||||
|
||||
function uint32le(bytes, offset) {
|
||||
return bytes[offset] + bytes[offset + 1] * 0x100 + bytes[offset + 2] * 0x10000 +
|
||||
bytes[offset + 3] * 0x1000000;
|
||||
}
|
||||
|
||||
function ascii(bytes, offset, length) {
|
||||
return String.fromCharCode(...bytes.subarray(offset, offset + length));
|
||||
}
|
||||
|
||||
function pngDimensions(bytes) {
|
||||
const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
||||
if (bytes.length < 24 || signature.some((value, index) => bytes[index] !== value) ||
|
||||
uint32be(bytes, 8) !== 13 || ascii(bytes, 12, 4) !== "IHDR") return null;
|
||||
const width = uint32be(bytes, 16);
|
||||
const height = uint32be(bytes, 20);
|
||||
return width > 0 && height > 0 ? { width, height } : null;
|
||||
}
|
||||
|
||||
function jpegDimensions(bytes) {
|
||||
if (bytes.length < 12 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;
|
||||
let offset = 2;
|
||||
while (offset + 9 < bytes.length) {
|
||||
if (bytes[offset] !== 0xff) {
|
||||
offset += 1;
|
||||
continue;
|
||||
}
|
||||
while (offset < bytes.length && bytes[offset] === 0xff) offset += 1;
|
||||
const marker = bytes[offset++];
|
||||
if (marker === 0xd9 || marker === 0xda) break;
|
||||
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
|
||||
if (offset + 2 > bytes.length) break;
|
||||
const length = uint16be(bytes, offset);
|
||||
if (length < 2 || offset + length > bytes.length) break;
|
||||
if (SOF_MARKERS.has(marker) && length >= 7) {
|
||||
const height = uint16be(bytes, offset + 3);
|
||||
const width = uint16be(bytes, offset + 5);
|
||||
return width > 0 && height > 0 ? { width, height } : null;
|
||||
}
|
||||
offset += length;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function webpDimensions(bytes) {
|
||||
if (bytes.length < 20 || ascii(bytes, 0, 4) !== "RIFF" || ascii(bytes, 8, 4) !== "WEBP") {
|
||||
return null;
|
||||
}
|
||||
const riffEnd = Math.min(bytes.length, uint32le(bytes, 4) + 8);
|
||||
let offset = 12;
|
||||
while (offset + 8 <= riffEnd) {
|
||||
const type = ascii(bytes, offset, 4);
|
||||
const size = bytes[offset + 4] + bytes[offset + 5] * 256 +
|
||||
bytes[offset + 6] * 65536 + bytes[offset + 7] * 0x1000000;
|
||||
const data = offset + 8;
|
||||
if (data + size > riffEnd) break;
|
||||
if (type === "VP8X" && size >= 10) {
|
||||
return { width: uint24le(bytes, data + 4) + 1, height: uint24le(bytes, data + 7) + 1 };
|
||||
}
|
||||
if (type === "VP8L" && size >= 5 && bytes[data] === 0x2f) {
|
||||
const width = 1 + bytes[data + 1] + ((bytes[data + 2] & 0x3f) << 8);
|
||||
const height = 1 + (bytes[data + 2] >> 6) + (bytes[data + 3] << 2) +
|
||||
((bytes[data + 4] & 0x0f) << 10);
|
||||
return { width, height };
|
||||
}
|
||||
if (type === "VP8 " && size >= 10 && bytes[data + 3] === 0x9d &&
|
||||
bytes[data + 4] === 0x01 && bytes[data + 5] === 0x2a) {
|
||||
return {
|
||||
width: uint16le(bytes, data + 6) & 0x3fff,
|
||||
height: uint16le(bytes, data + 8) & 0x3fff,
|
||||
};
|
||||
}
|
||||
offset = data + size + (size % 2);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function classifyImageDimensions({ width, height }) {
|
||||
const ratio = width / height;
|
||||
if (
|
||||
!Number.isSafeInteger(width) || !Number.isSafeInteger(height)
|
||||
|| width < 1 || height < 1
|
||||
|| width > MAX_IMAGE_DIMENSION || height > MAX_IMAGE_DIMENSION
|
||||
|| width * height > MAX_IMAGE_PIXELS
|
||||
|| !Number.isFinite(ratio)
|
||||
) return null;
|
||||
const aspect = ratio >= 2.25 ? "ultrawide" : ratio >= 1.45 ? "wide"
|
||||
: ratio >= 1.08 ? "landscape" : ratio >= 0.9 ? "square" : "portrait";
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
ratio,
|
||||
wide: ratio >= 1.75,
|
||||
aspect,
|
||||
taskMode: ratio >= 2.25 ? "banner" : "ambient",
|
||||
};
|
||||
}
|
||||
|
||||
export function readImageMetadata(value, extension = "") {
|
||||
const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
|
||||
const normalized = extension.toLowerCase();
|
||||
let dimensions = null;
|
||||
if (normalized === ".png" || bytes[0] === 0x89) dimensions = pngDimensions(bytes);
|
||||
else if (normalized === ".jpg" || normalized === ".jpeg" ||
|
||||
(bytes[0] === 0xff && bytes[1] === 0xd8)) dimensions = jpegDimensions(bytes);
|
||||
else if (normalized === ".webp" || ascii(bytes, 8, 4) === "WEBP") dimensions = webpDimensions(bytes);
|
||||
return dimensions ? classifyImageDimensions(dimensions) : null;
|
||||
}
|
||||
@@ -1,913 +0,0 @@
|
||||
import fs from "node:fs/promises";
|
||||
import { constants as fsConstants, watch as watchFs } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { readImageMetadata } from "./image-metadata.mjs";
|
||||
|
||||
const scriptPath = fileURLToPath(import.meta.url);
|
||||
const here = path.dirname(scriptPath);
|
||||
const root = path.resolve(here, "..");
|
||||
const SKIN_VERSION = "1.2.3";
|
||||
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
|
||||
const CDP_ID_PATTERN = /^[A-Za-z0-9._-]{1,200}$/;
|
||||
const MAX_ART_BYTES = 16 * 1024 * 1024;
|
||||
let staticPayloadAssets = null;
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
port: 9341,
|
||||
mode: "watch",
|
||||
timeoutMs: 30000,
|
||||
screenshot: null,
|
||||
reload: false,
|
||||
themeDir: null,
|
||||
};
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === "--port") options.port = Number(argv[++i]);
|
||||
else if (arg === "--once") options.mode = "once";
|
||||
else if (arg === "--watch") options.mode = "watch";
|
||||
else if (arg === "--verify") options.mode = "verify";
|
||||
else if (arg === "--remove") options.mode = "remove";
|
||||
else if (arg === "--check-payload") options.mode = "check";
|
||||
else if (arg === "--timeout-ms") options.timeoutMs = Number(argv[++i]);
|
||||
else if (arg === "--screenshot") options.screenshot = path.resolve(argv[++i]);
|
||||
else if (arg === "--theme-dir") options.themeDir = path.resolve(argv[++i]);
|
||||
else if (arg === "--reload") options.reload = true;
|
||||
else throw new Error(`Unknown argument: ${arg}`);
|
||||
}
|
||||
if (!Number.isInteger(options.port) || options.port < 1024 || options.port > 65535) {
|
||||
throw new Error(`Invalid port: ${options.port}`);
|
||||
}
|
||||
if (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 250 || options.timeoutMs > 120000) {
|
||||
throw new Error(`Invalid timeout: ${options.timeoutMs}`);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function validatedDebuggerUrl(target, port) {
|
||||
const url = new URL(target.webSocketDebuggerUrl);
|
||||
const pathIsValid = /^\/devtools\/page\/[A-Za-z0-9._-]{1,200}$/.test(url.pathname);
|
||||
if (
|
||||
url.protocol !== "ws:" || !LOOPBACK_HOSTS.has(url.hostname) || Number(url.port) !== port
|
||||
|| url.username || url.password || url.search || url.hash || !pathIsValid
|
||||
) {
|
||||
throw new Error("Rejected a CDP WebSocket URL outside the allowed loopback page endpoint shape");
|
||||
}
|
||||
return url.href;
|
||||
}
|
||||
|
||||
function isValidCdpPageTarget(item, port) {
|
||||
if (
|
||||
item?.type !== "page" || !item.url?.startsWith("app://")
|
||||
|| typeof item.id !== "string" || !CDP_ID_PATTERN.test(item.id)
|
||||
|| !item.webSocketDebuggerUrl
|
||||
) return false;
|
||||
try {
|
||||
const debuggerUrl = new URL(validatedDebuggerUrl(item, port));
|
||||
return debuggerUrl.pathname === `/devtools/page/${item.id}`;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class CdpSession {
|
||||
constructor(target, port) {
|
||||
this.target = target;
|
||||
this.ws = new WebSocket(validatedDebuggerUrl(target, port));
|
||||
this.nextId = 1;
|
||||
this.pending = new Map();
|
||||
this.listeners = new Map();
|
||||
this.closed = false;
|
||||
}
|
||||
|
||||
async open() {
|
||||
await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
try { this.ws.close(); } catch {}
|
||||
reject(new Error("CDP WebSocket open timed out"));
|
||||
}, 5000);
|
||||
this.ws.addEventListener("open", () => { clearTimeout(timeout); resolve(); }, { once: true });
|
||||
this.ws.addEventListener("error", () => { clearTimeout(timeout); reject(new Error("CDP WebSocket open failed")); }, { once: true });
|
||||
});
|
||||
this.ws.addEventListener("message", (event) => this.onMessage(event));
|
||||
this.ws.addEventListener("error", () => this.close());
|
||||
this.ws.addEventListener("close", () => {
|
||||
this.closed = true;
|
||||
for (const waiter of this.pending.values()) {
|
||||
clearTimeout(waiter.timeout);
|
||||
waiter.reject(new Error("CDP socket closed"));
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
await this.send("Runtime.enable");
|
||||
await this.send("Page.enable");
|
||||
return this;
|
||||
}
|
||||
|
||||
onMessage(event) {
|
||||
let message;
|
||||
try {
|
||||
message = JSON.parse(String(event.data));
|
||||
} catch {
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
if (!message || typeof message !== "object") {
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
if (message.id) {
|
||||
const waiter = this.pending.get(message.id);
|
||||
if (!waiter) return;
|
||||
clearTimeout(waiter.timeout);
|
||||
this.pending.delete(message.id);
|
||||
if (message.error) waiter.reject(new Error(`${message.error.message} (${message.error.code})`));
|
||||
else waiter.resolve(message.result);
|
||||
return;
|
||||
}
|
||||
for (const listener of this.listeners.get(message.method) ?? []) {
|
||||
try { listener(message.params ?? {}); } catch (error) {
|
||||
console.error(`[dream-skin] CDP listener failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
on(method, listener) {
|
||||
const listeners = this.listeners.get(method) ?? [];
|
||||
listeners.push(listener);
|
||||
this.listeners.set(method, listeners);
|
||||
}
|
||||
|
||||
send(method, params = {}, timeoutMs = 10000) {
|
||||
if (this.closed) return Promise.reject(new Error("CDP session is closed"));
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = this.nextId++;
|
||||
const timeout = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`CDP command timed out: ${method}`));
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, { resolve, reject, timeout });
|
||||
try {
|
||||
this.ws.send(JSON.stringify({ id, method, params }));
|
||||
} catch (error) {
|
||||
clearTimeout(timeout);
|
||||
this.pending.delete(id);
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async evaluate(expression) {
|
||||
const result = await this.send("Runtime.evaluate", {
|
||||
expression,
|
||||
awaitPromise: true,
|
||||
returnByValue: true,
|
||||
userGesture: false,
|
||||
});
|
||||
if (result.exceptionDetails) {
|
||||
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.text;
|
||||
throw new Error(`Renderer evaluation failed: ${detail}`);
|
||||
}
|
||||
return result.result?.value;
|
||||
}
|
||||
|
||||
close() {
|
||||
for (const waiter of this.pending.values()) {
|
||||
clearTimeout(waiter.timeout);
|
||||
waiter.reject(new Error("CDP session closed"));
|
||||
}
|
||||
this.pending.clear();
|
||||
if (!this.closed) {
|
||||
try { this.ws.close(); } catch {}
|
||||
}
|
||||
this.closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function listAppTargets(port) {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 2000);
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/json/list`, {
|
||||
redirect: "error",
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const targets = await response.json();
|
||||
if (!Array.isArray(targets)) throw new Error("CDP target list was not an array");
|
||||
return targets.filter((item) => isValidCdpPageTarget(item, port));
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
async function probeSession(session) {
|
||||
return session.evaluate(`(() => {
|
||||
const markers = {
|
||||
shell: Boolean(document.querySelector('main.main-surface')),
|
||||
sidebar: Boolean(document.querySelector('aside.app-shell-left-panel')),
|
||||
composer: Boolean(document.querySelector('.composer-surface-chrome')),
|
||||
main: Boolean(document.querySelector('[role="main"]')),
|
||||
};
|
||||
return {
|
||||
title: document.title,
|
||||
href: location.href,
|
||||
markers,
|
||||
codex: markers.shell && markers.sidebar,
|
||||
};
|
||||
})()`);
|
||||
}
|
||||
|
||||
async function waitForCodexProbe(session, timeoutMs = 1800) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let probe = null;
|
||||
while (Date.now() < deadline) {
|
||||
probe = await probeSession(session);
|
||||
if (probe?.codex) return probe;
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
return probe;
|
||||
}
|
||||
|
||||
async function connectTarget(target, port) {
|
||||
return new CdpSession(target, port).open();
|
||||
}
|
||||
|
||||
async function connectCodexTargets(port, timeoutMs) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let lastError;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const targets = await listAppTargets(port);
|
||||
const connected = [];
|
||||
for (const target of targets) {
|
||||
let session;
|
||||
try {
|
||||
session = await connectTarget(target, port);
|
||||
const probe = await probeSession(session);
|
||||
if (probe?.codex) connected.push({ target, session, probe });
|
||||
else session.close();
|
||||
} catch (error) {
|
||||
session?.close();
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
if (connected.length) return connected;
|
||||
lastError = new Error("No page matched the expected Codex shell markers");
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 350));
|
||||
}
|
||||
throw new Error(`No verified Codex renderer on 127.0.0.1:${port}: ${lastError?.message ?? "timed out"}`);
|
||||
}
|
||||
|
||||
function assertContainedPath(rootPath, candidatePath, label) {
|
||||
const relative = path.relative(rootPath, candidatePath);
|
||||
if (
|
||||
relative === ""
|
||||
|| (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`))
|
||||
) return;
|
||||
throw new Error(`${label} must stay inside its theme directory`);
|
||||
}
|
||||
|
||||
async function loadTheme(themeDir) {
|
||||
const requestedRoot = themeDir ?? path.join(root, "assets");
|
||||
const configPath = path.join(requestedRoot, "theme.json");
|
||||
let assetsRoot;
|
||||
let canonicalConfigPath;
|
||||
try {
|
||||
[assetsRoot, canonicalConfigPath] = await Promise.all([
|
||||
fs.realpath(requestedRoot),
|
||||
fs.realpath(configPath),
|
||||
]);
|
||||
} catch (error) {
|
||||
if (themeDir && error.code === "ENOENT") {
|
||||
throw new Error(`Explicit theme directory is missing theme.json: ${configPath}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
assertContainedPath(assetsRoot, canonicalConfigPath, "Theme config");
|
||||
let config;
|
||||
try {
|
||||
config = await fs.readFile(canonicalConfigPath, "utf8");
|
||||
} catch (error) {
|
||||
if (themeDir && error.code === "ENOENT") {
|
||||
throw new Error(`Explicit theme directory is missing theme.json: ${configPath}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const raw = JSON.parse(config);
|
||||
if (raw.schemaVersion !== 1 || typeof raw.image !== "string" || !raw.image) {
|
||||
throw new Error(`${configPath} has an unsupported schema or image field`);
|
||||
}
|
||||
if (/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(raw.image)) {
|
||||
throw new Error(`${configPath} has an invalid image field`);
|
||||
}
|
||||
if (path.basename(raw.image) !== raw.image) throw new Error("Theme image must stay inside its theme directory");
|
||||
const text = (value, fallback, max, name) => {
|
||||
if (value === undefined) return fallback;
|
||||
if (typeof value !== "string" || /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(value)) {
|
||||
throw new Error(`${configPath} has an invalid ${name} field`);
|
||||
}
|
||||
return value.trim() ? Array.from(value.trim()).slice(0, max).join("") : fallback;
|
||||
};
|
||||
const color = (value, fallback) => {
|
||||
if (typeof value !== "string") return fallback;
|
||||
const normalized = value.trim();
|
||||
return /^#[0-9a-f]{6}$/i.test(normalized) || /^rgba?\([0-9., %]+\)$/i.test(normalized)
|
||||
? normalized
|
||||
: fallback;
|
||||
};
|
||||
const choice = (value, name, choices) => {
|
||||
if (value === undefined) return undefined;
|
||||
if (typeof value !== "string" || !choices.includes(value)) {
|
||||
throw new Error(`${configPath} has an invalid ${name} field`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
const unit = (value, name) => {
|
||||
if (value === undefined) return undefined;
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {
|
||||
throw new Error(`${configPath} has an invalid ${name} field`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
const rawColors = raw.colors && typeof raw.colors === "object" && !Array.isArray(raw.colors)
|
||||
? raw.colors : null;
|
||||
const colorKeys = [
|
||||
"background", "panel", "panelAlt", "accent", "accentAlt", "secondary",
|
||||
"highlight", "text", "muted", "line",
|
||||
];
|
||||
const appearance = choice(raw.appearance, "appearance", ["auto", "light", "dark"]);
|
||||
const surfaceOpacity = unit(raw.surfaceOpacity, "surfaceOpacity");
|
||||
if (raw.art !== undefined && (!raw.art || typeof raw.art !== "object" || Array.isArray(raw.art))) {
|
||||
throw new Error(`${configPath} has an invalid art field`);
|
||||
}
|
||||
const rawArt = raw.art || {};
|
||||
const art = {
|
||||
focusX: unit(rawArt.focusX, "art.focusX"),
|
||||
focusY: unit(rawArt.focusY, "art.focusY"),
|
||||
safeArea: choice(rawArt.safeArea, "art.safeArea", ["auto", "left", "right", "center", "none"]),
|
||||
taskMode: choice(rawArt.taskMode, "art.taskMode", ["auto", "ambient", "banner", "off"]),
|
||||
};
|
||||
const theme = {
|
||||
schemaVersion: 1,
|
||||
id: text(raw.id, "custom", 80, "id"),
|
||||
name: text(raw.name, "Codex Dream Skin", 80, "name"),
|
||||
brandSubtitle: text(raw.brandSubtitle, "CODEX DREAM SKIN", 80, "brandSubtitle"),
|
||||
tagline: text(raw.tagline, "Make something wonderful.", 160, "tagline"),
|
||||
projectPrefix: text(raw.projectPrefix, "选择项目 · ", 80, "projectPrefix"),
|
||||
projectLabel: text(raw.projectLabel, "◉ 选择项目", 80, "projectLabel"),
|
||||
statusText: text(raw.statusText, "DREAM SKIN ONLINE", 80, "statusText"),
|
||||
quote: text(raw.quote, "MAKE SOMETHING WONDERFUL", 80, "quote"),
|
||||
image: raw.image,
|
||||
surfaceOpacity: surfaceOpacity ?? 1,
|
||||
colorMode: rawColors ? "explicit" : "auto",
|
||||
explicitColorKeys: rawColors ? colorKeys.filter((key) => Object.hasOwn(rawColors, key)) : [],
|
||||
colors: {
|
||||
background: color(rawColors?.background, "#071116"),
|
||||
panel: color(rawColors?.panel, "#0b1a20"),
|
||||
panelAlt: color(rawColors?.panelAlt, "#10272c"),
|
||||
accent: color(rawColors?.accent, "#7cff46"),
|
||||
accentAlt: color(rawColors?.accentAlt, "#b8ff3d"),
|
||||
secondary: color(rawColors?.secondary, "#36d7e8"),
|
||||
highlight: color(rawColors?.highlight, "#642a8c"),
|
||||
text: color(rawColors?.text, "#e9fff1"),
|
||||
muted: color(rawColors?.muted, "#9ebdb3"),
|
||||
line: color(rawColors?.line, "rgba(124, 255, 70, .28)"),
|
||||
},
|
||||
};
|
||||
if (appearance !== undefined) theme.appearance = appearance;
|
||||
if (Object.values(art).some((value) => value !== undefined)) {
|
||||
theme.art = Object.fromEntries(Object.entries(art).filter(([, value]) => value !== undefined));
|
||||
}
|
||||
const requestedImagePath = path.join(assetsRoot, theme.image);
|
||||
let imagePath;
|
||||
try {
|
||||
imagePath = await fs.realpath(requestedImagePath);
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT") throw new Error(`Theme image is missing: ${requestedImagePath}`);
|
||||
throw error;
|
||||
}
|
||||
assertContainedPath(assetsRoot, imagePath, "Theme image");
|
||||
const imageStat = await fs.stat(imagePath);
|
||||
const extension = path.extname(theme.image).toLowerCase();
|
||||
if (![".png", ".jpg", ".jpeg", ".webp"].includes(extension)) {
|
||||
throw new Error(`Unsupported theme image format: ${extension || "missing"}`);
|
||||
}
|
||||
let imageHandle;
|
||||
try {
|
||||
imageHandle = await fs.open(imagePath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
|
||||
} catch (error) {
|
||||
if (error.code === "ELOOP") throw new Error("Theme image changed into a symbolic link while loading");
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
const openedStat = await imageHandle.stat();
|
||||
if (
|
||||
!imageStat.isFile()
|
||||
|| !openedStat.isFile()
|
||||
|| imageStat.dev !== openedStat.dev
|
||||
|| imageStat.ino !== openedStat.ino
|
||||
|| openedStat.size < 1
|
||||
|| openedStat.size > MAX_ART_BYTES
|
||||
) {
|
||||
throw new Error(`Theme image must be a stable non-empty file no larger than ${MAX_ART_BYTES} bytes`);
|
||||
}
|
||||
const art = await imageHandle.readFile();
|
||||
if (art.length < 1 || art.length > MAX_ART_BYTES) {
|
||||
throw new Error(`Theme image must be a non-empty file no larger than ${MAX_ART_BYTES} bytes`);
|
||||
}
|
||||
return { art, assetsRoot, extension, imagePath, theme };
|
||||
} finally {
|
||||
await imageHandle.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStaticPayloadAssets() {
|
||||
const cacheHit = Boolean(staticPayloadAssets);
|
||||
if (!staticPayloadAssets) {
|
||||
staticPayloadAssets = Promise.all([
|
||||
fs.readFile(path.join(root, "assets", "dream-skin.css"), "utf8"),
|
||||
fs.readFile(path.join(root, "assets", "renderer-inject.js"), "utf8"),
|
||||
]).catch((error) => {
|
||||
staticPayloadAssets = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
const [css, template] = await staticPayloadAssets;
|
||||
return { css, template, cacheHit };
|
||||
}
|
||||
|
||||
function invalidateStaticPayloadAssets() {
|
||||
staticPayloadAssets = null;
|
||||
}
|
||||
|
||||
async function loadPayload(themeDir) {
|
||||
const startedAt = performance.now();
|
||||
const [staticAssets, loaded] = await Promise.all([
|
||||
loadStaticPayloadAssets(),
|
||||
loadTheme(themeDir),
|
||||
]);
|
||||
const { css, template } = staticAssets;
|
||||
const { art, extension, theme } = loaded;
|
||||
const styleRevision = createHash("sha256").update(css).digest("hex").slice(0, 20);
|
||||
const artMetadata = readImageMetadata(art, extension);
|
||||
if (!artMetadata) {
|
||||
throw new Error("Theme image metadata is invalid or exceeds the 16384px / 50MP safety limit");
|
||||
}
|
||||
const artKey = createHash("sha256").update(art).digest("hex").slice(0, 20);
|
||||
theme.artMetadata = artMetadata;
|
||||
theme.artKey = artKey;
|
||||
const mime = extension === ".jpg" || extension === ".jpeg" ? "image/jpeg"
|
||||
: extension === ".webp" ? "image/webp" : "image/png";
|
||||
const artDataUrl = `data:${mime};base64,${art.toString("base64")}`;
|
||||
const payload = template
|
||||
.replace("__DREAM_SKIN_CSS_JSON__", JSON.stringify(css))
|
||||
.replace("__DREAM_SKIN_ART_JSON__", JSON.stringify(artDataUrl))
|
||||
.replace("__DREAM_SKIN_THEME_JSON__", JSON.stringify(theme))
|
||||
.replace("__DREAM_SKIN_VERSION_JSON__", JSON.stringify(SKIN_VERSION))
|
||||
.replace("__DREAM_SKIN_STYLE_REVISION_JSON__", JSON.stringify(styleRevision));
|
||||
const revision = createHash("sha256")
|
||||
.update(SKIN_VERSION)
|
||||
.update(css)
|
||||
.update(template)
|
||||
.update(JSON.stringify(theme))
|
||||
.digest("hex")
|
||||
.slice(0, 20);
|
||||
return {
|
||||
imageBytes: art.length,
|
||||
payload,
|
||||
revision,
|
||||
theme,
|
||||
timings: {
|
||||
buildMs: Number((performance.now() - startedAt).toFixed(3)),
|
||||
staticCacheHit: staticAssets.cacheHit,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function applyToSession(session, payload) {
|
||||
return session.evaluate(payload);
|
||||
}
|
||||
|
||||
async function removeFromSession(session) {
|
||||
return session.evaluate(`(() => {
|
||||
window.__CODEX_DREAM_SKIN_DISABLED__ = true;
|
||||
const state = window.__CODEX_DREAM_SKIN_STATE__;
|
||||
if (state?.cleanup) return state.cleanup();
|
||||
document.documentElement?.classList.remove('codex-dream-skin');
|
||||
document.documentElement?.style.removeProperty('--dream-skin-art');
|
||||
document.getElementById('codex-dream-skin-style')?.remove();
|
||||
document.getElementById('codex-dream-skin-chrome')?.remove();
|
||||
delete window.__CODEX_DREAM_SKIN_STATE__;
|
||||
return true;
|
||||
})()`);
|
||||
}
|
||||
|
||||
async function verifyRemovedSession(session) {
|
||||
return session.evaluate(`(() =>
|
||||
!document.documentElement.classList.contains('codex-dream-skin') &&
|
||||
!document.getElementById('codex-dream-skin-style') &&
|
||||
!document.getElementById('codex-dream-skin-chrome') &&
|
||||
!window.__CODEX_DREAM_SKIN_STATE__
|
||||
)()`);
|
||||
}
|
||||
|
||||
async function verifySession(session) {
|
||||
return session.evaluate(`(() => {
|
||||
const box = (node) => {
|
||||
if (!node) return null;
|
||||
const r = node.getBoundingClientRect();
|
||||
const style = getComputedStyle(node);
|
||||
return {
|
||||
x: Math.round(r.x), y: Math.round(r.y),
|
||||
width: Math.round(r.width), height: Math.round(r.height),
|
||||
visible: r.width > 0 && r.height > 0 && style.display !== 'none' && style.visibility !== 'hidden',
|
||||
};
|
||||
};
|
||||
const homeIndicator = document.querySelector('[data-testid="home-icon"]');
|
||||
const homeSignal = homeIndicator ?? document.querySelector('[data-feature="game-source"]') ??
|
||||
document.querySelector('.group\\\\/home-suggestions');
|
||||
const homeRoute = homeSignal?.closest('[role="main"]') ?? null;
|
||||
const home = document.querySelector('[role="main"].dream-skin-home');
|
||||
const suggestions = home?.querySelector('.group\\\\/home-suggestions') ?? null;
|
||||
const cardBoxes = suggestions ? [...suggestions.querySelectorAll('button')].map(box) : [];
|
||||
const visibleCards = cardBoxes.filter((item) => item?.visible);
|
||||
const hero = box(home?.firstElementChild?.firstElementChild?.firstElementChild);
|
||||
const projectButton = box(home?.querySelector('.group\\\\/project-selector > button'));
|
||||
const shell = box(document.querySelector('main.main-surface'));
|
||||
const composer = box(document.querySelector('.composer-surface-chrome'));
|
||||
const sidebar = box(document.querySelector('aside.app-shell-left-panel'));
|
||||
const chrome = document.getElementById('codex-dream-skin-chrome');
|
||||
const result = {
|
||||
installed: document.documentElement.classList.contains('codex-dream-skin'),
|
||||
version: window.__CODEX_DREAM_SKIN_STATE__?.version ?? null,
|
||||
stylePresent: Boolean(document.getElementById('codex-dream-skin-style')),
|
||||
chromePresent: Boolean(chrome),
|
||||
chromePointerEvents: getComputedStyle(chrome || document.body).pointerEvents,
|
||||
homeRoute: Boolean(homeRoute),
|
||||
homePresent: Boolean(home),
|
||||
hero,
|
||||
cards: cardBoxes,
|
||||
visibleCardCount: visibleCards.length,
|
||||
projectButton,
|
||||
shell,
|
||||
composer,
|
||||
sidebar,
|
||||
viewport: { width: innerWidth, height: innerHeight },
|
||||
documentOverflow: {
|
||||
x: document.documentElement.scrollWidth > document.documentElement.clientWidth,
|
||||
y: document.documentElement.scrollHeight > document.documentElement.clientHeight,
|
||||
},
|
||||
};
|
||||
const basePass = result.installed && result.version === ${JSON.stringify(SKIN_VERSION)} &&
|
||||
result.stylePresent && result.chromePresent && result.chromePointerEvents === 'none' &&
|
||||
Boolean(result.shell?.visible) && Boolean(result.sidebar?.visible) && !result.documentOverflow.x;
|
||||
// Project selector markup varies across Codex builds — soft requirement.
|
||||
const homePass = !result.homeRoute || (
|
||||
result.homePresent && result.hero?.visible && result.hero.width >= 280 && result.hero.height >= 120
|
||||
);
|
||||
result.pass = Boolean(basePass && homePass);
|
||||
result.softNotes = {
|
||||
projectButtonOptional: !result.projectButton?.visible,
|
||||
composerOptionalOnNonTaskRoutes: !result.composer?.visible,
|
||||
suggestionCardsOptional: result.homeRoute && result.visibleCardCount === 0,
|
||||
};
|
||||
return result;
|
||||
})()`);
|
||||
}
|
||||
|
||||
async function waitForVerifiedSession(session, timeoutMs) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let lastResult;
|
||||
while (Date.now() < deadline) {
|
||||
lastResult = await verifySession(session);
|
||||
if (lastResult.pass) return lastResult;
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
}
|
||||
return lastResult;
|
||||
}
|
||||
|
||||
async function capture(session, outputPath) {
|
||||
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
||||
const bestEffortInput = async (method, params) => {
|
||||
try {
|
||||
await session.send(method, params, 750);
|
||||
} catch {
|
||||
// Screenshot capture is still valid when a renderer omits the Input domain.
|
||||
}
|
||||
};
|
||||
await bestEffortInput("Input.dispatchKeyEvent", {
|
||||
type: "keyDown", key: "Escape", code: "Escape", windowsVirtualKeyCode: 27,
|
||||
});
|
||||
await bestEffortInput("Input.dispatchKeyEvent", {
|
||||
type: "keyUp", key: "Escape", code: "Escape", windowsVirtualKeyCode: 27,
|
||||
});
|
||||
const viewport = await session.evaluate("({ width: innerWidth, height: innerHeight })");
|
||||
await bestEffortInput("Input.dispatchMouseEvent", {
|
||||
type: "mouseMoved",
|
||||
x: Math.round(viewport.width * 0.64),
|
||||
y: Math.round(viewport.height * 0.62),
|
||||
button: "none",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
const result = await session.send("Page.captureScreenshot", {
|
||||
format: "png",
|
||||
fromSurface: true,
|
||||
captureBeyondViewport: false,
|
||||
});
|
||||
await fs.writeFile(outputPath, Buffer.from(result.data, "base64"));
|
||||
}
|
||||
|
||||
async function runOneShot(options) {
|
||||
const connected = await connectCodexTargets(options.port, options.timeoutMs);
|
||||
const loaded = (options.mode === "once" || options.reload) ? await loadPayload(options.themeDir) : null;
|
||||
const payload = loaded?.payload ?? null;
|
||||
const results = [];
|
||||
let screenshotCaptured = false;
|
||||
|
||||
for (const { target, session, probe } of connected) {
|
||||
try {
|
||||
if (options.mode === "remove") await removeFromSession(session);
|
||||
else if (options.mode === "once") await applyToSession(session, payload);
|
||||
|
||||
if (options.reload) {
|
||||
await session.send("Page.reload", { ignoreCache: true });
|
||||
await new Promise((resolve) => setTimeout(resolve, 1600));
|
||||
if (options.mode !== "remove") await applyToSession(session, payload);
|
||||
}
|
||||
|
||||
const result = options.mode === "remove"
|
||||
? await verifyRemovedSession(session)
|
||||
: await waitForVerifiedSession(session, options.timeoutMs);
|
||||
results.push({ targetId: target.id, title: target.title, url: target.url, probe, result });
|
||||
|
||||
if (options.screenshot && !screenshotCaptured) {
|
||||
await capture(session, options.screenshot);
|
||||
screenshotCaptured = true;
|
||||
}
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
|
||||
console.log(JSON.stringify({ mode: options.mode, version: SKIN_VERSION, port: options.port, targets: results }, null, 2));
|
||||
const failed = results.length === 0 || results.some((item) => options.mode === "remove" ? item.result !== true : !item.result?.pass);
|
||||
if (failed) process.exitCode = 2;
|
||||
}
|
||||
|
||||
async function flushStandardStreams() {
|
||||
const flush = (stream) => new Promise((resolve) => {
|
||||
if (!stream?.writable || stream.destroyed) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
stream.write("", resolve);
|
||||
});
|
||||
await Promise.all([flush(process.stdout), flush(process.stderr)]);
|
||||
}
|
||||
|
||||
export function earlyPayloadFor(payload, revision) {
|
||||
return `(() => {
|
||||
const generationKey = "__CODEX_DREAM_SKIN_EARLY_GENERATION__";
|
||||
const appliedKey = "__CODEX_DREAM_SKIN_EARLY_APPLIED__";
|
||||
const generation = ${JSON.stringify(revision)};
|
||||
window[generationKey] = generation;
|
||||
let observer = null;
|
||||
let timeout = null;
|
||||
const stop = () => {
|
||||
observer?.disconnect();
|
||||
observer = null;
|
||||
if (timeout) clearTimeout(timeout);
|
||||
timeout = null;
|
||||
};
|
||||
const install = () => {
|
||||
if (window[generationKey] !== generation) { stop(); return true; }
|
||||
if (!document.documentElement) return false;
|
||||
const shell = document.querySelector('main.main-surface');
|
||||
const sidebar = document.querySelector('aside.app-shell-left-panel');
|
||||
if (!shell || !sidebar) return false;
|
||||
stop();
|
||||
${payload};
|
||||
window[appliedKey] = generation;
|
||||
return true;
|
||||
};
|
||||
if (install()) return;
|
||||
if (typeof MutationObserver === "function" && document.documentElement) {
|
||||
observer = new MutationObserver(install);
|
||||
observer.observe(document.documentElement, { childList: true, subtree: true });
|
||||
}
|
||||
timeout = setTimeout(stop, 10000);
|
||||
})()`;
|
||||
}
|
||||
|
||||
function watchPayloadSources(themeDir, onDirty) {
|
||||
const assetsRoot = path.join(root, "assets");
|
||||
const themeRoot = themeDir ?? assetsRoot;
|
||||
const watchers = [];
|
||||
const add = (directory, kind) => {
|
||||
let watcher;
|
||||
try {
|
||||
watcher = watchFs(directory, { persistent: false }, (_event, filename) => {
|
||||
const name = filename ? String(filename) : "";
|
||||
const staticChanged = directory === assetsRoot &&
|
||||
(!name || name === "dream-skin.css" || name === "renderer-inject.js");
|
||||
if (kind === "static" && !staticChanged) return;
|
||||
onDirty({ staticChanged });
|
||||
});
|
||||
watcher.on("error", (error) => {
|
||||
console.error(`[dream-skin] file watch unavailable for ${directory}: ${error.message}`);
|
||||
});
|
||||
watchers.push(watcher);
|
||||
} catch (error) {
|
||||
console.error(`[dream-skin] file watch unavailable for ${directory}: ${error.message}`);
|
||||
}
|
||||
};
|
||||
add(themeRoot, "theme");
|
||||
if (themeRoot !== assetsRoot) add(assetsRoot, "static");
|
||||
return () => watchers.forEach((watcher) => watcher.close());
|
||||
}
|
||||
|
||||
async function runWatch(options) {
|
||||
let current = await loadPayload(options.themeDir);
|
||||
const sessions = new Map();
|
||||
const rejected = new Set();
|
||||
let stopping = false;
|
||||
let reloadTimer = null;
|
||||
let reloadChain = Promise.resolve();
|
||||
let discoveryDelayMs = 100;
|
||||
let lastListErrorAt = 0;
|
||||
const stop = () => { stopping = true; };
|
||||
process.on("SIGINT", stop);
|
||||
process.on("SIGTERM", stop);
|
||||
|
||||
const registerEarly = async (session, payload, revision) => {
|
||||
const result = await session.send("Page.addScriptToEvaluateOnNewDocument", {
|
||||
source: earlyPayloadFor(payload, revision),
|
||||
});
|
||||
return result.identifier ?? null;
|
||||
};
|
||||
|
||||
const removeEarly = async (record) => {
|
||||
if (!record.earlyScriptId || record.session.closed) return;
|
||||
const identifier = record.earlyScriptId;
|
||||
record.earlyScriptId = null;
|
||||
await record.session.send("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => {});
|
||||
};
|
||||
|
||||
const refreshPayload = async () => {
|
||||
const next = await loadPayload(options.themeDir);
|
||||
if (next.revision === current.revision) return;
|
||||
current = next;
|
||||
for (const record of sessions.values()) {
|
||||
const { session } = record;
|
||||
if (session.closed) continue;
|
||||
try {
|
||||
const nextIdentifier = await registerEarly(session, current.payload, current.revision);
|
||||
if (record.earlyScriptId) {
|
||||
await session.send("Page.removeScriptToEvaluateOnNewDocument", {
|
||||
identifier: record.earlyScriptId,
|
||||
}).catch(() => {});
|
||||
}
|
||||
record.earlyScriptId = nextIdentifier;
|
||||
record.needsLoadFallback = !nextIdentifier;
|
||||
await applyToSession(session, current.payload);
|
||||
} catch (error) {
|
||||
record.needsLoadFallback = true;
|
||||
console.error(`[dream-skin] theme refresh failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
console.log(`[dream-skin] refreshed theme ${current.theme.id} (${current.timings.buildMs}ms)`);
|
||||
};
|
||||
|
||||
const queuePayloadRefresh = ({ staticChanged = false } = {}) => {
|
||||
if (staticChanged) invalidateStaticPayloadAssets();
|
||||
if (reloadTimer) clearTimeout(reloadTimer);
|
||||
reloadTimer = setTimeout(() => {
|
||||
reloadTimer = null;
|
||||
reloadChain = reloadChain.then(refreshPayload).catch((error) => {
|
||||
console.error(`[dream-skin] theme reload failed: ${error.message}`);
|
||||
});
|
||||
}, 45);
|
||||
};
|
||||
const closePayloadWatchers = watchPayloadSources(options.themeDir, queuePayloadRefresh);
|
||||
|
||||
try {
|
||||
while (!stopping) {
|
||||
let targets = [];
|
||||
try {
|
||||
targets = await listAppTargets(options.port);
|
||||
discoveryDelayMs = 100;
|
||||
} catch (error) {
|
||||
if (Date.now() - lastListErrorAt >= 2000) {
|
||||
console.error(`[dream-skin] ${new Date().toISOString()} ${error.message}`);
|
||||
lastListErrorAt = Date.now();
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, discoveryDelayMs));
|
||||
discoveryDelayMs = Math.min(500, Math.round(discoveryDelayMs * 1.6));
|
||||
continue;
|
||||
}
|
||||
|
||||
const activeIds = new Set(targets.map((target) => target.id));
|
||||
for (const [id, record] of sessions) {
|
||||
if (!activeIds.has(id) || record.session.closed) {
|
||||
record.session.close();
|
||||
sessions.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
for (const target of targets) {
|
||||
if (sessions.has(target.id)) continue;
|
||||
let session;
|
||||
let record;
|
||||
try {
|
||||
session = await connectTarget(target, options.port);
|
||||
record = { session, earlyScriptId: null, needsLoadFallback: false };
|
||||
try {
|
||||
record.earlyScriptId = await registerEarly(session, current.payload, current.revision);
|
||||
await session.evaluate(earlyPayloadFor(current.payload, current.revision));
|
||||
} catch (error) {
|
||||
record.needsLoadFallback = true;
|
||||
console.error(`[dream-skin] early injection unavailable: ${error.message}`);
|
||||
}
|
||||
const probe = await waitForCodexProbe(session);
|
||||
if (!probe?.codex) {
|
||||
await removeEarly(record);
|
||||
session.close();
|
||||
if (!rejected.has(target.id)) {
|
||||
console.error(`[dream-skin] rejected non-Codex app target ${target.id}`);
|
||||
rejected.add(target.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
rejected.delete(target.id);
|
||||
session.on("Page.loadEventFired", () => {
|
||||
if (!record.needsLoadFallback) return;
|
||||
setTimeout(() => applyToSession(session, current.payload).catch((error) => {
|
||||
console.error(`[dream-skin] fallback reinject failed: ${error.message}`);
|
||||
}), 0);
|
||||
});
|
||||
const earlyApplied = await session.evaluate(
|
||||
`window.__CODEX_DREAM_SKIN_EARLY_APPLIED__ === ${JSON.stringify(current.revision)}`,
|
||||
);
|
||||
if (!earlyApplied) {
|
||||
await session.evaluate(
|
||||
`window.__CODEX_DREAM_SKIN_EARLY_GENERATION__ = ${JSON.stringify(`fallback:${current.revision}`)}`,
|
||||
);
|
||||
await applyToSession(session, current.payload);
|
||||
}
|
||||
sessions.set(target.id, record);
|
||||
console.log(`[dream-skin] injected verified Codex target ${target.id} (${target.title || target.url})`);
|
||||
} catch (error) {
|
||||
if (record) await removeEarly(record);
|
||||
session?.close();
|
||||
console.error(`[dream-skin] inject failed for ${target.id}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
const pollDelay = sessions.size ? 800 : (targets.length ? 250 : 100);
|
||||
await new Promise((resolve) => setTimeout(resolve, pollDelay));
|
||||
}
|
||||
} finally {
|
||||
if (reloadTimer) clearTimeout(reloadTimer);
|
||||
closePayloadWatchers();
|
||||
await reloadChain.catch(() => {});
|
||||
await Promise.all([...sessions.values()].map((record) => removeEarly(record)));
|
||||
for (const record of sessions.values()) record.session.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (path.resolve(process.argv[1] || "") === path.resolve(scriptPath)) {
|
||||
let options = null;
|
||||
try {
|
||||
options = parseArgs(process.argv.slice(2));
|
||||
if (options.mode === "check") {
|
||||
const loaded = await loadPayload(options.themeDir);
|
||||
console.log(JSON.stringify({
|
||||
pass: true,
|
||||
version: SKIN_VERSION,
|
||||
themeId: loaded.theme.id,
|
||||
themeName: loaded.theme.name,
|
||||
imageBytes: loaded.imageBytes,
|
||||
payloadBytes: Buffer.byteLength(loaded.payload),
|
||||
artMetadata: loaded.theme.artMetadata ?? null,
|
||||
timings: loaded.timings,
|
||||
}, null, 2));
|
||||
} else if (options.mode === "watch") await runWatch(options);
|
||||
else {
|
||||
await runOneShot(options);
|
||||
await flushStandardStreams();
|
||||
process.exit(process.exitCode ?? 0);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[dream-skin] ${error.stack || error.message}`);
|
||||
process.exitCode = 1;
|
||||
if (options?.mode && options.mode !== "watch" && options.mode !== "check") {
|
||||
await flushStandardStreams();
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
import fs from "node:fs/promises";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const [sourceDirArg, stageDirArg] = process.argv.slice(2);
|
||||
if (!sourceDirArg || !stageDirArg) {
|
||||
throw new Error("Usage: stage-theme.mjs <source-theme-dir> <stage-dir>");
|
||||
}
|
||||
|
||||
const MAX_CONFIG_BYTES = 1024 * 1024;
|
||||
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
|
||||
const OPEN_FLAGS = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0);
|
||||
|
||||
function assertContained(rootPath, candidatePath, label) {
|
||||
const relative = path.relative(rootPath, candidatePath);
|
||||
if (
|
||||
relative === ""
|
||||
|| (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`))
|
||||
) return;
|
||||
throw new Error(`${label} must stay inside its theme directory`);
|
||||
}
|
||||
|
||||
function sameStat(left, right) {
|
||||
return left.isFile() && right.isFile()
|
||||
&& left.dev === right.dev
|
||||
&& left.ino === right.ino
|
||||
&& left.size === right.size
|
||||
&& left.mtimeMs === right.mtimeMs
|
||||
&& left.ctimeMs === right.ctimeMs;
|
||||
}
|
||||
|
||||
async function readStableFile(filePath, label, maxBytes) {
|
||||
let handle;
|
||||
try {
|
||||
handle = await fs.open(filePath, OPEN_FLAGS);
|
||||
} catch (error) {
|
||||
if (error.code === "ELOOP") throw new Error(`${label} must not be a symbolic link`);
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
const before = await handle.stat();
|
||||
if (!before.isFile()) throw new Error(`${label} must be a regular file`);
|
||||
if (before.size > maxBytes) throw new Error(`${label} is larger than ${maxBytes} bytes`);
|
||||
const bytes = await handle.readFile();
|
||||
const after = await handle.stat();
|
||||
if (!sameStat(before, after)) {
|
||||
throw new Error(`${label} changed while it was being staged`);
|
||||
}
|
||||
if (bytes.length > maxBytes) throw new Error(`${label} is larger than ${maxBytes} bytes`);
|
||||
return { bytes, stat: after };
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
function decodeJson(bytes, label) {
|
||||
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
||||
if (text.includes("\0")) throw new Error(`${label} contains NUL characters`);
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
throw new Error(`${label} is not valid JSON`);
|
||||
}
|
||||
}
|
||||
|
||||
async function writeExclusive(filePath, bytes) {
|
||||
const temporary = `${filePath}.${process.pid}.tmp`;
|
||||
try {
|
||||
await fs.writeFile(temporary, bytes, { flag: "wx", mode: 0o600 });
|
||||
await fs.rename(temporary, filePath);
|
||||
} finally {
|
||||
await fs.rm(temporary, { force: true }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const sourceRoot = await fs.realpath(sourceDirArg);
|
||||
const sourceStat = await fs.stat(sourceRoot);
|
||||
if (!sourceStat.isDirectory()) throw new Error("Theme source must be a directory");
|
||||
|
||||
const configPath = path.join(sourceRoot, "theme.json");
|
||||
const config = await readStableFile(configPath, "Theme config", MAX_CONFIG_BYTES);
|
||||
const theme = decodeJson(config.bytes, "Theme config");
|
||||
if (theme?.schemaVersion !== 1 || typeof theme.image !== "string" || !theme.image) {
|
||||
throw new Error("Theme config has an unsupported schema or image field");
|
||||
}
|
||||
if (path.basename(theme.image) !== theme.image) {
|
||||
throw new Error("Theme image must stay inside its theme directory");
|
||||
}
|
||||
if (theme.image === "theme.json") {
|
||||
throw new Error("Theme image must not replace theme.json");
|
||||
}
|
||||
if (/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(theme.image)) {
|
||||
throw new Error("Theme image contains control characters");
|
||||
}
|
||||
|
||||
const imagePath = path.resolve(sourceRoot, theme.image);
|
||||
assertContained(sourceRoot, imagePath, "Theme image");
|
||||
const image = await readStableFile(imagePath, "Theme image", MAX_IMAGE_BYTES);
|
||||
if (image.bytes.length < 1) throw new Error("Theme image is empty");
|
||||
|
||||
const stageRoot = await fs.realpath(stageDirArg);
|
||||
const stageStat = await fs.stat(stageRoot);
|
||||
if (!stageStat.isDirectory()) throw new Error("Theme stage must be a directory");
|
||||
assertContained(stageRoot, path.join(stageRoot, "theme.json"), "Staged theme config");
|
||||
assertContained(stageRoot, path.join(stageRoot, theme.image), "Staged theme image");
|
||||
|
||||
// Write both files from the already-open, stable descriptors. The caller
|
||||
// publishes the image first and theme.json last, so the watcher only ever
|
||||
// observes a complete pair; subsequent source edits cannot race the copy.
|
||||
await writeExclusive(path.join(stageRoot, theme.image), image.bytes);
|
||||
await writeExclusive(path.join(stageRoot, "theme.json"), config.bytes);
|
||||
process.stdout.write(theme.image);
|
||||
}
|
||||
|
||||
await main();
|
||||
|
Before Width: | Height: | Size: 117 KiB |
@@ -1,92 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
MAX_IMAGE_DIMENSION,
|
||||
MAX_IMAGE_PIXELS,
|
||||
classifyImageDimensions,
|
||||
readImageMetadata,
|
||||
} from "../scripts/image-metadata.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const macosRoot = path.resolve(here, "..");
|
||||
|
||||
const fixture = await fs.readFile(path.join(macosRoot, "tests", "fixtures", "background.jpg"));
|
||||
assert.deepEqual(readImageMetadata(fixture, ".jpg"), {
|
||||
width: 1920,
|
||||
height: 1200,
|
||||
ratio: 1.6,
|
||||
wide: false,
|
||||
aspect: "wide",
|
||||
taskMode: "ambient",
|
||||
});
|
||||
const malformedJpeg = Buffer.from(fixture);
|
||||
malformedJpeg[0] = 0;
|
||||
assert.equal(readImageMetadata(malformedJpeg, ".jpg"), null);
|
||||
|
||||
assert.deepEqual(classifyImageDimensions({ width: 2400, height: 1350 }), {
|
||||
width: 2400,
|
||||
height: 1350,
|
||||
ratio: 2400 / 1350,
|
||||
wide: true,
|
||||
aspect: "wide",
|
||||
taskMode: "ambient",
|
||||
});
|
||||
assert.equal(MAX_IMAGE_DIMENSION, 16384);
|
||||
assert.equal(MAX_IMAGE_PIXELS, 50_000_000);
|
||||
assert.equal(classifyImageDimensions({ width: 10000, height: 6000 }), null);
|
||||
assert.equal(classifyImageDimensions({ width: 20000, height: 1 }), null);
|
||||
assert.equal(classifyImageDimensions({ width: 2560.5, height: 1440 }), null);
|
||||
|
||||
const writeAscii = (bytes, offset, value) => {
|
||||
for (let index = 0; index < value.length; index += 1) bytes[offset + index] = value.charCodeAt(index);
|
||||
};
|
||||
const writeUint32Le = (bytes, offset, value) => {
|
||||
bytes[offset] = value & 0xff;
|
||||
bytes[offset + 1] = (value >>> 8) & 0xff;
|
||||
bytes[offset + 2] = (value >>> 16) & 0xff;
|
||||
bytes[offset + 3] = (value >>> 24) & 0xff;
|
||||
};
|
||||
const writeUint24Le = (bytes, offset, value) => {
|
||||
bytes[offset] = value & 0xff;
|
||||
bytes[offset + 1] = (value >>> 8) & 0xff;
|
||||
bytes[offset + 2] = (value >>> 16) & 0xff;
|
||||
};
|
||||
|
||||
const vp8l = new Uint8Array(26);
|
||||
writeAscii(vp8l, 0, "RIFF");
|
||||
writeUint32Le(vp8l, 4, vp8l.length - 8);
|
||||
writeAscii(vp8l, 8, "WEBP");
|
||||
writeAscii(vp8l, 12, "VP8L");
|
||||
writeUint32Le(vp8l, 16, 5);
|
||||
vp8l.set([0x2f, 0x7f, 0xc2, 0x59, 0x00], 20);
|
||||
assert.deepEqual(readImageMetadata(vp8l, ".webp"), {
|
||||
width: 640,
|
||||
height: 360,
|
||||
ratio: 640 / 360,
|
||||
wide: true,
|
||||
aspect: "wide",
|
||||
taskMode: "ambient",
|
||||
});
|
||||
|
||||
const vp8x = new Uint8Array(30);
|
||||
writeAscii(vp8x, 0, "RIFF");
|
||||
writeUint32Le(vp8x, 4, vp8x.length - 8);
|
||||
writeAscii(vp8x, 8, "WEBP");
|
||||
writeAscii(vp8x, 12, "VP8X");
|
||||
writeUint32Le(vp8x, 16, 10);
|
||||
writeUint24Le(vp8x, 24, 2559);
|
||||
writeUint24Le(vp8x, 27, 1439);
|
||||
assert.deepEqual(readImageMetadata(vp8x, ".webp"), {
|
||||
width: 2560,
|
||||
height: 1440,
|
||||
ratio: 2560 / 1440,
|
||||
wide: true,
|
||||
aspect: "wide",
|
||||
taskMode: "ambient",
|
||||
});
|
||||
|
||||
assert.equal(readImageMetadata(new Uint8Array([0, 1, 2, 3]), ".png"), null);
|
||||
|
||||
console.log("PASS: image dimensions strictly classify PNG, JPEG, VP8L, and VP8X profiles.");
|
||||
@@ -1,85 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import vm from "node:vm";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { earlyPayloadFor } from "../scripts/injector.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const injectorPath = path.resolve(here, "../scripts/injector.mjs");
|
||||
const source = await fs.readFile(injectorPath, "utf8");
|
||||
|
||||
function createFixture() {
|
||||
const observers = [];
|
||||
const timers = new Map();
|
||||
let nextTimer = 1;
|
||||
const markers = { shell: false, sidebar: false };
|
||||
const context = {
|
||||
window: { installs: [] },
|
||||
document: {
|
||||
documentElement: {},
|
||||
querySelector(selector) {
|
||||
if (selector === "main.main-surface") return markers.shell ? {} : null;
|
||||
if (selector === "aside.app-shell-left-panel") return markers.sidebar ? {} : null;
|
||||
return null;
|
||||
},
|
||||
},
|
||||
MutationObserver: class {
|
||||
constructor(callback) {
|
||||
this.callback = callback;
|
||||
this.connected = true;
|
||||
observers.push(this);
|
||||
}
|
||||
observe() {}
|
||||
disconnect() { this.connected = false; }
|
||||
},
|
||||
setTimeout(callback) {
|
||||
const id = nextTimer++;
|
||||
timers.set(id, callback);
|
||||
return id;
|
||||
},
|
||||
clearTimeout(id) { timers.delete(id); },
|
||||
};
|
||||
return { context, markers, observers };
|
||||
}
|
||||
|
||||
const guarded = createFixture();
|
||||
vm.runInNewContext(earlyPayloadFor('window.installs.push("guarded")', "guarded"), guarded.context);
|
||||
assert.deepEqual(guarded.context.window.installs, [], "Auxiliary app targets must remain untouched.");
|
||||
guarded.markers.shell = true;
|
||||
guarded.observers[0].callback([]);
|
||||
assert.deepEqual(guarded.context.window.installs, [], "A main surface without the Codex sidebar is not sufficient.");
|
||||
|
||||
const generations = createFixture();
|
||||
vm.runInNewContext(earlyPayloadFor('window.installs.push("old")', "old"), generations.context);
|
||||
vm.runInNewContext(earlyPayloadFor('window.installs.push("new")', "new"), generations.context);
|
||||
generations.markers.shell = true;
|
||||
generations.markers.sidebar = true;
|
||||
for (const observer of generations.observers) observer.callback([]);
|
||||
assert.deepEqual(
|
||||
generations.context.window.installs,
|
||||
["new"],
|
||||
"A stale early script must yield to the newest watcher generation.",
|
||||
);
|
||||
assert.equal(generations.context.window.__CODEX_DREAM_SKIN_EARLY_APPLIED__, "new");
|
||||
|
||||
const discoveryStart = source.indexOf("record.earlyScriptId = await registerEarly");
|
||||
const probeStart = source.indexOf("const probe = await waitForCodexProbe", discoveryStart);
|
||||
assert.ok(discoveryStart >= 0 && probeStart > discoveryStart, "Early registration must happen before full shell probing.");
|
||||
assert.match(
|
||||
source,
|
||||
/finally\s*\{[\s\S]*Promise\.all\(\[\.\.\.sessions\.values\(\)\][\s\S]*removeEarly\(record\)/,
|
||||
"Watcher shutdown must unregister persistent Page scripts before closing CDP sessions.",
|
||||
);
|
||||
assert.match(
|
||||
source,
|
||||
/const earlyApplied = await session\.evaluate\([\s\S]*if \(!earlyApplied\) \{[\s\S]*applyToSession/,
|
||||
"The watcher must not run the full payload twice after a successful early install.",
|
||||
);
|
||||
assert.match(
|
||||
source,
|
||||
/await runOneShot\(options\);[\s\S]{0,160}await flushStandardStreams\(\);[\s\S]{0,100}process\.exit\(process\.exitCode \?\? 0\)/,
|
||||
"One-shot commands must exit after flushing output so a lingering CDP close handshake cannot block Codex-X.",
|
||||
);
|
||||
|
||||
console.log("PASS: early injection is shell-guarded, generation-safe, and removed on shutdown.");
|
||||
@@ -1,613 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import vm from "node:vm";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const macosRoot = path.resolve(here, "..");
|
||||
const template = await fs.readFile(path.join(macosRoot, "assets", "renderer-inject.js"), "utf8");
|
||||
const css = await fs.readFile(path.join(macosRoot, "assets", "dream-skin.css"), "utf8");
|
||||
|
||||
assert.doesNotMatch(
|
||||
css,
|
||||
/background-image:\s*var\(--dream-skin-art\),\s*var\(--dream-skin-art\)/,
|
||||
"The home hero must not stack duplicate copies of the selected image.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/data-dream-art-safe="left"[\s\S]{0,140}--ds-art-position:\s*100% var\(--ds-focus-y\);/,
|
||||
"A left text-safe image must preserve its right-side subject on narrower windows.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/\.dream-skin-home > div:has\(\[data-feature="game-source"\]\) > div:first-child > div:first-child\s*\{[\s\S]{0,700}background-position:\s*var\(--ds-home-art-position\) !important;/,
|
||||
"The home hero must use its route-specific focal point.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/\.dream-skin-home > div:has\(\[data-feature="game-source"\]\)\s*\{[\s\S]{0,120}min-height:\s*100% !important;/,
|
||||
"The home layout must target the content container instead of an inserted banner sibling.",
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
css,
|
||||
/\.dream-skin-home > div:first-child\s*\{[\s\S]{0,120}min-height:\s*100% !important;/,
|
||||
"An empty home banner container must not push the composer below the viewport.",
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
css,
|
||||
/background-size:\s*auto 100% !important;/,
|
||||
"Wide home artwork must not leave an unpainted half-card by fitting only to height.",
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
css,
|
||||
/background-size:\s*100% 100%,\s*100% 100%,\s*100% auto;/,
|
||||
"Wide task artwork must cover the full route instead of ending above the composer.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/data-dream-art-task-mode="ambient"[\s\S]{0,500}body\s*\{[\s\S]{0,500}background-image:\s*var\(--dream-skin-art\) !important;[\s\S]{0,200}background-size:\s*cover !important;/,
|
||||
"Wide ambient task artwork should cover the full application window.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/data-dream-task-mode="banner"[\s\S]{0,900}body\s*\{[\s\S]{0,500}background-image:\s*var\(--dream-skin-art\) !important;[\s\S]{0,200}background-size:\s*cover !important;/,
|
||||
"Wide banner task artwork should use the same full-window wallpaper contract as ambient routes.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/data-dream-art-wide="true"\]:has\(main\.main-surface\.dream-skin-home-shell\)[\s\S]{0,100}body\s*\{[\s\S]{0,300}background-image:\s*var\(--dream-skin-art\) !important;/,
|
||||
"Wide home artwork should use the same full-window image as utility routes.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/data-dream-art-wide="true"\]:has\(main\.main-surface\.dream-skin-home-shell\)[\s\S]{0,120}body\s*\{[\s\S]{0,260}background-position:\s*var\(--ds-art-position\) !important;/,
|
||||
"Wide home artwork must honor the configured focal point instead of forcing a centered crop.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/data-dream-art-task-mode="ambient"[\s\S]{0,260}data-dream-art-wide="true"\]:has\(main\.main-surface:not\(\.dream-skin-home-shell\)\)[\s\S]{0,120}body\s*\{[\s\S]{0,260}background-position:\s*var\(--ds-art-position\) !important;/,
|
||||
"Wide task artwork must retain the same focal point as the home route.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/data-dream-art-wide="true"\]\s+\.composer-surface-chrome\s*\{[\s\S]{0,500}backdrop-filter:\s*none !important;/,
|
||||
"Wide artwork should use one uniform composer surface without a split blur layer.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/--ds-immersive-composer-solid:\s*rgb\(var\(--ds-panel-rgb\) \/ \.94\);/,
|
||||
"The light composer should remain opaque enough to prevent thread text from showing through.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/--ds-task-immersive-edge:\s*rgb\(var\(--ds-panel-rgb\) \/ calc\(\.86 \* var\(--ds-surface-opacity\)\)\);/,
|
||||
"Wide task surfaces should expose the wallpaper according to the configured opacity.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/--ds-task-fade:\s*linear-gradient\(180deg,[\s\S]{0,400}var\(--ds-surface-opacity\)/,
|
||||
"Regular landscape artwork should apply the configured opacity to its task scrim.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/main\.main-surface:not\(\.dream-skin-home-shell\)::before\s*\{[\s\S]{0,420}opacity:\s*1;/,
|
||||
"The wallpaper layer must keep its original colors instead of blending through a white base.",
|
||||
);
|
||||
const homeSuggestionRuleStart = css.indexOf(
|
||||
".dream-skin-home .group\\/home-suggestions button {",
|
||||
);
|
||||
assert.notEqual(homeSuggestionRuleStart, -1, "The home suggestion card rule must exist.");
|
||||
const homeSuggestionRuleEnd = css.indexOf("}", homeSuggestionRuleStart);
|
||||
const homeSuggestionRule = css.slice(homeSuggestionRuleStart, homeSuggestionRuleEnd);
|
||||
assert.match(
|
||||
homeSuggestionRule,
|
||||
/background:\s*rgb\(var\(--ds-panel-rgb\) \/ calc\(\.56 \* var\(--ds-surface-opacity\)\)\) !important;/,
|
||||
"Home suggestion cards must use the shared surface opacity instead of a fixed white layer.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/--ds-composer-surface:\s*rgb\(var\(--ds-panel-rgb\) \/ calc\(\.82 \+ \(\.12 \* var\(--ds-surface-opacity\)\)\)\);/,
|
||||
"The composer must keep a readable minimum opacity while responding to the skin setting.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/html\.codex-dream-skin \.composer-surface-chrome\s*\{[\s\S]{0,100}overflow:\s*hidden !important;/,
|
||||
"Composer internals must be clipped to the rounded input surface.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/data-dream-shell="light"\]\[data-dream-art-wide="true"\][\s\S]{0,100}\.composer-surface-chrome\s*\{[\s\S]{0,400}backdrop-filter:\s*blur\(8px\) saturate\(102%\) !important;/,
|
||||
"The translucent light composer should softly separate text from detailed artwork.",
|
||||
);
|
||||
assert.match(
|
||||
template,
|
||||
/\[class\*="_homeUtilityBar_"\][\s\S]{0,500}dream-skin-home-utility/,
|
||||
"The renderer should give the current native home utility bar a stable theme class.",
|
||||
);
|
||||
assert.match(
|
||||
template,
|
||||
/\[data-feature="game-source"\][\s\S]{0,180}\[data-codex-composer-root\]/,
|
||||
"Home detection should use stable semantic markers instead of optional suggestion cards.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/\.dream-skin-home:has\(\.dream-skin-home-utility\)[\s\S]{0,120}\.composer-surface-chrome\s*\{[\s\S]{0,180}border-radius:\s*0 0 22px 22px !important;/,
|
||||
"The home utility bar and composer should render as one continuous control.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/\.composer-surface-chrome button:not\(\[class~="bg-token-foreground"\]\)[\s\S]{0,100}color:\s*var\(--ds-muted\) !important;/,
|
||||
"Composer controls must remain readable when Codex native tokens lag behind a forced dark appearance.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/\.composer-surface-chrome button:not\(\[class~="bg-token-foreground"\]\) \*\s*\{[\s\S]{0,80}color:\s*currentColor !important;/,
|
||||
"Nested labels inside composer controls must inherit the corrected theme color.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/\.composer-surface-chrome p\.placeholder::after\s*\{[\s\S]{0,120}color:\s*rgb\(var\(--ds-muted-rgb\) \/ \.82\) !important;[\s\S]{0,80}opacity:\s*1 !important;/,
|
||||
"Composer placeholder text must not inherit a stale native color with double opacity.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/header\.app-header-tint\s*\{[\s\S]{0,180}background:\s*transparent !important;/,
|
||||
"Wide artwork should not paint a separate opaque header band.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/\.thread-scroll-container \.bg-gradient-to-t\.from-token-main-surface-primary\s*\{[\s\S]{0,100}background:\s*transparent !important;/,
|
||||
"Wide artwork should remove the native opaque fade behind the sticky composer.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/div\.sticky:has\(input\[type="text"\]\)[\s\S]{0,100}background:\s*transparent !important;/,
|
||||
"Search routes should not retain the native opaque sticky band.",
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/\[class~="bg-token-main-surface-primary"\]\[class~="h-full"\]\[class~="w-full"\][\s\S]{0,100}background:\s*transparent !important;/,
|
||||
"Full-size utility route wrappers should not hide the selected artwork.",
|
||||
);
|
||||
|
||||
function createStyleDeclaration() {
|
||||
const values = new Map();
|
||||
return {
|
||||
values,
|
||||
getPropertyValue(name) { return values.get(name) ?? ""; },
|
||||
setProperty(name, value) { values.set(name, value); },
|
||||
removeProperty(name) { values.delete(name); },
|
||||
};
|
||||
}
|
||||
|
||||
function createClassList(initial = []) {
|
||||
const values = new Set(initial);
|
||||
return {
|
||||
values,
|
||||
add(...names) { for (const name of names) values.add(name); },
|
||||
remove(...names) { for (const name of names) values.delete(name); },
|
||||
contains(name) { return values.has(name); },
|
||||
toggle(name, enabled) {
|
||||
if (enabled) values.add(name);
|
||||
else values.delete(name);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFixture(theme, {
|
||||
nativeShell = "light",
|
||||
analysisFixture = null,
|
||||
analysisCache = null,
|
||||
} = {}) {
|
||||
let fixtureShell = nativeShell;
|
||||
const nodes = new Map();
|
||||
const attributes = new Map();
|
||||
const bodyAttributes = new Map();
|
||||
const observers = [];
|
||||
const resizeObservers = [];
|
||||
const timers = new Map();
|
||||
let nextTimer = 1;
|
||||
let nextBlob = 1;
|
||||
const rootStyle = createStyleDeclaration();
|
||||
const root = {
|
||||
className: nativeShell === "dark" ? "electron-dark" : "electron-light",
|
||||
classList: createClassList(),
|
||||
style: rootStyle,
|
||||
appendChild(node) {
|
||||
node.parentElement = root;
|
||||
if (node.id) nodes.set(node.id, node);
|
||||
},
|
||||
getAttribute(name) { return attributes.get(name) ?? null; },
|
||||
setAttribute(name, value) { attributes.set(name, String(value)); },
|
||||
removeAttribute(name) { attributes.delete(name); },
|
||||
};
|
||||
const body = {
|
||||
className: "",
|
||||
appendChild(node) {
|
||||
node.parentElement = body;
|
||||
if (node.id) nodes.set(node.id, node);
|
||||
},
|
||||
getAttribute(name) { return bodyAttributes.get(name) ?? null; },
|
||||
setAttribute(name, value) { bodyAttributes.set(name, String(value)); },
|
||||
};
|
||||
const shellBox = { left: 280, top: 36, width: 1000, height: 764 };
|
||||
const shellMain = {
|
||||
classList: createClassList(),
|
||||
getBoundingClientRect() {
|
||||
return { ...shellBox };
|
||||
},
|
||||
};
|
||||
|
||||
const createElement = (tagName) => {
|
||||
if (tagName === "canvas" && analysisFixture) {
|
||||
return {
|
||||
width: 0,
|
||||
height: 0,
|
||||
getContext() {
|
||||
return {
|
||||
drawImage() {},
|
||||
getImageData() { return { data: analysisFixture.pixels }; },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
const childNodes = new Map();
|
||||
const element = {
|
||||
id: "",
|
||||
dataset: {},
|
||||
style: createStyleDeclaration(),
|
||||
classList: createClassList(),
|
||||
parentElement: null,
|
||||
textContent: "",
|
||||
innerHTML: "",
|
||||
setAttribute() {},
|
||||
querySelector(selector) {
|
||||
if (!childNodes.has(selector)) childNodes.set(selector, { textContent: "" });
|
||||
return childNodes.get(selector);
|
||||
},
|
||||
remove() { if (element.id) nodes.delete(element.id); },
|
||||
};
|
||||
return element;
|
||||
};
|
||||
|
||||
const document = {
|
||||
documentElement: root,
|
||||
head: root,
|
||||
body,
|
||||
createElement,
|
||||
getElementById(id) { return nodes.get(id) ?? null; },
|
||||
querySelector(selector) {
|
||||
if (selector === "main.main-surface" || selector === "main") return shellMain;
|
||||
return null;
|
||||
},
|
||||
querySelectorAll() { return []; },
|
||||
};
|
||||
const mediaQuery = {
|
||||
matches: false,
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
const revokedUrls = [];
|
||||
const window = {
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
matchMedia() {
|
||||
mediaQuery.matches = fixtureShell === "dark";
|
||||
return mediaQuery;
|
||||
},
|
||||
};
|
||||
if (analysisCache) window.__CODEX_DREAM_SKIN_ANALYSIS_CACHE__ = analysisCache;
|
||||
if (analysisFixture) {
|
||||
window.Image = class {
|
||||
naturalWidth = analysisFixture.naturalWidth;
|
||||
naturalHeight = analysisFixture.naturalHeight;
|
||||
set src(_) { this.onload(); }
|
||||
};
|
||||
}
|
||||
const context = {
|
||||
window,
|
||||
document,
|
||||
MutationObserver: class {
|
||||
constructor(callback) {
|
||||
this.callback = callback;
|
||||
observers.push(this);
|
||||
}
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
},
|
||||
ResizeObserver: class {
|
||||
constructor(callback) {
|
||||
this.callback = callback;
|
||||
this.target = null;
|
||||
resizeObservers.push(this);
|
||||
}
|
||||
observe(target) { this.target = target; }
|
||||
disconnect() { this.target = null; }
|
||||
},
|
||||
URL: {
|
||||
createObjectURL() { return `blob:fixture-${nextBlob++}`; },
|
||||
revokeObjectURL(value) { revokedUrls.push(value); },
|
||||
},
|
||||
Blob,
|
||||
Uint8Array,
|
||||
atob,
|
||||
getComputedStyle() {
|
||||
const skinShell = root.classList.contains("codex-dream-skin")
|
||||
? (attributes.get("data-dream-shell") || "dark") : fixtureShell;
|
||||
return {
|
||||
colorScheme: skinShell,
|
||||
backgroundColor: fixtureShell === "dark" ? "rgb(24, 24, 27)" : "rgb(250, 250, 250)",
|
||||
};
|
||||
},
|
||||
setInterval: () => 1,
|
||||
clearInterval() {},
|
||||
setTimeout(callback, delay) {
|
||||
const id = ++nextTimer;
|
||||
timers.set(id, { callback, delay });
|
||||
return id;
|
||||
},
|
||||
clearTimeout(id) { timers.delete(id); },
|
||||
cancelAnimationFrame() {},
|
||||
};
|
||||
const payloadFor = (nextTheme, cssText = ".fixture { color: blue; }") => template
|
||||
.replace("__DREAM_SKIN_CSS_JSON__", JSON.stringify(cssText))
|
||||
.replace("__DREAM_SKIN_ART_JSON__", JSON.stringify("data:image/png;base64,AA=="))
|
||||
.replace("__DREAM_SKIN_THEME_JSON__", JSON.stringify(nextTheme))
|
||||
.replace("__DREAM_SKIN_VERSION_JSON__", JSON.stringify("test"))
|
||||
.replace("__DREAM_SKIN_STYLE_REVISION_JSON__", JSON.stringify(cssText));
|
||||
const flushTimers = (maximumDelay = Infinity) => {
|
||||
const pending = [...timers.entries()].filter(([, timer]) => timer.delay <= maximumDelay);
|
||||
for (const [id, timer] of pending) {
|
||||
timers.delete(id);
|
||||
timer.callback();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
attributes,
|
||||
body,
|
||||
bodyAttributes,
|
||||
context,
|
||||
flushTimers,
|
||||
nodes,
|
||||
observers,
|
||||
payload: payloadFor(theme),
|
||||
payloadFor,
|
||||
revokedUrls,
|
||||
resizeObservers,
|
||||
root,
|
||||
rootStyle,
|
||||
shellBox,
|
||||
timers,
|
||||
window,
|
||||
setNativeShell(value) { fixtureShell = value; },
|
||||
};
|
||||
}
|
||||
|
||||
const defaults = createFixture({
|
||||
id: "default-contract",
|
||||
appearance: "auto",
|
||||
art: { safeArea: "auto", taskMode: "auto" },
|
||||
});
|
||||
const defaultResult = vm.runInNewContext(defaults.payload, defaults.context);
|
||||
assert.equal(defaultResult.installed, true);
|
||||
assert.equal(defaults.attributes.get("data-dream-shell"), "light");
|
||||
assert.equal(defaults.attributes.get("data-dream-art-safe-area"), "center");
|
||||
assert.equal(defaults.attributes.get("data-dream-art-task-mode"), "ambient");
|
||||
assert.equal(defaults.attributes.get("data-dream-art-ready"), "false");
|
||||
assert.equal(defaults.rootStyle.values.get("--dream-art-position"), "50.00% 50.00%");
|
||||
assert.equal(defaults.rootStyle.values.get("--ds-surface-opacity"), "1.00");
|
||||
const defaultMetrics = defaults.window.__CODEX_DREAM_SKIN_STATE__.metrics;
|
||||
assert.equal(defaultMetrics.rootPasses, 1);
|
||||
assert.equal(defaultMetrics.routePasses, 1);
|
||||
assert.equal(defaultMetrics.layoutReads, 1);
|
||||
for (let index = 0; index < 50; index += 1) defaults.observers[0].callback([]);
|
||||
assert.equal(defaults.timers.size, 1, "Mutation bursts should coalesce into one scheduled ensure.");
|
||||
defaults.flushTimers(64);
|
||||
assert.equal(defaultMetrics.rootPasses, 1, "Subtree mutations must not recompute root theme tokens.");
|
||||
assert.equal(defaultMetrics.routePasses, 2);
|
||||
assert.equal(defaultMetrics.layoutReads, 1, "Subtree mutations must not force shell layout reads.");
|
||||
assert.equal(defaults.resizeObservers.length, 1);
|
||||
assert.ok(defaults.resizeObservers[0].target);
|
||||
defaults.shellBox.left = 196;
|
||||
defaults.shellBox.width = 1084;
|
||||
defaults.resizeObservers[0].callback([]);
|
||||
defaults.flushTimers(64);
|
||||
assert.equal(defaultMetrics.layoutReads, 2, "Shell ResizeObserver changes must refresh chrome geometry.");
|
||||
const defaultChrome = defaults.nodes.get("codex-dream-skin-chrome");
|
||||
assert.equal(defaultChrome.style.values.get("left"), "196px");
|
||||
assert.equal(defaultChrome.style.values.get("width"), "1084px");
|
||||
|
||||
// Auto appearance must continue following the native shell after the skin is
|
||||
// already installed. The fixture makes the injected root color-scheme win
|
||||
// whenever our class remains on <html>, so a temporary native probe is needed
|
||||
// for each light → dark → light transition.
|
||||
const shellFollow = createFixture({
|
||||
id: "shell-follow",
|
||||
appearance: "auto",
|
||||
art: { safeArea: "auto", taskMode: "auto" },
|
||||
});
|
||||
shellFollow.root.className = "";
|
||||
vm.runInNewContext(shellFollow.payload, shellFollow.context);
|
||||
assert.equal(shellFollow.attributes.get("data-dream-shell"), "light");
|
||||
shellFollow.setNativeShell("dark");
|
||||
shellFollow.window.__CODEX_DREAM_SKIN_STATE__.ensure();
|
||||
assert.equal(shellFollow.attributes.get("data-dream-shell"), "dark");
|
||||
shellFollow.setNativeShell("light");
|
||||
shellFollow.window.__CODEX_DREAM_SKIN_STATE__.ensure();
|
||||
assert.equal(shellFollow.attributes.get("data-dream-shell"), "light");
|
||||
|
||||
defaults.root.className = "";
|
||||
defaults.body.setAttribute("data-theme", "dark");
|
||||
defaults.observers[1].callback([{ type: "attributes", target: defaults.body }]);
|
||||
defaults.flushTimers(64);
|
||||
assert.equal(defaults.attributes.get("data-dream-shell"), "dark", "Body theme changes must apply without the fallback interval.");
|
||||
|
||||
const synchronousWide = createFixture({
|
||||
id: "synchronous-wide",
|
||||
appearance: "auto",
|
||||
art: { safeArea: "auto", taskMode: "auto" },
|
||||
artKey: "wide-art",
|
||||
artMetadata: {
|
||||
width: 2400,
|
||||
height: 1350,
|
||||
ratio: 2400 / 1350,
|
||||
wide: true,
|
||||
aspect: "wide",
|
||||
taskMode: "ambient",
|
||||
},
|
||||
});
|
||||
vm.runInNewContext(synchronousWide.payload, synchronousWide.context);
|
||||
assert.equal(synchronousWide.attributes.get("data-dream-art-wide"), "true");
|
||||
assert.equal(synchronousWide.attributes.get("data-dream-art-aspect"), "wide");
|
||||
assert.equal(synchronousWide.attributes.get("data-dream-art-task-mode"), "ambient");
|
||||
assert.equal(synchronousWide.attributes.get("data-dream-art-ready"), "false");
|
||||
|
||||
const autoLandscape = createFixture({
|
||||
id: "auto-landscape-focus",
|
||||
appearance: "auto",
|
||||
art: { safeArea: "auto", taskMode: "auto" },
|
||||
artMetadata: {
|
||||
width: 1586,
|
||||
height: 992,
|
||||
ratio: 1586 / 992,
|
||||
wide: false,
|
||||
aspect: "wide",
|
||||
taskMode: "ambient",
|
||||
},
|
||||
});
|
||||
vm.runInNewContext(autoLandscape.payload, autoLandscape.context);
|
||||
assert.equal(autoLandscape.rootStyle.values.get("--dream-art-position"), "50.00% 50.00%");
|
||||
assert.equal(
|
||||
autoLandscape.rootStyle.values.get("--dream-skin-home-art-position"),
|
||||
"50.00% 28.00%",
|
||||
"An unconfigured landscape should keep upper subjects visible in the much wider home hero.",
|
||||
);
|
||||
|
||||
const cachedAnalysis = {
|
||||
width: 2400,
|
||||
height: 1350,
|
||||
ratio: 2400 / 1350,
|
||||
wide: true,
|
||||
aspect: "wide",
|
||||
taskMode: "ambient",
|
||||
safeArea: "left",
|
||||
focusX: 0.72,
|
||||
focusY: 0.48,
|
||||
accentRgb: { r: 180, g: 90, b: 110 },
|
||||
};
|
||||
const cached = createFixture({
|
||||
id: "cached-wide",
|
||||
appearance: "auto",
|
||||
art: { safeArea: "auto", taskMode: "auto" },
|
||||
artKey: "cached-art",
|
||||
artMetadata: synchronousWide.window.__CODEX_DREAM_SKIN_STATE__.artMetadata,
|
||||
}, { analysisCache: new Map([["cached-art", cachedAnalysis]]) });
|
||||
vm.runInNewContext(cached.payload, cached.context);
|
||||
assert.equal(cached.attributes.get("data-dream-art-ready"), "true");
|
||||
assert.equal(cached.attributes.get("data-dream-art-safe-area"), "left");
|
||||
assert.equal(cached.window.__CODEX_DREAM_SKIN_STATE__.metrics.analysisCacheHits, 1);
|
||||
assert.equal(cached.window.__CODEX_DREAM_SKIN_STATE__.metrics.analysisRuns, 0);
|
||||
|
||||
const previousWideState = synchronousWide.window.__CODEX_DREAM_SKIN_STATE__;
|
||||
const stableStyle = synchronousWide.nodes.get("codex-dream-skin-style");
|
||||
vm.runInNewContext(synchronousWide.payloadFor({
|
||||
id: "switched-wide",
|
||||
appearance: "dark",
|
||||
art: { safeArea: "right", taskMode: "ambient" },
|
||||
artKey: "switched-art",
|
||||
artMetadata: {
|
||||
width: 2400,
|
||||
height: 1350,
|
||||
ratio: 2400 / 1350,
|
||||
wide: true,
|
||||
aspect: "wide",
|
||||
taskMode: "ambient",
|
||||
},
|
||||
}, ".fixture { color: red; }"), synchronousWide.context);
|
||||
assert.equal(synchronousWide.nodes.get("codex-dream-skin-style"), stableStyle);
|
||||
assert.equal(stableStyle.textContent, ".fixture { color: red; }");
|
||||
assert.equal(stableStyle.dataset.dreamSkinVersion, "test");
|
||||
assert.equal(synchronousWide.rootStyle.values.get("--dream-skin-art"), 'url("blob:fixture-2")');
|
||||
assert.deepEqual(synchronousWide.revokedUrls, ["blob:fixture-1"]);
|
||||
assert.equal(previousWideState.cleanup(), false, "An old async cleanup must not remove the new theme.");
|
||||
|
||||
const brightPixels = new Uint8ClampedArray(96 * 32 * 4);
|
||||
for (let offset = 0; offset < brightPixels.length; offset += 4) {
|
||||
brightPixels[offset] = 245;
|
||||
brightPixels[offset + 1] = 224;
|
||||
brightPixels[offset + 2] = 224;
|
||||
brightPixels[offset + 3] = 255;
|
||||
}
|
||||
const nativeDark = createFixture({
|
||||
id: "native-dark-contract",
|
||||
appearance: "auto",
|
||||
art: { safeArea: "auto", taskMode: "auto" },
|
||||
}, {
|
||||
nativeShell: "dark",
|
||||
analysisFixture: { naturalWidth: 2400, naturalHeight: 800, pixels: brightPixels },
|
||||
});
|
||||
vm.runInNewContext(nativeDark.payload, nativeDark.context);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
nativeDark.window.__CODEX_DREAM_SKIN_STATE__.ensure();
|
||||
assert.equal(nativeDark.window.__CODEX_DREAM_SKIN_STATE__.analysis.shell, "light");
|
||||
assert.equal(nativeDark.attributes.get("data-dream-shell"), "dark");
|
||||
assert.match(nativeDark.rootStyle.values.get("--ds-bg"), /^#[0-9a-f]{6}$/);
|
||||
assert.ok(Number.parseInt(nativeDark.rootStyle.values.get("--ds-bg").slice(1), 16) < 0x303030);
|
||||
|
||||
const explicit = createFixture({
|
||||
id: "explicit-contract",
|
||||
appearance: "dark",
|
||||
surfaceOpacity: 0.55,
|
||||
art: { focusX: 0.15, focusY: 0.8, safeArea: "none", taskMode: "off" },
|
||||
});
|
||||
const explicitResult = vm.runInNewContext(explicit.payload, explicit.context);
|
||||
assert.equal(explicitResult.shell, "dark");
|
||||
assert.equal(explicit.attributes.get("data-dream-shell"), "dark");
|
||||
assert.equal(explicit.attributes.get("data-dream-art-safe-area"), "none");
|
||||
assert.equal(explicit.attributes.get("data-dream-art-safe"), "none");
|
||||
assert.equal(explicit.attributes.get("data-dream-art-task-mode"), "off");
|
||||
assert.equal(explicit.rootStyle.values.get("--dream-art-position"), "15.00% 80.00%");
|
||||
assert.equal(explicit.rootStyle.values.get("--dream-skin-home-art-position"), "15.00% 80.00%");
|
||||
assert.equal(explicit.rootStyle.values.get("--ds-surface-opacity"), "0.55");
|
||||
assert.equal(explicit.window.__CODEX_DREAM_SKIN_STATE__.analysis, null);
|
||||
|
||||
const banner = createFixture({
|
||||
id: "banner-contract",
|
||||
appearance: "auto",
|
||||
art: { safeArea: "left", taskMode: "banner" },
|
||||
artMetadata: {
|
||||
width: 2560,
|
||||
height: 1440,
|
||||
ratio: 2560 / 1440,
|
||||
wide: true,
|
||||
aspect: "ultrawide",
|
||||
taskMode: "banner",
|
||||
safeArea: "left",
|
||||
focusX: 0.72,
|
||||
focusY: 0.44,
|
||||
},
|
||||
});
|
||||
vm.runInNewContext(banner.payload, banner.context);
|
||||
assert.equal(banner.attributes.get("data-dream-art-wide"), "true");
|
||||
assert.equal(banner.attributes.get("data-dream-art-task-mode"), "banner");
|
||||
assert.equal(banner.attributes.get("data-dream-task-mode"), "banner");
|
||||
|
||||
assert.equal(explicit.window.__CODEX_DREAM_SKIN_STATE__.cleanup(), true);
|
||||
assert.equal(explicit.root.classList.contains("codex-dream-skin"), false);
|
||||
assert.equal(explicit.attributes.has("data-dream-shell"), false);
|
||||
assert.equal(explicit.attributes.has("data-dream-art-safe-area"), false);
|
||||
assert.equal(explicit.attributes.has("data-dream-art-task-mode"), false);
|
||||
assert.equal(explicit.rootStyle.values.has("--dream-art-position"), false);
|
||||
assert.equal(explicit.nodes.has("codex-dream-skin-style"), false);
|
||||
assert.equal(explicit.nodes.has("codex-dream-skin-chrome"), false);
|
||||
assert.deepEqual(explicit.revokedUrls, ["blob:fixture-1"]);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
assert.equal(explicit.root.classList.contains("codex-dream-skin"), false);
|
||||
assert.equal(explicit.nodes.has("codex-dream-skin-style"), false);
|
||||
assert.equal(explicit.window.__CODEX_DREAM_SKIN_STATE__, undefined);
|
||||
|
||||
console.log("PASS: renderer honors adaptive art metadata, fallback, and cleanup behavior.");
|
||||
@@ -1,4 +0,0 @@
|
||||
await import("./image-metadata.test.mjs");
|
||||
await import("./injector-bootstrap.test.mjs");
|
||||
await import("./renderer-inject.test.mjs");
|
||||
await import("./theme-stage.test.mjs");
|
||||
@@ -1,85 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const macosRoot = path.resolve(here, "..");
|
||||
const stageScript = path.join(macosRoot, "scripts", "stage-theme.mjs");
|
||||
const fixtureAsset = path.join(macosRoot, "tests", "fixtures", "background.jpg");
|
||||
const tempRoot = await fs.mkdtemp(path.join("/tmp", "codex-dream-skin-stage-"));
|
||||
|
||||
function runStage(source, stage) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, [stageScript, source, stage], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
||||
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
if (code === 0) resolve(stdout);
|
||||
else reject(new Error(stderr || `stage-theme exited with ${code}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const source = path.join(tempRoot, "themes", "preset-race");
|
||||
const stage = path.join(tempRoot, "stage");
|
||||
await fs.mkdir(source, { recursive: true });
|
||||
await fs.mkdir(stage);
|
||||
await fs.copyFile(fixtureAsset, path.join(source, "background-a.png"));
|
||||
await fs.writeFile(
|
||||
path.join(source, "theme.json"),
|
||||
`${JSON.stringify({ schemaVersion: 1, id: "preset-race", name: "A", image: "background-a.png" })}\n`,
|
||||
);
|
||||
|
||||
const imageName = await runStage(source, stage);
|
||||
assert.equal(imageName, "background-a.png");
|
||||
const stagedConfig = JSON.parse(await fs.readFile(path.join(stage, "theme.json"), "utf8"));
|
||||
assert.equal(stagedConfig.image, "background-a.png");
|
||||
const stagedBeforeMutation = await fs.readFile(path.join(stage, "background-a.png"));
|
||||
|
||||
// A source edit after staging must not change the pair that is about to be
|
||||
// published. This is the regression for switch-theme's old copy-after-
|
||||
// validation TOCTOU window.
|
||||
await fs.copyFile(fixtureAsset, path.join(source, "background-b.png"));
|
||||
await fs.writeFile(
|
||||
path.join(source, "theme.json"),
|
||||
`${JSON.stringify({ schemaVersion: 1, id: "preset-race", name: "B", image: "background-b.png" })}\n`,
|
||||
);
|
||||
await fs.writeFile(path.join(source, "background-a.png"), Buffer.from("changed-after-stage"));
|
||||
assert.deepEqual(await fs.readFile(path.join(stage, "background-a.png")), stagedBeforeMutation);
|
||||
assert.equal(JSON.parse(await fs.readFile(path.join(stage, "theme.json"), "utf8")).name, "A");
|
||||
|
||||
const outside = path.join(tempRoot, "outside.png");
|
||||
await fs.copyFile(fixtureAsset, outside);
|
||||
const traversal = path.join(tempRoot, "traversal");
|
||||
await fs.mkdir(traversal);
|
||||
await fs.writeFile(
|
||||
path.join(traversal, "theme.json"),
|
||||
`${JSON.stringify({ schemaVersion: 1, id: "bad", image: "../outside.png" })}\n`,
|
||||
);
|
||||
const traversalStage = path.join(tempRoot, "traversal-stage");
|
||||
await fs.mkdir(traversalStage);
|
||||
await assert.rejects(runStage(traversal, traversalStage), /inside its theme directory/);
|
||||
|
||||
const symlink = path.join(tempRoot, "symlink");
|
||||
await fs.mkdir(symlink);
|
||||
await fs.symlink(outside, path.join(symlink, "background.png"));
|
||||
await fs.writeFile(
|
||||
path.join(symlink, "theme.json"),
|
||||
`${JSON.stringify({ schemaVersion: 1, id: "bad-link", image: "background.png" })}\n`,
|
||||
);
|
||||
const symlinkStage = path.join(tempRoot, "symlink-stage");
|
||||
await fs.mkdir(symlinkStage);
|
||||
await assert.rejects(runStage(symlink, symlinkStage), /symbolic link/);
|
||||
|
||||
console.log("PASS: theme staging snapshots a matched, contained config/image pair.");
|
||||
} finally {
|
||||
await fs.rm(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidateSet('inspect', 'selectPort', 'launch', 'stopCodex', 'launchNormal', 'verifyPort', 'processInfo', 'injectorStatus', 'stopInjector')]
|
||||
[string]$Action,
|
||||
[int]$Port = 9341,
|
||||
[int]$TargetPid = 0,
|
||||
[string]$StatePath
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
. (Join-Path $PSScriptRoot 'common-windows.ps1')
|
||||
|
||||
function Write-CodexxJson {
|
||||
param([Parameter(Mandatory = $true)][object]$Value)
|
||||
$Value | ConvertTo-Json -Depth 8 -Compress
|
||||
}
|
||||
|
||||
function Get-CodexxState {
|
||||
if (-not $StatePath -or -not (Test-Path -LiteralPath $StatePath -PathType Leaf)) {
|
||||
throw 'Codex-X skin state file is missing.'
|
||||
}
|
||||
return Get-Content -LiteralPath $StatePath -Raw -Encoding UTF8 | ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
|
||||
function Get-CodexxDebugIdentity {
|
||||
param([Parameter(Mandatory = $true)][object]$Codex)
|
||||
foreach ($process in @(Get-DreamSkinCodexProcesses -Codex $Codex)) {
|
||||
$commandLine = "$($process.CommandLine)"
|
||||
foreach ($match in [regex]::Matches($commandLine, '(?i)(?:^|\s)--remote-debugging-port(?:=|\s+)(?<port>[0-9]{4,5})(?=$|\s)')) {
|
||||
$candidate = [int]$match.Groups['port'].Value
|
||||
if ($candidate -lt 1024 -or $candidate -gt 65535) { continue }
|
||||
$identity = Get-DreamSkinVerifiedCdpIdentity -Port $candidate -Codex $Codex
|
||||
if ($null -ne $identity) {
|
||||
return [pscustomobject]@{ Port = $candidate; Identity = $identity }
|
||||
}
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Test-CodexxInjectorState {
|
||||
param([Parameter(Mandatory = $true)][object]$State)
|
||||
if (-not $State.injectorPid -or -not $State.injectorStartedAt -or
|
||||
-not $State.injectorPath -or -not $State.nodePath -or -not $State.port) {
|
||||
return $false
|
||||
}
|
||||
$processId = [int]$State.injectorPid
|
||||
$process = Get-CimInstance Win32_Process -Filter "ProcessId = $processId" -ErrorAction SilentlyContinue
|
||||
if ($null -eq $process) { return $false }
|
||||
$processPath = Get-DreamSkinProcessExecutablePath -ProcessInfo $process
|
||||
$commandLine = "$($process.CommandLine)"
|
||||
$startedAt = Get-DreamSkinProcessStartedAt -ProcessId $processId
|
||||
$portPattern = '(?i)(?:^|\s)--port(?:=|\s+)' + [regex]::Escape("$($State.port)") + '(?=$|\s)'
|
||||
return [bool](
|
||||
$processPath -and
|
||||
([System.IO.Path]::GetFileName($processPath) -ieq 'node.exe') -and
|
||||
(Test-DreamSkinPathEqual -Left $processPath -Right "$($State.nodePath)") -and
|
||||
(Test-DreamSkinCommandLineToken -CommandLine $commandLine -Token "$($State.injectorPath)") -and
|
||||
(Test-DreamSkinCommandLineToken -CommandLine $commandLine -Token '--watch') -and
|
||||
[regex]::IsMatch($commandLine, $portPattern) -and
|
||||
$startedAt -eq "$($State.injectorStartedAt)"
|
||||
)
|
||||
}
|
||||
|
||||
$operationLock = Enter-DreamSkinOperationLock
|
||||
try {
|
||||
switch ($Action) {
|
||||
'inspect' {
|
||||
$codex = Get-DreamSkinCodexInstall
|
||||
$processes = @(Get-DreamSkinCodexProcesses -Codex $codex)
|
||||
$debug = Get-CodexxDebugIdentity -Codex $codex
|
||||
$watcherPids = @(Get-CimInstance Win32_Process -Filter "Name = 'node.exe'" -ErrorAction SilentlyContinue |
|
||||
Where-Object {
|
||||
$_.CommandLine -and
|
||||
[regex]::IsMatch("$($_.CommandLine)", '(?i)(?:^|\s)--watch(?=$|\s)') -and
|
||||
"$($_.CommandLine)".IndexOf('injector.mjs', [System.StringComparison]::OrdinalIgnoreCase) -ge 0
|
||||
} | ForEach-Object { [int]$_.ProcessId })
|
||||
Write-CodexxJson ([pscustomobject]@{
|
||||
packageRoot = "$($codex.PackageRoot)"
|
||||
executable = "$($codex.Executable)"
|
||||
version = "$($codex.Version)"
|
||||
packageFullName = "$($codex.PackageFullName)"
|
||||
packageFamilyName = "$($codex.PackageFamilyName)"
|
||||
appUserModelId = "$($codex.AppUserModelId)"
|
||||
running = $processes.Count -gt 0
|
||||
debugPort = if ($null -eq $debug) { $null } else { [int]$debug.Port }
|
||||
browserId = if ($null -eq $debug) { $null } else { "$($debug.Identity.BrowserId)" }
|
||||
watcherPids = $watcherPids
|
||||
})
|
||||
break
|
||||
}
|
||||
'selectPort' {
|
||||
Assert-DreamSkinPort -Port $Port
|
||||
Write-CodexxJson ([pscustomobject]@{ port = (Select-DreamSkinPort -PreferredPort $Port) })
|
||||
break
|
||||
}
|
||||
'launch' {
|
||||
Assert-DreamSkinPort -Port $Port
|
||||
$codex = Get-DreamSkinCodexInstall
|
||||
$preserved = @(Get-DreamSkinCodexProcesses -Codex $codex | ForEach-Object { [int]$_.ProcessId })
|
||||
$arguments = @('--remote-debugging-address=127.0.0.1', "--remote-debugging-port=$Port")
|
||||
try {
|
||||
$launch = Start-DreamSkinCodexForDebugging -Codex $codex -Arguments $arguments `
|
||||
-Port $Port -PreserveProcessIds $preserved
|
||||
$deadline = (Get-Date).AddSeconds(45)
|
||||
$identity = Get-DreamSkinVerifiedCdpIdentity -Port $Port -Codex $codex
|
||||
while ($null -eq $identity -and (Get-Date) -lt $deadline) {
|
||||
Start-Sleep -Milliseconds 350
|
||||
$identity = Get-DreamSkinVerifiedCdpIdentity -Port $Port -Codex $codex
|
||||
}
|
||||
if ($null -eq $identity) {
|
||||
throw "Codex did not expose a verified loopback CDP endpoint on port $Port within 45 seconds."
|
||||
}
|
||||
Write-CodexxJson ([pscustomobject]@{
|
||||
port = $Port
|
||||
browserId = "$($identity.BrowserId)"
|
||||
strategy = "$($launch.Strategy)"
|
||||
})
|
||||
} catch {
|
||||
try { Stop-DreamSkinCodex -Codex $codex -PreserveProcessIds $preserved -AllowForce } catch {}
|
||||
if ($preserved.Count -eq 0 -and (Get-DreamSkinCodexProcesses -Codex $codex).Count -eq 0) {
|
||||
try { $null = Start-DreamSkinCodex -Codex $codex } catch {}
|
||||
}
|
||||
throw
|
||||
}
|
||||
break
|
||||
}
|
||||
'stopCodex' {
|
||||
$codex = Get-DreamSkinCodexInstall
|
||||
Stop-DreamSkinCodex -Codex $codex -AllowForce
|
||||
Write-CodexxJson ([pscustomobject]@{ stopped = $true })
|
||||
break
|
||||
}
|
||||
'launchNormal' {
|
||||
$codex = Get-DreamSkinCodexInstall
|
||||
$processId = Start-DreamSkinCodex -Codex $codex
|
||||
Write-CodexxJson ([pscustomobject]@{ processId = [int]$processId })
|
||||
break
|
||||
}
|
||||
'verifyPort' {
|
||||
Assert-DreamSkinPort -Port $Port
|
||||
$codex = Get-DreamSkinCodexInstall
|
||||
$identity = Get-DreamSkinVerifiedCdpIdentity -Port $Port -Codex $codex
|
||||
Write-CodexxJson ([pscustomobject]@{
|
||||
verified = $null -ne $identity
|
||||
browserId = if ($null -eq $identity) { $null } else { "$($identity.BrowserId)" }
|
||||
})
|
||||
break
|
||||
}
|
||||
'processInfo' {
|
||||
if ($TargetPid -le 0) { throw 'Target PID must be positive.' }
|
||||
$process = Get-CimInstance Win32_Process -Filter "ProcessId = $TargetPid" -ErrorAction SilentlyContinue
|
||||
if ($null -eq $process) {
|
||||
Write-CodexxJson ([pscustomobject]@{ alive = $false })
|
||||
break
|
||||
}
|
||||
Write-CodexxJson ([pscustomobject]@{
|
||||
alive = $true
|
||||
path = (Get-DreamSkinProcessExecutablePath -ProcessInfo $process)
|
||||
commandLine = "$($process.CommandLine)"
|
||||
startedAt = (Get-DreamSkinProcessStartedAt -ProcessId $TargetPid)
|
||||
})
|
||||
break
|
||||
}
|
||||
'injectorStatus' {
|
||||
$state = Get-CodexxState
|
||||
Write-CodexxJson ([pscustomobject]@{ active = (Test-CodexxInjectorState -State $state) })
|
||||
break
|
||||
}
|
||||
'stopInjector' {
|
||||
$state = Get-CodexxState
|
||||
if (-not (Test-CodexxInjectorState -State $state)) {
|
||||
$process = Get-Process -Id ([int]$state.injectorPid) -ErrorAction SilentlyContinue
|
||||
if ($null -ne $process) { throw 'The recorded skin injector identity does not match; it was not stopped.' }
|
||||
} else {
|
||||
$null = Stop-DreamSkinRecordedInjector -State $state
|
||||
}
|
||||
Write-CodexxJson ([pscustomobject]@{ stopped = $true })
|
||||
break
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
Exit-DreamSkinOperationLock -Mutex $operationLock
|
||||
}
|
||||
@@ -1,602 +0,0 @@
|
||||
$script:DreamSkinUtf8NoBom = [System.Text.UTF8Encoding]::new($false, $true)
|
||||
$script:DreamSkinLegacyAppearanceTheme = 'appearanceTheme = "light"'
|
||||
$script:DreamSkinManagedLightCodeTheme = 'appearanceLightCodeThemeId = "codex"'
|
||||
$script:DreamSkinManagedLightChromeTheme = 'appearanceLightChromeTheme = { accent = "#B65CFF", contrast = 64, fonts = { code = "Cascadia Code", ui = "Microsoft YaHei UI" }, ink = "#4A235F", opaqueWindows = true, semanticColors = { diffAdded = "#BCE8CF", diffRemoved = "#F7B8CE", skill = "#C47BFF" }, surface = "#FFF4FA" }'
|
||||
|
||||
function ConvertFrom-DreamSkinUtf8Bytes {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][AllowEmptyCollection()][byte[]]$Bytes,
|
||||
[Parameter(Mandatory = $true)][string]$Path
|
||||
)
|
||||
|
||||
try {
|
||||
$offset = if ($Bytes.Length -ge 3 -and $Bytes[0] -eq 0xEF -and $Bytes[1] -eq 0xBB -and $Bytes[2] -eq 0xBF) { 3 } else { 0 }
|
||||
$content = $script:DreamSkinUtf8NoBom.GetString($Bytes, $offset, $Bytes.Length - $offset)
|
||||
if ($content.IndexOf([char]0) -ge 0) {
|
||||
throw "Refusing to rewrite a config file containing NUL characters (possibly BOM-less UTF-16): $Path"
|
||||
}
|
||||
return $content
|
||||
} catch [System.Text.DecoderFallbackException] {
|
||||
throw "Refusing to rewrite a config file that is not valid UTF-8: $Path"
|
||||
}
|
||||
}
|
||||
|
||||
function Test-DreamSkinBytesEqual {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][AllowEmptyCollection()][byte[]]$Left,
|
||||
[Parameter(Mandatory = $true)][AllowEmptyCollection()][byte[]]$Right
|
||||
)
|
||||
if ($Left.Length -ne $Right.Length) { return $false }
|
||||
for ($index = 0; $index -lt $Left.Length; $index++) {
|
||||
if ($Left[$index] -ne $Right[$index]) { return $false }
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
function Assert-DreamSkinFileUnchanged {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Path,
|
||||
[AllowNull()][byte[]]$ExpectedBytes
|
||||
)
|
||||
if ($null -eq $ExpectedBytes) {
|
||||
if (Test-Path -LiteralPath $Path) { throw "File changed during the operation; retry without other writers: $Path" }
|
||||
return
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $Path)) { throw "File disappeared during the operation; retry: $Path" }
|
||||
$currentBytes = [System.IO.File]::ReadAllBytes($Path)
|
||||
if (-not (Test-DreamSkinBytesEqual -Left $ExpectedBytes -Right $currentBytes)) {
|
||||
throw "File changed during the operation; retry without other writers: $Path"
|
||||
}
|
||||
}
|
||||
|
||||
function Get-DreamSkinNewLine {
|
||||
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Content)
|
||||
if ($Content.Contains("`r`n")) { return "`r`n" }
|
||||
return "`n"
|
||||
}
|
||||
|
||||
function Read-DreamSkinUtf8File {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Path
|
||||
)
|
||||
|
||||
$bytes = [System.IO.File]::ReadAllBytes($Path)
|
||||
return (ConvertFrom-DreamSkinUtf8Bytes -Bytes $bytes -Path $Path)
|
||||
}
|
||||
|
||||
function Write-DreamSkinUtf8FileAtomically {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Path,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[AllowEmptyString()]
|
||||
[string]$Content,
|
||||
|
||||
[AllowNull()]
|
||||
[byte[]]$ExpectedBytes
|
||||
)
|
||||
|
||||
$bytes = $script:DreamSkinUtf8NoBom.GetBytes($Content)
|
||||
if ($PSBoundParameters.ContainsKey('ExpectedBytes')) {
|
||||
Write-DreamSkinBytesAtomically -Path $Path -Bytes $bytes -ExpectedBytes $ExpectedBytes
|
||||
} else {
|
||||
Write-DreamSkinBytesAtomically -Path $Path -Bytes $bytes
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-DreamSkinAtomicArtifact {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Path
|
||||
)
|
||||
|
||||
if ([System.IO.File]::Exists($Path)) {
|
||||
[System.IO.File]::Delete($Path)
|
||||
}
|
||||
}
|
||||
|
||||
function Write-DreamSkinBytesAtomically {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Path,
|
||||
[Parameter(Mandatory = $true)][AllowEmptyCollection()][byte[]]$Bytes,
|
||||
[AllowNull()][byte[]]$ExpectedBytes
|
||||
)
|
||||
|
||||
$fullPath = [System.IO.Path]::GetFullPath($Path)
|
||||
$directory = [System.IO.Path]::GetDirectoryName($fullPath)
|
||||
if (-not [System.IO.Directory]::Exists($directory)) {
|
||||
[System.IO.Directory]::CreateDirectory($directory) | Out-Null
|
||||
}
|
||||
$fileName = [System.IO.Path]::GetFileName($fullPath)
|
||||
$operationId = "$PID.$([guid]::NewGuid().ToString('N'))"
|
||||
$temporary = Join-Path $directory ".$fileName.$operationId.tmp"
|
||||
$replacementBackup = Join-Path $directory ".$fileName.$operationId.replace-backup"
|
||||
|
||||
try {
|
||||
[System.IO.File]::WriteAllBytes($temporary, $Bytes)
|
||||
if ($PSBoundParameters.ContainsKey('ExpectedBytes')) {
|
||||
Assert-DreamSkinFileUnchanged -Path $fullPath -ExpectedBytes $ExpectedBytes
|
||||
}
|
||||
if ([System.IO.File]::Exists($fullPath)) {
|
||||
[System.IO.File]::Replace($temporary, $fullPath, $replacementBackup)
|
||||
} else {
|
||||
[System.IO.File]::Move($temporary, $fullPath)
|
||||
}
|
||||
} finally {
|
||||
foreach ($artifact in @($temporary, $replacementBackup)) {
|
||||
try {
|
||||
Remove-DreamSkinAtomicArtifact -Path $artifact
|
||||
} catch {
|
||||
try {
|
||||
Write-Warning "Could not remove temporary atomic config artifact '$artifact': $($_.Exception.Message)"
|
||||
} catch {
|
||||
# Cleanup must never mask the result of the atomic write.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Get-DreamSkinTomlKeyTokenPattern {
|
||||
param([Parameter(Mandatory = $true)][string]$Key)
|
||||
$bare = [regex]::Escape($Key)
|
||||
$doubleQuoted = [regex]::Escape('"' + $Key + '"')
|
||||
$singleQuoted = [regex]::Escape("'" + $Key + "'")
|
||||
return "(?:$bare|$doubleQuoted|$singleQuoted)"
|
||||
}
|
||||
|
||||
function ConvertTo-DreamSkinTomlAsciiEscapeProbe {
|
||||
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Value)
|
||||
|
||||
$result = $Value
|
||||
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-'.ToCharArray()
|
||||
foreach ($character in $characters) {
|
||||
$code = ([int][char]$character).ToString('x2')
|
||||
$pattern = '(?i)\\(?:u00' + $code + '|U000000' + $code + ')'
|
||||
$result = [regex]::Replace($result, $pattern, [string]$character)
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
function Get-DreamSkinTomlArrayBracketBalance {
|
||||
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Line)
|
||||
|
||||
$quote = $null
|
||||
$escaped = $false
|
||||
$balance = 0
|
||||
for ($index = 0; $index -lt $Line.Length; $index++) {
|
||||
$character = $Line[$index]
|
||||
if ($null -eq $quote) {
|
||||
if ($character -eq '#') { break }
|
||||
if ($character -eq '"' -or $character -eq "'") { $quote = $character }
|
||||
elseif ($character -eq '[') { $balance++ }
|
||||
elseif ($character -eq ']') { $balance-- }
|
||||
continue
|
||||
}
|
||||
if ($quote -eq '"') {
|
||||
if ($escaped) { $escaped = $false; continue }
|
||||
if ($character -eq '\') { $escaped = $true; continue }
|
||||
}
|
||||
if ($character -eq $quote) { $quote = $null }
|
||||
}
|
||||
return $balance
|
||||
}
|
||||
|
||||
function Assert-DreamSkinTomlLineEditingSafe {
|
||||
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Content)
|
||||
|
||||
if ($Content.Contains('"""') -or $Content.Contains("'''")) {
|
||||
throw 'Refusing to rewrite TOML containing multiline strings; use single-line values before installing Dream Skin.'
|
||||
}
|
||||
foreach ($match in [regex]::Matches($Content, '(?m)^[^\r\n]*=[\t ]*\[[^\r\n]*\r?$')) {
|
||||
if ((Get-DreamSkinTomlArrayBracketBalance -Line $match.Value) -ne 0) {
|
||||
throw 'Refusing to rewrite TOML containing multiline arrays; use single-line arrays before installing Dream Skin.'
|
||||
}
|
||||
}
|
||||
|
||||
$probe = ConvertTo-DreamSkinTomlAsciiEscapeProbe -Value $Content
|
||||
if ($probe -cne $Content) {
|
||||
$desktopToken = Get-DreamSkinTomlKeyTokenPattern -Key 'desktop'
|
||||
$desktopShape = "(?m)^[\t ]*(?:\[\[?[\t ]*$desktopToken[\t ]*(?:\]|\.)|$desktopToken[\t ]*(?:\.|=))"
|
||||
$rawDesktopShapes = [regex]::Matches($Content, $desktopShape).Count
|
||||
$probedDesktopShapes = [regex]::Matches($probe, $desktopShape).Count
|
||||
if ($probedDesktopShapes -gt $rawDesktopShapes) {
|
||||
throw 'Refusing to rewrite an escaped TOML key equivalent to desktop; normalize the key spelling first.'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Get-DreamSkinDesktopSectionPattern {
|
||||
$desktopToken = Get-DreamSkinTomlKeyTokenPattern -Key 'desktop'
|
||||
return "(?ms)^[\t ]*\[[\t ]*$desktopToken[\t ]*\][\t ]*(?:#[^\r\n]*)?(?:\r?\n|(?=\z))(?<body>.*?)(?=^[\t ]*\[\[?|\z)"
|
||||
}
|
||||
|
||||
function Test-DreamSkinDesktopNestedTable {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$Content,
|
||||
[Parameter(Mandatory = $true)][string]$Key
|
||||
)
|
||||
|
||||
$desktopToken = Get-DreamSkinTomlKeyTokenPattern -Key 'desktop'
|
||||
$keyToken = Get-DreamSkinTomlKeyTokenPattern -Key $Key
|
||||
return [regex]::IsMatch(
|
||||
$Content,
|
||||
"(?m)^[\t ]*\[[\t ]*$desktopToken[\t ]*\.[\t ]*$keyToken[\t ]*(?:\]|\.)"
|
||||
)
|
||||
}
|
||||
|
||||
function Assert-DreamSkinDesktopShapeSupported {
|
||||
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Content)
|
||||
|
||||
Assert-DreamSkinTomlLineEditingSafe -Content $Content
|
||||
$sectionPattern = Get-DreamSkinDesktopSectionPattern
|
||||
if ([regex]::Matches($Content, $sectionPattern).Count -gt 1) {
|
||||
throw 'Refusing to rewrite multiple equivalent [desktop] tables.'
|
||||
}
|
||||
|
||||
$desktopToken = Get-DreamSkinTomlKeyTokenPattern -Key 'desktop'
|
||||
if ([regex]::IsMatch($Content, "(?m)^[\t ]*\[\[[\t ]*$desktopToken[\t ]*(?:\]\]|\.)")) {
|
||||
throw 'Refusing to rewrite a config that represents desktop as an array of tables.'
|
||||
}
|
||||
foreach ($key in @('appearanceTheme', 'appearanceLightCodeThemeId')) {
|
||||
if (Test-DreamSkinDesktopNestedTable -Content $Content -Key $key) {
|
||||
throw "Refusing to replace '$key' because it is represented as a nested desktop table."
|
||||
}
|
||||
}
|
||||
|
||||
$firstTable = [regex]::Match($Content, '(?m)^[\t ]*\[\[?')
|
||||
$rootContent = if ($firstTable.Success) { $Content.Substring(0, $firstTable.Index) } else { $Content }
|
||||
if ([regex]::IsMatch($rootContent, "(?m)^[\t ]*$desktopToken[\t ]*(?:\.|=)")) {
|
||||
throw 'Refusing to rewrite root dotted or inline desktop keys; normalize them to a [desktop] table first.'
|
||||
}
|
||||
|
||||
$desktop = Get-DreamSkinDesktopSection -Content $Content
|
||||
if ($null -ne $desktop) {
|
||||
$bodyProbe = ConvertTo-DreamSkinTomlAsciiEscapeProbe -Value $desktop.Body
|
||||
foreach ($key in @('appearanceTheme', 'appearanceLightCodeThemeId', 'appearanceLightChromeTheme')) {
|
||||
$keyToken = Get-DreamSkinTomlKeyTokenPattern -Key $key
|
||||
$settingShape = "(?m)^[\t ]*$keyToken[\t ]*(?:\.|=)"
|
||||
if ($key -eq 'appearanceLightChromeTheme' -and
|
||||
(Test-DreamSkinDesktopNestedTable -Content $Content -Key $key) -and
|
||||
[regex]::IsMatch($desktop.Body, $settingShape)) {
|
||||
throw "Refusing to rewrite '$key' because both a scalar and nested table are present."
|
||||
}
|
||||
if ([regex]::Matches($bodyProbe, $settingShape).Count -gt
|
||||
[regex]::Matches($desktop.Body, $settingShape).Count) {
|
||||
throw "Refusing to rewrite an escaped TOML key equivalent to '$key'."
|
||||
}
|
||||
if ([regex]::IsMatch($desktop.Body, "(?m)^[\t ]*$keyToken[\t ]*\.")) {
|
||||
throw "Refusing to replace dotted '$key' keys in the [desktop] table."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Get-DreamSkinDesktopSection {
|
||||
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Content)
|
||||
|
||||
$match = [regex]::Match($Content, (Get-DreamSkinDesktopSectionPattern))
|
||||
if (-not $match.Success) { return $null }
|
||||
return [pscustomobject]@{
|
||||
Body = $match.Groups['body'].Value
|
||||
BodyStart = $match.Groups['body'].Index
|
||||
BodyLength = $match.Groups['body'].Length
|
||||
SectionStart = $match.Index
|
||||
SectionLength = $match.Length
|
||||
}
|
||||
}
|
||||
|
||||
function Add-DreamSkinDesktopSection {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$Content,
|
||||
[Parameter(Mandatory = $true)][string]$NewLine
|
||||
)
|
||||
|
||||
if ($Content.Length -eq 0) { return "[desktop]$NewLine" }
|
||||
$separator = if ($Content.EndsWith("`n")) { $NewLine } else { $NewLine + $NewLine }
|
||||
return $Content + $separator + "[desktop]$NewLine"
|
||||
}
|
||||
|
||||
function Set-DreamSkinSectionSetting {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$Body,
|
||||
[Parameter(Mandatory = $true)][string]$Key,
|
||||
[AllowNull()][object]$Line,
|
||||
[Parameter(Mandatory = $true)][string]$NewLine
|
||||
)
|
||||
|
||||
$keyToken = Get-DreamSkinTomlKeyTokenPattern -Key $Key
|
||||
$pattern = "(?m)^[\t ]*$keyToken[\t ]*=[^\r\n]*(?:\r?\n|(?=\z))"
|
||||
$matcher = [regex]::new($pattern)
|
||||
if ($matcher.Matches($Body).Count -gt 1) {
|
||||
throw "Refusing to rewrite duplicate '$Key' entries in the [desktop] section."
|
||||
}
|
||||
if ($null -eq $Line) { return $matcher.Replace($Body, '', 1) }
|
||||
$normalizedLine = $Line.TrimEnd("`r", "`n") + $NewLine
|
||||
if ($matcher.IsMatch($Body)) {
|
||||
$literalReplacement = $normalizedLine.Replace('$', '$$')
|
||||
return $matcher.Replace($Body, $literalReplacement, 1)
|
||||
}
|
||||
$separator = if ($Body.Length -eq 0 -or $Body.EndsWith("`n")) { '' } else { $NewLine }
|
||||
return $Body + $separator + $normalizedLine
|
||||
}
|
||||
|
||||
function Get-DreamSkinSectionSettingLine {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$Body,
|
||||
[Parameter(Mandatory = $true)][string]$Key
|
||||
)
|
||||
$keyToken = Get-DreamSkinTomlKeyTokenPattern -Key $Key
|
||||
$matches = [regex]::Matches($Body, "(?m)^[\t ]*$keyToken[\t ]*=.*$")
|
||||
if ($matches.Count -gt 1) { throw "Refusing to inspect duplicate '$Key' entries in the [desktop] section." }
|
||||
if ($matches.Count -eq 0) { return $null }
|
||||
return $matches[0].Value.Trim()
|
||||
}
|
||||
|
||||
function Test-DreamSkinLegacyManagedLightTrio {
|
||||
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Content)
|
||||
$desktop = Get-DreamSkinDesktopSection -Content $Content
|
||||
if ($null -eq $desktop) { return $false }
|
||||
return (
|
||||
(Get-DreamSkinSectionSettingLine -Body $desktop.Body -Key 'appearanceTheme') -ceq
|
||||
$script:DreamSkinLegacyAppearanceTheme -and
|
||||
(Get-DreamSkinSectionSettingLine -Body $desktop.Body -Key 'appearanceLightCodeThemeId') -ceq
|
||||
$script:DreamSkinManagedLightCodeTheme -and
|
||||
(Get-DreamSkinSectionSettingLine -Body $desktop.Body -Key 'appearanceLightChromeTheme') -ceq
|
||||
$script:DreamSkinManagedLightChromeTheme
|
||||
)
|
||||
}
|
||||
|
||||
function Get-DreamSkinAppearanceMarkerPath {
|
||||
param([Parameter(Mandatory = $true)][string]$BackupPath)
|
||||
return "$BackupPath.appearance.json"
|
||||
}
|
||||
|
||||
function Read-DreamSkinAppearanceMarker {
|
||||
param([Parameter(Mandatory = $true)][string]$BackupPath)
|
||||
$markerPath = Get-DreamSkinAppearanceMarkerPath -BackupPath $BackupPath
|
||||
if (-not (Test-Path -LiteralPath $markerPath)) { return $null }
|
||||
try {
|
||||
$marker = (Read-DreamSkinUtf8File -Path $markerPath) | ConvertFrom-Json -ErrorAction Stop
|
||||
} catch {
|
||||
throw "Dream Skin appearance marker is unreadable; config was preserved: $markerPath"
|
||||
}
|
||||
if ($null -eq $marker -or $marker -is [string] -or $marker -is [array]) {
|
||||
throw "Dream Skin appearance marker is invalid; config was preserved: $markerPath"
|
||||
}
|
||||
$schemaVersion = 0
|
||||
try { $schemaVersion = [int]$marker.schemaVersion } catch { $schemaVersion = 0 }
|
||||
# v1 markers are always unmanaged; v2 markers may pin appearanceTheme.
|
||||
$validUnmanagedV1 = $schemaVersion -eq 1 -and $marker.appearanceThemeManaged -is [bool] -and
|
||||
-not [bool]$marker.appearanceThemeManaged
|
||||
$validV2 = $schemaVersion -eq 2 -and $marker.appearanceThemeManaged -is [bool]
|
||||
if (-not ($validUnmanagedV1 -or $validV2)) {
|
||||
throw "Dream Skin appearance marker is invalid; config was preserved: $markerPath"
|
||||
}
|
||||
return $marker
|
||||
}
|
||||
|
||||
function Write-DreamSkinAppearanceMarker {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$BackupPath,
|
||||
[bool]$Managed = $false
|
||||
)
|
||||
$markerPath = Get-DreamSkinAppearanceMarkerPath -BackupPath $BackupPath
|
||||
if (Get-Command Assert-DreamSkinNoReparseComponents -ErrorAction SilentlyContinue) {
|
||||
Assert-DreamSkinNoReparseComponents -Path $markerPath
|
||||
}
|
||||
# Unmanaged markers keep the v1 shape older engines accept; managed pins use
|
||||
# schemaVersion 2, which older engines conservatively refuse to act on.
|
||||
$schemaVersion = 1
|
||||
if ($Managed) { $schemaVersion = 2 }
|
||||
$marker = [ordered]@{
|
||||
schemaVersion = $schemaVersion
|
||||
appearanceThemeManaged = $Managed
|
||||
} | ConvertTo-Json
|
||||
Write-DreamSkinUtf8FileAtomically -Path $markerPath -Content ($marker + "`r`n")
|
||||
}
|
||||
|
||||
function Install-DreamSkinBaseTheme {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$ConfigPath,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$BackupPath,
|
||||
|
||||
[ValidateSet('auto', 'light', 'dark')]
|
||||
[string]$AppearanceTheme = 'auto'
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $ConfigPath)) { throw "Codex config not found: $ConfigPath" }
|
||||
if (Get-Command Assert-DreamSkinNoReparseComponents -ErrorAction SilentlyContinue) {
|
||||
Assert-DreamSkinNoReparseComponents -Path $BackupPath
|
||||
Assert-DreamSkinNoReparseComponents -Path (Get-DreamSkinAppearanceMarkerPath -BackupPath $BackupPath)
|
||||
}
|
||||
$originalBytes = [System.IO.File]::ReadAllBytes($ConfigPath)
|
||||
$content = ConvertFrom-DreamSkinUtf8Bytes -Bytes $originalBytes -Path $ConfigPath
|
||||
$appearanceMarker = Read-DreamSkinAppearanceMarker -BackupPath $BackupPath
|
||||
$appearanceMarkerPath = Get-DreamSkinAppearanceMarkerPath -BackupPath $BackupPath
|
||||
$appearanceMarkerExisted = Test-Path -LiteralPath $appearanceMarkerPath -PathType Leaf
|
||||
$backupCreated = $false
|
||||
if (-not (Test-Path -LiteralPath $BackupPath)) {
|
||||
Write-DreamSkinBytesAtomically -Path $BackupPath -Bytes $originalBytes -ExpectedBytes $null
|
||||
$backupCreated = $true
|
||||
}
|
||||
|
||||
$writeCompleted = $false
|
||||
try {
|
||||
Assert-DreamSkinDesktopShapeSupported -Content $content
|
||||
$newLine = Get-DreamSkinNewLine -Content $content
|
||||
$desktop = Get-DreamSkinDesktopSection -Content $content
|
||||
if ($null -eq $desktop) {
|
||||
$content = Add-DreamSkinDesktopSection -Content $content -NewLine $newLine
|
||||
$desktop = Get-DreamSkinDesktopSection -Content $content
|
||||
}
|
||||
|
||||
$body = $desktop.Body
|
||||
$backupContent = $null
|
||||
$pinnedAppearance = $AppearanceTheme -ne 'auto'
|
||||
$managedByMarker = $null -ne $appearanceMarker -and [bool]$appearanceMarker.appearanceThemeManaged
|
||||
$legacyMigration = $null -eq $appearanceMarker -and (Test-Path -LiteralPath $BackupPath) -and
|
||||
(Test-DreamSkinLegacyManagedLightTrio -Content $content)
|
||||
# Put the pre-install appearanceTheme back whenever we stop managing it:
|
||||
# either migrating away from the legacy forced-light trio, or un-pinning
|
||||
# after a fixed-appearance theme is replaced by an auto one.
|
||||
if (-not $pinnedAppearance -and ($legacyMigration -or $managedByMarker)) {
|
||||
$backupContent = ConvertFrom-DreamSkinUtf8Bytes -Bytes ([System.IO.File]::ReadAllBytes($BackupPath)) -Path $BackupPath
|
||||
Assert-DreamSkinDesktopShapeSupported -Content $backupContent
|
||||
$backupDesktop = Get-DreamSkinDesktopSection -Content $backupContent
|
||||
$savedAppearance = if ($null -ne $backupDesktop) {
|
||||
Get-DreamSkinSectionSettingLine -Body $backupDesktop.Body -Key 'appearanceTheme'
|
||||
} else { $null }
|
||||
$body = Set-DreamSkinSectionSetting -Body $body -Key 'appearanceTheme' -Line $savedAppearance -NewLine $newLine
|
||||
}
|
||||
if ($pinnedAppearance) {
|
||||
# Native token surfaces (dropdowns/popovers) follow appearanceTheme, so a
|
||||
# fixed-appearance theme pins it to match; Restore puts the original back.
|
||||
$body = Set-DreamSkinSectionSetting -Body $body -Key 'appearanceTheme' `
|
||||
-Line ('appearanceTheme = "{0}"' -f $AppearanceTheme) -NewLine $newLine
|
||||
}
|
||||
$settings = [ordered]@{
|
||||
appearanceLightCodeThemeId = $script:DreamSkinManagedLightCodeTheme
|
||||
appearanceLightChromeTheme = $script:DreamSkinManagedLightChromeTheme
|
||||
}
|
||||
$hasNestedLightChromeTheme = Test-DreamSkinDesktopNestedTable `
|
||||
-Content $content -Key 'appearanceLightChromeTheme'
|
||||
foreach ($key in $settings.Keys) {
|
||||
if ($key -eq 'appearanceLightChromeTheme' -and $hasNestedLightChromeTheme) { continue }
|
||||
$body = Set-DreamSkinSectionSetting -Body $body -Key $key -Line $settings[$key] -NewLine $newLine
|
||||
}
|
||||
|
||||
$content = $content.Substring(0, $desktop.BodyStart) + $body +
|
||||
$content.Substring($desktop.BodyStart + $desktop.BodyLength)
|
||||
# Commit the metadata first. A config commit must never exist without the
|
||||
# marker that tells restore exactly which appearance keys we own.
|
||||
Write-DreamSkinAppearanceMarker -BackupPath $BackupPath -Managed $pinnedAppearance
|
||||
Write-DreamSkinUtf8FileAtomically -Path $ConfigPath -Content $content -ExpectedBytes $originalBytes
|
||||
$writeCompleted = $true
|
||||
} catch {
|
||||
if (-not $writeCompleted) {
|
||||
$configUnchanged = $false
|
||||
try {
|
||||
$configUnchanged = (Test-Path -LiteralPath $ConfigPath -PathType Leaf) -and
|
||||
(Test-DreamSkinBytesEqual -Left $originalBytes -Right ([System.IO.File]::ReadAllBytes($ConfigPath)))
|
||||
} catch {
|
||||
$configUnchanged = $false
|
||||
}
|
||||
if ($configUnchanged) {
|
||||
$markerCleanupSucceeded = $true
|
||||
if (-not $appearanceMarkerExisted -and (Test-Path -LiteralPath $appearanceMarkerPath)) {
|
||||
try {
|
||||
Remove-Item -LiteralPath $appearanceMarkerPath -Force -ErrorAction Stop
|
||||
} catch {
|
||||
$markerCleanupSucceeded = $false
|
||||
}
|
||||
}
|
||||
if ($markerCleanupSucceeded -and $backupCreated) {
|
||||
Remove-Item -LiteralPath $BackupPath -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
}
|
||||
throw
|
||||
}
|
||||
}
|
||||
|
||||
function Restore-DreamSkinBaseTheme {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$ConfigPath,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$BackupPath
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $BackupPath)) { throw 'No pre-install config backup is available.' }
|
||||
if (Get-Command Assert-DreamSkinNoReparseComponents -ErrorAction SilentlyContinue) {
|
||||
Assert-DreamSkinNoReparseComponents -Path $BackupPath
|
||||
Assert-DreamSkinNoReparseComponents -Path (Get-DreamSkinAppearanceMarkerPath -BackupPath $BackupPath)
|
||||
}
|
||||
$backupBytes = [System.IO.File]::ReadAllBytes($BackupPath)
|
||||
$backupContent = ConvertFrom-DreamSkinUtf8Bytes -Bytes $backupBytes -Path $BackupPath
|
||||
$currentBytes = [System.IO.File]::ReadAllBytes($ConfigPath)
|
||||
$currentContent = ConvertFrom-DreamSkinUtf8Bytes -Bytes $currentBytes -Path $ConfigPath
|
||||
Assert-DreamSkinDesktopShapeSupported -Content $backupContent
|
||||
Assert-DreamSkinDesktopShapeSupported -Content $currentContent
|
||||
$newLine = Get-DreamSkinNewLine -Content $currentContent
|
||||
$backupDesktop = Get-DreamSkinDesktopSection -Content $backupContent
|
||||
$currentDesktop = Get-DreamSkinDesktopSection -Content $currentContent
|
||||
if ($null -eq $currentDesktop) {
|
||||
$currentContent = Add-DreamSkinDesktopSection -Content $currentContent -NewLine $newLine
|
||||
$currentDesktop = Get-DreamSkinDesktopSection -Content $currentContent
|
||||
}
|
||||
|
||||
$body = $currentDesktop.Body
|
||||
$appearanceMarker = Read-DreamSkinAppearanceMarker -BackupPath $BackupPath
|
||||
$restoreLegacyAppearance = $null -eq $appearanceMarker -and
|
||||
(Test-DreamSkinLegacyManagedLightTrio -Content $currentContent)
|
||||
$restoreManagedAppearance = $null -ne $appearanceMarker -and
|
||||
[bool]$appearanceMarker.appearanceThemeManaged
|
||||
$restoreKeys = @('appearanceLightCodeThemeId', 'appearanceLightChromeTheme')
|
||||
if ($restoreLegacyAppearance -or $restoreManagedAppearance) {
|
||||
$restoreKeys = @('appearanceTheme') + $restoreKeys
|
||||
}
|
||||
$hasNestedLightChromeTheme = Test-DreamSkinDesktopNestedTable `
|
||||
-Content $currentContent -Key 'appearanceLightChromeTheme'
|
||||
foreach ($key in $restoreKeys) {
|
||||
if ($key -eq 'appearanceLightChromeTheme' -and $hasNestedLightChromeTheme) { continue }
|
||||
$keyToken = Get-DreamSkinTomlKeyTokenPattern -Key $key
|
||||
$pattern = "(?m)^[\t ]*$keyToken[\t ]*=[^\r\n]*(?:\r?\n|(?=\z))"
|
||||
$saved = if ($null -ne $backupDesktop) { [regex]::Match($backupDesktop.Body, $pattern) } else { $null }
|
||||
$line = if ($null -ne $saved -and $saved.Success) { $saved.Value } else { $null }
|
||||
$body = Set-DreamSkinSectionSetting -Body $body -Key $key -Line $line -NewLine $newLine
|
||||
}
|
||||
if ($null -eq $backupDesktop -and [string]::IsNullOrWhiteSpace($body)) {
|
||||
$currentContent = $currentContent.Remove($currentDesktop.SectionStart, $currentDesktop.SectionLength)
|
||||
} else {
|
||||
$currentContent = $currentContent.Substring(0, $currentDesktop.BodyStart) + $body +
|
||||
$currentContent.Substring($currentDesktop.BodyStart + $currentDesktop.BodyLength)
|
||||
}
|
||||
Write-DreamSkinUtf8FileAtomically -Path $ConfigPath -Content $currentContent -ExpectedBytes $currentBytes
|
||||
}
|
||||
|
||||
function Restore-DreamSkinConfigBackup {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$ConfigPath,
|
||||
[Parameter(Mandatory = $true)][string]$BackupPath,
|
||||
[Parameter(Mandatory = $true)][string]$RecoveryBackupPath
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $BackupPath)) { throw 'No pre-install config backup is available.' }
|
||||
$backupBytes = [System.IO.File]::ReadAllBytes($BackupPath)
|
||||
$null = ConvertFrom-DreamSkinUtf8Bytes -Bytes $backupBytes -Path $BackupPath
|
||||
$currentBytes = $null
|
||||
if (Test-Path -LiteralPath $ConfigPath) {
|
||||
$currentBytes = [System.IO.File]::ReadAllBytes($ConfigPath)
|
||||
Write-DreamSkinBytesAtomically -Path $RecoveryBackupPath -Bytes $currentBytes -ExpectedBytes $null
|
||||
}
|
||||
|
||||
Write-DreamSkinBytesAtomically -Path $ConfigPath -Bytes $backupBytes -ExpectedBytes $currentBytes
|
||||
}
|
||||
|
||||
function Archive-DreamSkinConfigBackup {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$BackupPath,
|
||||
[Parameter(Mandatory = $true)][string]$ArchivePath
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $BackupPath)) { return }
|
||||
if (Test-Path -LiteralPath $ArchivePath) { throw "Config backup archive already exists: $ArchivePath" }
|
||||
Move-Item -LiteralPath $BackupPath -Destination $ArchivePath -ErrorAction Stop
|
||||
Remove-Item -LiteralPath (Get-DreamSkinAppearanceMarkerPath -BackupPath $BackupPath) -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
The official Windows release workflow places the pinned Node.js runtime here.
|
||||
|
||||
Version: 22.23.1
|
||||
Archive: node-v22.23.1-win-x64.zip
|
||||
SHA-256: 7df0bc9375723f4a86b3aa1b7cc73342423d9677a8df4538aca31a049e309c29
|
||||
Source: https://nodejs.org/dist/v22.23.1/node-v22.23.1-win-x64.zip
|
||||
|
||||
Local source builds may use Node.js 22 or newer from PATH instead.
|
||||
@@ -3,7 +3,110 @@ use crate::file_io::ensure_directory;
|
||||
use crate::paths::app_home;
|
||||
use crate::sqlite_utils::table_column_set;
|
||||
use rusqlite::Connection;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
const APP_DB_SCHEMA_VERSION: i64 = 8;
|
||||
|
||||
struct DatabaseInitializer {
|
||||
migration_lock: Mutex<()>,
|
||||
}
|
||||
|
||||
impl DatabaseInitializer {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
migration_lock: Mutex::new(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_at(&self, path: &Path) -> Result<Connection> {
|
||||
self.open_at_with(path, initialize_schema)
|
||||
}
|
||||
|
||||
fn open_at_with(
|
||||
&self,
|
||||
path: &Path,
|
||||
initialize: impl FnOnce(&Connection) -> Result<()>,
|
||||
) -> Result<Connection> {
|
||||
if let Some(parent) = path.parent() {
|
||||
ensure_directory(parent)?;
|
||||
}
|
||||
let conn = Connection::open(path).map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
conn.busy_timeout(Duration::from_secs(5))
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
|
||||
if schema_is_current(&conn)? {
|
||||
return Ok(conn);
|
||||
}
|
||||
|
||||
// Serialize first-time migrations inside this process. The persistent
|
||||
// schema version also prevents repeated migrations across launches and
|
||||
// detects a database replaced at the same path.
|
||||
let _migration_guard = self
|
||||
.migration_lock
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if !schema_is_current(&conn)? {
|
||||
migrate_schema(&conn, initialize)?;
|
||||
}
|
||||
Ok(conn)
|
||||
}
|
||||
}
|
||||
|
||||
fn schema_version(conn: &Connection) -> Result<i64> {
|
||||
conn.pragma_query_value(None, "user_version", |row| row.get(0))
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))
|
||||
}
|
||||
|
||||
fn schema_is_current(conn: &Connection) -> Result<bool> {
|
||||
Ok(schema_version(conn)? >= APP_DB_SCHEMA_VERSION)
|
||||
}
|
||||
|
||||
fn migrate_schema(
|
||||
conn: &Connection,
|
||||
initialize: impl FnOnce(&Connection) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
conn.execute_batch("BEGIN IMMEDIATE")
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
|
||||
let migration = (|| {
|
||||
// Another Codex-X process may have completed the migration while this
|
||||
// connection waited for SQLite's write lock.
|
||||
if !schema_is_current(conn)? {
|
||||
initialize(conn)?;
|
||||
conn.pragma_update(None, "user_version", APP_DB_SCHEMA_VERSION)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
}
|
||||
conn.execute_batch("COMMIT")
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))
|
||||
})();
|
||||
|
||||
match migration {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) => match conn.execute_batch("ROLLBACK") {
|
||||
Ok(()) => Err(error),
|
||||
Err(rollback_error) => Err(CodexxError::Database(format!(
|
||||
"{error}; app database migration rollback failed: {rollback_error}"
|
||||
))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn database_initializer() -> &'static DatabaseInitializer {
|
||||
static INITIALIZER: OnceLock<DatabaseInitializer> = OnceLock::new();
|
||||
INITIALIZER.get_or_init(DatabaseInitializer::new)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_db_guard() -> std::sync::MutexGuard<'static, ()> {
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
static TEST_DB_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
||||
TEST_DB_LOCK
|
||||
.get_or_init(|| Mutex::new(()))
|
||||
.lock()
|
||||
.expect("test app database lock poisoned")
|
||||
}
|
||||
|
||||
fn db_path() -> Result<PathBuf> {
|
||||
Ok(app_home()?.join("codexx.db"))
|
||||
@@ -34,12 +137,7 @@ fn ensure_sqlite_column(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn open() -> Result<Connection> {
|
||||
let path = db_path()?;
|
||||
if let Some(parent) = path.parent() {
|
||||
ensure_directory(parent)?;
|
||||
}
|
||||
let conn = Connection::open(&path).map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
fn initialize_schema(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS providers (
|
||||
id TEXT PRIMARY KEY,
|
||||
@@ -50,6 +148,9 @@ pub(crate) fn open() -> Result<Connection> {
|
||||
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
|
||||
);
|
||||
@@ -71,6 +172,12 @@ pub(crate) fn open() -> Result<Connection> {
|
||||
checked_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS builtin_prompt_overrides (
|
||||
template_id TEXT PRIMARY KEY,
|
||||
content TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS managed_mcp_servers (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
@@ -87,15 +194,78 @@ pub(crate) fn open() -> Result<Connection> {
|
||||
content_hash TEXT,
|
||||
enabled INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS skills_mcp_notes (
|
||||
codex_dir TEXT NOT NULL,
|
||||
item_kind TEXT NOT NULL CHECK(item_kind IN ('skill', 'mcp')),
|
||||
item_id TEXT NOT NULL,
|
||||
note TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
PRIMARY KEY(codex_dir, item_kind, item_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS active_provider_selections (
|
||||
codex_dir TEXT PRIMARY KEY,
|
||||
provider_id TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS provider_failover (
|
||||
codex_dir TEXT PRIMARY KEY,
|
||||
record_json TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS provider_common_config_state (
|
||||
codex_dir TEXT PRIMARY KEY,
|
||||
handled_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS official_profiles (
|
||||
codex_dir TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
provider_name TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
PRIMARY KEY(codex_dir, id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS official_profile_selections (
|
||||
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()))?;
|
||||
ensure_sqlite_column(
|
||||
&conn,
|
||||
conn,
|
||||
"providers",
|
||||
"toml_config",
|
||||
"ALTER TABLE providers ADD COLUMN toml_config TEXT",
|
||||
)?;
|
||||
ensure_sqlite_column(
|
||||
conn,
|
||||
"providers",
|
||||
"source",
|
||||
"ALTER TABLE providers ADD COLUMN source TEXT NOT NULL DEFAULT 'manual'",
|
||||
)?;
|
||||
ensure_sqlite_column(
|
||||
conn,
|
||||
"providers",
|
||||
"source_id",
|
||||
"ALTER TABLE providers ADD COLUMN source_id TEXT",
|
||||
)?;
|
||||
ensure_sqlite_column(
|
||||
conn,
|
||||
"providers",
|
||||
"model_mappings_json",
|
||||
"ALTER TABLE providers ADD COLUMN model_mappings_json TEXT NOT NULL DEFAULT '[]'",
|
||||
)?;
|
||||
conn.execute_batch(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_providers_source_identity
|
||||
ON providers(source, source_id)
|
||||
WHERE source_id IS NOT NULL;",
|
||||
)
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
conn.execute(
|
||||
"DELETE FROM prompts
|
||||
WHERE id LIKE 'external-%'
|
||||
@@ -131,5 +301,364 @@ pub(crate) fn open() -> Result<Connection> {
|
||||
[],
|
||||
)
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
Ok(conn)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn open() -> Result<Connection> {
|
||||
database_initializer().open_at(&db_path()?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Barrier};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
fn test_db_path(name: &str) -> PathBuf {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let suffix = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
std::env::temp_dir()
|
||||
.join(format!(
|
||||
"codex-x-app-db-{name}-{}-{suffix}",
|
||||
std::process::id()
|
||||
))
|
||||
.join("codexx.db")
|
||||
}
|
||||
|
||||
fn remove_test_db(path: &Path) {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::remove_dir_all(parent).expect("remove app database test directory");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_opens_do_not_rerun_legacy_cleanup() {
|
||||
let path = test_db_path("cleanup-once");
|
||||
let initializer = DatabaseInitializer::new();
|
||||
let conn = initializer.open_at(&path).expect("initialize database");
|
||||
conn.execute_batch(
|
||||
"INSERT INTO prompts (id, title, filename, content, created_at, updated_at)
|
||||
VALUES
|
||||
('kept', 'Kept', 'same.md', 'same', '1', '1'),
|
||||
('external-duplicate', 'Duplicate', 'same.md', 'same', '2', '2');",
|
||||
)
|
||||
.expect("seed a post-migration duplicate");
|
||||
drop(conn);
|
||||
|
||||
let reopened_initializer = DatabaseInitializer::new();
|
||||
let conn = reopened_initializer
|
||||
.open_at(&path)
|
||||
.expect("reopen database in a new process lifecycle");
|
||||
let count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM prompts", [], |row| row.get(0))
|
||||
.expect("count prompts after reopen");
|
||||
assert_eq!(count, 2, "reopen must not rerun migration cleanup");
|
||||
drop(conn);
|
||||
remove_test_db(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn database_replaced_at_the_same_path_is_initialized_again() {
|
||||
let path = test_db_path("replace-database");
|
||||
let initializer = DatabaseInitializer::new();
|
||||
let conn = initializer.open_at(&path).expect("initialize database");
|
||||
assert_eq!(
|
||||
schema_version(&conn).expect("read schema version"),
|
||||
APP_DB_SCHEMA_VERSION
|
||||
);
|
||||
drop(conn);
|
||||
|
||||
fs::remove_file(&path).expect("replace initialized database");
|
||||
let conn = initializer
|
||||
.open_at(&path)
|
||||
.expect("initialize replacement database");
|
||||
let provider_count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM providers", [], |row| row.get(0))
|
||||
.expect("query replacement database schema");
|
||||
assert_eq!(provider_count, 0);
|
||||
assert_eq!(
|
||||
schema_version(&conn).expect("read replacement version"),
|
||||
APP_DB_SCHEMA_VERSION
|
||||
);
|
||||
drop(conn);
|
||||
remove_test_db(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_four_provider_rows_migrate_with_empty_model_mappings() {
|
||||
let path = test_db_path("provider-model-mappings-v5");
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).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,
|
||||
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, source, source_id, created_at, updated_at)
|
||||
VALUES ('legacy-models', 'Existing provider', 'https://migration.example.test/v1', 'existing-model', 'fixture-key', 'cc-switch', 'source-row', 'original-created', 'original-updated');
|
||||
PRAGMA user_version = 4;").unwrap();
|
||||
drop(legacy);
|
||||
let migrated = DatabaseInitializer::new().open_at(&path).unwrap();
|
||||
assert_eq!(schema_version(&migrated).unwrap(), APP_DB_SCHEMA_VERSION);
|
||||
assert_eq!(
|
||||
migrated
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM provider_common_config_state",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0)
|
||||
)
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
let stored = crate::providers::list_saved_providers_on_connection(&migrated).unwrap();
|
||||
assert_eq!(stored.len(), 1);
|
||||
assert!(stored[0].model_mappings.is_empty());
|
||||
assert_eq!(stored[0].model, "existing-model");
|
||||
assert_eq!(stored[0].api_key.as_deref(), Some("fixture-key"));
|
||||
let metadata: (String, String, String, String, String) = migrated.query_row(
|
||||
"SELECT source, source_id, created_at, updated_at, model_mappings_json FROM providers WHERE id = 'legacy-models'", [],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)),
|
||||
).unwrap();
|
||||
assert_eq!(
|
||||
metadata,
|
||||
(
|
||||
"cc-switch".into(),
|
||||
"source-row".into(),
|
||||
"original-created".into(),
|
||||
"original-updated".into(),
|
||||
"[]".into()
|
||||
)
|
||||
);
|
||||
drop(migrated);
|
||||
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_one_database_migrates_new_metadata_tables_without_data_loss() {
|
||||
let path = test_db_path("skills-mcp-notes-migration");
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).expect("create legacy database directory");
|
||||
}
|
||||
let legacy = Connection::open(&path).expect("create legacy database");
|
||||
legacy
|
||||
.execute_batch(
|
||||
"CREATE TABLE managed_skills (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
directory TEXT NOT NULL,
|
||||
source_path TEXT,
|
||||
content_hash TEXT,
|
||||
enabled INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
INSERT INTO managed_skills
|
||||
(id, name, directory, enabled, updated_at)
|
||||
VALUES ('legacy-skill', 'Legacy skill', 'legacy-skill', 1, '2026-01-01T00:00:00Z');
|
||||
PRAGMA user_version = 1;",
|
||||
)
|
||||
.expect("seed version one database");
|
||||
drop(legacy);
|
||||
|
||||
let initializer = DatabaseInitializer::new();
|
||||
let migrated = initializer.open_at(&path).expect("migrate database");
|
||||
assert_eq!(
|
||||
schema_version(&migrated).expect("read migrated schema version"),
|
||||
APP_DB_SCHEMA_VERSION
|
||||
);
|
||||
let skill_count: i64 = migrated
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM managed_skills WHERE id = 'legacy-skill'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.expect("count preserved skill");
|
||||
assert_eq!(skill_count, 1);
|
||||
migrated
|
||||
.execute(
|
||||
"INSERT INTO skills_mcp_notes
|
||||
(codex_dir, item_kind, item_id, note, updated_at)
|
||||
VALUES
|
||||
('/tmp/legacy-codex', 'skill', 'legacy-skill', 'my note', '2026-01-02T00:00:00Z')",
|
||||
[],
|
||||
)
|
||||
.expect("write note after migration");
|
||||
migrated
|
||||
.execute(
|
||||
"INSERT INTO active_provider_selections
|
||||
(codex_dir, provider_id, updated_at)
|
||||
VALUES
|
||||
('/tmp/legacy-codex', 'legacy-provider', '2026-01-02T00:00:00Z')",
|
||||
[],
|
||||
)
|
||||
.expect("write active provider selection after migration");
|
||||
drop(migrated);
|
||||
remove_test_db(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_first_opens_initialize_once() {
|
||||
let path = test_db_path("concurrent-init");
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
let barrier = Arc::new(Barrier::new(3));
|
||||
let mut workers = Vec::new();
|
||||
|
||||
for _ in 0..2 {
|
||||
let path = path.clone();
|
||||
// Separate initializers model independent Codex-X processes; the
|
||||
// SQLite transaction and persistent version still permit one run.
|
||||
let initializer = DatabaseInitializer::new();
|
||||
let attempts = Arc::clone(&attempts);
|
||||
let barrier = Arc::clone(&barrier);
|
||||
workers.push(thread::spawn(move || {
|
||||
barrier.wait();
|
||||
initializer.open_at_with(&path, |conn| {
|
||||
attempts.fetch_add(1, Ordering::SeqCst);
|
||||
thread::sleep(Duration::from_millis(25));
|
||||
conn.execute_batch("CREATE TABLE initialized_once (id INTEGER PRIMARY KEY);")
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))
|
||||
})
|
||||
}));
|
||||
}
|
||||
|
||||
barrier.wait();
|
||||
for worker in workers {
|
||||
drop(
|
||||
worker
|
||||
.join()
|
||||
.expect("join concurrent database opener")
|
||||
.expect("open database concurrently"),
|
||||
);
|
||||
}
|
||||
assert_eq!(attempts.load(Ordering::SeqCst), 1);
|
||||
remove_test_db(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_initialization_can_retry() {
|
||||
let path = test_db_path("retry-init");
|
||||
let initializer = DatabaseInitializer::new();
|
||||
let attempts = AtomicUsize::new(0);
|
||||
|
||||
let error = initializer
|
||||
.open_at_with(&path, |_| {
|
||||
attempts.fetch_add(1, Ordering::SeqCst);
|
||||
Err(CodexxError::Database(
|
||||
"injected transient initialization failure".to_string(),
|
||||
))
|
||||
})
|
||||
.expect_err("first initialization must fail");
|
||||
assert!(error
|
||||
.to_string()
|
||||
.contains("transient initialization failure"));
|
||||
|
||||
let conn = initializer
|
||||
.open_at_with(&path, |conn| {
|
||||
attempts.fetch_add(1, Ordering::SeqCst);
|
||||
conn.execute_batch("CREATE TABLE retry_succeeded (id INTEGER PRIMARY KEY);")
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))
|
||||
})
|
||||
.expect("retry initialization");
|
||||
drop(conn);
|
||||
let conn = initializer
|
||||
.open_at_with(&path, |_| {
|
||||
attempts.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(())
|
||||
})
|
||||
.expect("open initialized database");
|
||||
assert_eq!(attempts.load(Ordering::SeqCst), 2);
|
||||
drop(conn);
|
||||
remove_test_db(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialized_read_connection_does_not_need_a_write_lock() {
|
||||
let path = test_db_path("read-with-writer");
|
||||
let initializer = DatabaseInitializer::new();
|
||||
let writer = initializer.open_at(&path).expect("initialize database");
|
||||
writer
|
||||
.execute_batch("BEGIN IMMEDIATE")
|
||||
.expect("hold database write reservation");
|
||||
|
||||
let reader = initializer
|
||||
.open_at(&path)
|
||||
.expect("open reader while write reservation is held");
|
||||
let count: i64 = reader
|
||||
.query_row("SELECT COUNT(*) FROM providers", [], |row| row.get(0))
|
||||
.expect("read while another connection holds write reservation");
|
||||
assert_eq!(count, 0);
|
||||
|
||||
drop(reader);
|
||||
writer
|
||||
.execute_batch("ROLLBACK")
|
||||
.expect("release write lock");
|
||||
drop(writer);
|
||||
remove_test_db(&path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
//! 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, 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);
|
||||
const DOWNLOAD_TIMEOUT_MS: u64 = 10 * 60 * 1000;
|
||||
|
||||
#[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()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// 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 update = webview
|
||||
.resources_table()
|
||||
.get::<Update>(update_rid)
|
||||
.map_err(|_| {
|
||||
failure(
|
||||
FailureStage::Prepare,
|
||||
"更新信息已失效,请重新检查更新。",
|
||||
None,
|
||||
)
|
||||
})?;
|
||||
let mut update = (*update).clone();
|
||||
// The 15s 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 finished = AtomicBool::new(false);
|
||||
let mut started = false;
|
||||
let bytes = 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) {
|
||||
log.record("signature_verification_failed");
|
||||
failure(
|
||||
FailureStage::Verify,
|
||||
"更新包校验未通过,安装尚未启动。请重新下载或前往下载页。",
|
||||
Some(&log),
|
||||
)
|
||||
} else {
|
||||
log.record("download_failed");
|
||||
failure(
|
||||
FailureStage::Download,
|
||||
"更新下载未完成或连接超时。请检查网络后重试。",
|
||||
Some(&log),
|
||||
)
|
||||
}
|
||||
})?;
|
||||
log.record("signature_verified");
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let app = webview.app_handle().clone();
|
||||
let result = install_windows(app, bytes, on_event, log).await;
|
||||
if result.is_ok() {
|
||||
_lease.handoff();
|
||||
}
|
||||
result
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
let _ = on_event.send(AppUpdateEvent::Installing);
|
||||
log.record("install_started");
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
update.install(bytes).map_err(|_| {
|
||||
log.record("install_failed");
|
||||
failure(
|
||||
FailureStage::Install,
|
||||
"安装更新未完成,请重试或前往下载页安装。",
|
||||
Some(&log),
|
||||
)
|
||||
})?;
|
||||
log.record("install_finished_restart_required");
|
||||
Ok(InstallResult {
|
||||
restart_required: true,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|_| {
|
||||
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,
|
||||
) -> 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");
|
||||
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.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.
|
||||
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 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"));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::constants::AGENTS_FILENAME;
|
||||
use crate::error::Result;
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::{ensure_directory, io_err, write_json};
|
||||
use crate::paths::app_home;
|
||||
use crate::prompts::agents_path;
|
||||
@@ -7,7 +7,7 @@ use crate::{auth_path, config_path};
|
||||
use chrono::Local;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -40,6 +40,84 @@ pub(crate) struct BackupEntry {
|
||||
had_agents: bool,
|
||||
}
|
||||
|
||||
fn lexical_absolute_path(path: &Path) -> Result<PathBuf> {
|
||||
let absolute = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.map_err(|error| io_err(path, error))?
|
||||
.join(path)
|
||||
};
|
||||
let mut normalized = PathBuf::new();
|
||||
for component in absolute.components() {
|
||||
match component {
|
||||
Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
|
||||
Component::RootDir => normalized.push(component.as_os_str()),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
normalized.pop();
|
||||
}
|
||||
Component::Normal(part) => normalized.push(part),
|
||||
}
|
||||
}
|
||||
Ok(normalized)
|
||||
}
|
||||
|
||||
/// Resolves every existing ancestor while retaining a normalized suffix. This
|
||||
/// compares missing CODEX_HOME targets without requiring the target to exist.
|
||||
fn normalized_path_identity(path: &Path) -> Result<PathBuf> {
|
||||
let absolute = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.map_err(|error| io_err(path, error))?
|
||||
.join(path)
|
||||
};
|
||||
for ancestor in absolute.ancestors() {
|
||||
match fs::canonicalize(ancestor) {
|
||||
Ok(canonical) => {
|
||||
let suffix = absolute
|
||||
.strip_prefix(ancestor)
|
||||
.expect("ancestor must be a path prefix");
|
||||
return lexical_absolute_path(&canonical.join(suffix));
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(io_err(ancestor, error)),
|
||||
}
|
||||
}
|
||||
lexical_absolute_path(&absolute)
|
||||
}
|
||||
|
||||
fn same_path_identity(left: &Path, right: &Path) -> Result<bool> {
|
||||
let left = normalized_path_identity(left)?;
|
||||
let right = normalized_path_identity(right)?;
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let left = left.to_string_lossy().replace('/', "\\");
|
||||
let right = right.to_string_lossy().replace('/', "\\");
|
||||
Ok(left.eq_ignore_ascii_case(&right))
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
Ok(left == right)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_backup_codex_dir(meta: &BackupMeta, codex_dir: &Path) -> Result<()> {
|
||||
let recorded = meta.codex_dir.trim();
|
||||
if recorded.is_empty() {
|
||||
return Err(CodexxError::Config("备份元数据缺少 CODEX_HOME".to_string()));
|
||||
}
|
||||
if same_path_identity(Path::new(recorded), codex_dir)? {
|
||||
return Ok(());
|
||||
}
|
||||
Err(CodexxError::Config(format!(
|
||||
"备份属于其他 CODEX_HOME,拒绝恢复:备份为 {},当前为 {}",
|
||||
Path::new(recorded).display(),
|
||||
codex_dir.display()
|
||||
)))
|
||||
}
|
||||
|
||||
fn backup_root() -> Result<PathBuf> {
|
||||
Ok(app_home()?.join("backups"))
|
||||
}
|
||||
@@ -138,7 +216,3 @@ pub(crate) fn backups() -> Result<Vec<BackupEntry>> {
|
||||
entries.sort_by(|a, b| b.created_at.cmp(&a.created_at));
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
pub(crate) fn latest_backup() -> Result<Option<BackupEntry>> {
|
||||
Ok(backups()?.into_iter().next())
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use crate::backups::create_backup;
|
||||
use crate::config_path;
|
||||
use crate::error::Result;
|
||||
use crate::file_io::{parse_toml_document, read_to_string_if_exists, write_text};
|
||||
use crate::file_io::parse_toml_document;
|
||||
#[cfg(test)]
|
||||
use crate::live_config::acquire_live_config_lock;
|
||||
use crate::live_config::{atomic_write_if_unchanged, read_file_snapshot, text_from_snapshot};
|
||||
use std::path::Path;
|
||||
use toml_edit::{DocumentMut, Item, Table};
|
||||
|
||||
@@ -28,14 +31,18 @@ fn remove_markdown_path(table: &mut Table, key: &str) -> Option<Item> {
|
||||
|
||||
/// Repairs prompt paths appended by older Codex-X versions after a `[tui]`
|
||||
/// header. Only the exact legacy keys with Markdown path values are touched.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn migrate_legacy_prompt_config(codex_dir: &Path) -> Result<bool> {
|
||||
let cfg = config_path(codex_dir);
|
||||
let text = read_to_string_if_exists(&cfg)?;
|
||||
let _lock = acquire_live_config_lock(codex_dir)?;
|
||||
migrate_legacy_prompt_config_locked(codex_dir)
|
||||
}
|
||||
|
||||
pub(crate) fn migrated_legacy_prompt_config_text(cfg: &Path, text: &str) -> Result<Option<String>> {
|
||||
if text.trim().is_empty() {
|
||||
return Ok(false);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut doc = parse_toml_document(&cfg, &text)?;
|
||||
let mut doc = parse_toml_document(cfg, text)?;
|
||||
let nested_instruction = tui_table(&doc)
|
||||
.and_then(|tui| tui.get(MODEL_AVAILABILITY_NUX_KEY))
|
||||
.and_then(|item| item.as_table())
|
||||
@@ -46,12 +53,10 @@ pub(crate) fn migrate_legacy_prompt_config(codex_dir: &Path) -> Result<bool> {
|
||||
tui_table(&doc).is_some_and(|tui| markdown_path(tui.get(MODEL_AVAILABILITY_NUX_KEY)));
|
||||
|
||||
if !nested_instruction && !tui_instruction && !nux_as_instruction {
|
||||
return Ok(false);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let root_instruction_exists = doc.as_table().contains_key(INSTRUCTION_KEY);
|
||||
create_backup(codex_dir, "migrate-legacy-prompt-config")?;
|
||||
|
||||
let removed_nested = doc
|
||||
.get_mut("tui")
|
||||
.and_then(|item| item.as_table_mut())
|
||||
@@ -75,7 +80,19 @@ pub(crate) fn migrate_legacy_prompt_config(codex_dir: &Path) -> Result<bool> {
|
||||
doc.as_table_mut().insert(INSTRUCTION_KEY, instruction);
|
||||
}
|
||||
|
||||
write_text(&cfg, &doc.to_string())?;
|
||||
Ok(Some(doc.to_string()))
|
||||
}
|
||||
|
||||
pub(crate) fn migrate_legacy_prompt_config_locked(codex_dir: &Path) -> Result<bool> {
|
||||
let cfg = config_path(codex_dir);
|
||||
let original = read_file_snapshot(&cfg)?;
|
||||
let text = text_from_snapshot(&cfg, original.as_deref())?;
|
||||
let Some(migrated) = migrated_legacy_prompt_config_text(&cfg, &text)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
create_backup(codex_dir, "migrate-legacy-prompt-config")?;
|
||||
|
||||
atomic_write_if_unchanged(&cfg, original.as_deref(), migrated.as_bytes())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
|
||||
@@ -30,5 +30,3 @@ pub(crate) const GITHUB_EXAMPLES_API: &str =
|
||||
"https://api.github.com/repos/yynxxxxx/Codex-X/contents/examples?ref=main";
|
||||
pub(crate) const GITHUB_EXAMPLES_BASE: &str =
|
||||
"https://raw.githubusercontent.com/yynxxxxx/Codex-X/main/examples/";
|
||||
|
||||
pub(crate) const MAX_SKILL_ZIP_BYTES: u64 = 20 * 1024 * 1024;
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
use crate::error::{CodexxError, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use toml_edit::{value, DocumentMut};
|
||||
|
||||
const CONTEXT_WINDOW: &str = "model_context_window";
|
||||
const COMPACT_TOKEN_LIMIT: &str = "model_auto_compact_token_limit";
|
||||
const ONE_MILLION: i64 = 1_000_000;
|
||||
const DEFAULT_COMPACT_LIMIT: i64 = 900_000;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct ContextWindowValues {
|
||||
pub(crate) context_window: Option<i64>,
|
||||
pub(crate) compact_token_limit: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct ContextWindowConfig {
|
||||
pub(crate) config_text: String,
|
||||
pub(crate) enabled: bool,
|
||||
#[serde(flatten)]
|
||||
pub(crate) values: ContextWindowValues,
|
||||
}
|
||||
|
||||
fn read_integer(doc: &DocumentMut, key: &str) -> Result<Option<i64>> {
|
||||
doc.get(key)
|
||||
.map(|item| {
|
||||
item.as_integer()
|
||||
.ok_or_else(|| CodexxError::Config(format!("{key} 必须为整数")))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn write_integer(doc: &mut DocumentMut, key: &str, number: i64) {
|
||||
// Keep existing inline comments and spacing when replacing a setting.
|
||||
let decor = doc
|
||||
.get(key)
|
||||
.and_then(|item| item.as_value())
|
||||
.map(|value| value.decor().clone());
|
||||
doc[key] = value(number);
|
||||
if let Some(decor) = decor {
|
||||
*doc[key].as_value_mut().expect("integer value").decor_mut() = decor;
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_integer(doc: &mut DocumentMut, key: &str, number: Option<i64>) {
|
||||
if let Some(number) = number {
|
||||
write_integer(doc, key, number);
|
||||
} else {
|
||||
doc.as_table_mut().remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Edits a supplied draft only; this never reads or writes the live configuration.
|
||||
/// `enabled = None` parses the checkbox state after a manual TOML edit.
|
||||
pub(crate) fn update_codex_context_window_inner(
|
||||
config_text: String,
|
||||
enabled: Option<bool>,
|
||||
previous_values: Option<ContextWindowValues>,
|
||||
) -> Result<ContextWindowConfig> {
|
||||
let mut doc = config_text
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|error| CodexxError::Toml {
|
||||
path: "config.toml".to_string(),
|
||||
message: error.to_string(),
|
||||
})?;
|
||||
let context_window = read_integer(&doc, CONTEXT_WINDOW)?;
|
||||
let compact_token_limit = read_integer(&doc, COMPACT_TOKEN_LIMIT)?;
|
||||
|
||||
match enabled {
|
||||
Some(true) => {
|
||||
write_integer(&mut doc, CONTEXT_WINDOW, ONE_MILLION);
|
||||
if compact_token_limit.is_none() {
|
||||
write_integer(&mut doc, COMPACT_TOKEN_LIMIT, DEFAULT_COMPACT_LIMIT);
|
||||
}
|
||||
}
|
||||
Some(false) => {
|
||||
// Only undo the 1M preset. A manual edit to either value wins.
|
||||
if context_window == Some(ONE_MILLION) {
|
||||
restore_integer(
|
||||
&mut doc,
|
||||
CONTEXT_WINDOW,
|
||||
previous_values
|
||||
.as_ref()
|
||||
.and_then(|values| values.context_window),
|
||||
);
|
||||
}
|
||||
let expected_compact_limit = previous_values
|
||||
.as_ref()
|
||||
.and_then(|values| values.compact_token_limit)
|
||||
.unwrap_or(DEFAULT_COMPACT_LIMIT);
|
||||
if compact_token_limit == Some(expected_compact_limit) {
|
||||
restore_integer(
|
||||
&mut doc,
|
||||
COMPACT_TOKEN_LIMIT,
|
||||
previous_values
|
||||
.as_ref()
|
||||
.and_then(|values| values.compact_token_limit),
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
let context_window = read_integer(&doc, CONTEXT_WINDOW)?;
|
||||
let compact_token_limit = read_integer(&doc, COMPACT_TOKEN_LIMIT)?;
|
||||
Ok(ContextWindowConfig {
|
||||
config_text: if enabled.is_none() {
|
||||
config_text
|
||||
} else {
|
||||
doc.to_string()
|
||||
},
|
||||
enabled: context_window == Some(ONE_MILLION),
|
||||
values: ContextWindowValues {
|
||||
context_window,
|
||||
compact_token_limit,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn enables_at_top_level_and_preserves_unrelated_tables_and_comments() {
|
||||
let original = "# My Codex settings\nmodel = \"gpt-5.5\" # keep model\n\n[mcp_servers.notes]\ncommand = \"notes\"\nmodel_context_window = 120000\n\n[model_providers.custom]\nbase_url = \"https://api.example.test/v1\"\n";
|
||||
let result = update_codex_context_window_inner(original.into(), Some(true), None).unwrap();
|
||||
let doc = result.config_text.parse::<DocumentMut>().unwrap();
|
||||
assert_eq!(doc[CONTEXT_WINDOW].as_integer(), Some(ONE_MILLION));
|
||||
assert_eq!(
|
||||
doc[COMPACT_TOKEN_LIMIT].as_integer(),
|
||||
Some(DEFAULT_COMPACT_LIMIT)
|
||||
);
|
||||
assert_eq!(
|
||||
doc["mcp_servers"]["notes"][CONTEXT_WINDOW].as_integer(),
|
||||
Some(120000)
|
||||
);
|
||||
assert!(result.config_text.contains("# My Codex settings"));
|
||||
assert!(result
|
||||
.config_text
|
||||
.contains("model = \"gpt-5.5\" # keep model"));
|
||||
assert!(result
|
||||
.config_text
|
||||
.contains("base_url = \"https://api.example.test/v1\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_underscores_and_quoted_keys_without_reformatting_the_draft() {
|
||||
let original = "\"model_context_window\" = 1_000_000 # large\nmodel_auto_compact_token_limit = 850_000\n";
|
||||
let result = update_codex_context_window_inner(original.into(), None, None).unwrap();
|
||||
assert!(result.enabled);
|
||||
assert_eq!(result.values.compact_token_limit, Some(850000));
|
||||
assert_eq!(result.config_text, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_context_values_in_tables_or_multiline_strings() {
|
||||
let original = "instructions = '''\nmodel_context_window = 1000000\n'''\n[profiles.large]\nmodel_context_window = 1000000\n";
|
||||
let result = update_codex_context_window_inner(original.into(), None, None).unwrap();
|
||||
assert!(!result.enabled);
|
||||
assert_eq!(result.values.context_window, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_custom_compaction_when_enabling_and_disabling() {
|
||||
let original = "model_auto_compact_token_limit = 850000 # custom\n";
|
||||
let enabled = update_codex_context_window_inner(original.into(), Some(true), None).unwrap();
|
||||
assert_eq!(enabled.values.compact_token_limit, Some(850000));
|
||||
let disabled =
|
||||
update_codex_context_window_inner(enabled.config_text, Some(false), None).unwrap();
|
||||
assert_eq!(disabled.values.context_window, None);
|
||||
assert_eq!(disabled.config_text, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restores_custom_context_and_existing_default_compaction_in_same_edit() {
|
||||
let original = "model_context_window = 256000 # original\nmodel_auto_compact_token_limit = 900000 # intentional\n";
|
||||
let parsed = update_codex_context_window_inner(original.into(), None, None).unwrap();
|
||||
let enabled = update_codex_context_window_inner(original.into(), Some(true), None).unwrap();
|
||||
let disabled = update_codex_context_window_inner(
|
||||
enabled.config_text,
|
||||
Some(false),
|
||||
Some(parsed.values),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(disabled.config_text, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_a_saved_preset_removes_both_default_values() {
|
||||
let original = "model = \"gpt-5.5\"\n";
|
||||
let enabled = update_codex_context_window_inner(original.into(), Some(true), None).unwrap();
|
||||
let disabled =
|
||||
update_codex_context_window_inner(enabled.config_text, Some(false), None).unwrap();
|
||||
assert_eq!(disabled.config_text, original);
|
||||
assert!(!disabled.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_does_not_undo_new_manual_values() {
|
||||
let manual = "model_context_window = 500000\nmodel_auto_compact_token_limit = 420000\n";
|
||||
let result = update_codex_context_window_inner(
|
||||
manual.into(),
|
||||
Some(false),
|
||||
Some(ContextWindowValues {
|
||||
context_window: Some(256000),
|
||||
compact_token_limit: Some(200000),
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.config_text, manual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_toml_and_invalid_top_level_field_types() {
|
||||
for original in [
|
||||
"[unfinished",
|
||||
"model_context_window = '1000000'",
|
||||
"model_auto_compact_token_limit = 'automatic'",
|
||||
] {
|
||||
assert!(update_codex_context_window_inner(original.into(), Some(true), None).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_draft_can_be_enabled_and_returned_to_blank() {
|
||||
let enabled = update_codex_context_window_inner(String::new(), Some(true), None).unwrap();
|
||||
assert!(enabled.enabled);
|
||||
let disabled =
|
||||
update_codex_context_window_inner(enabled.config_text, Some(false), None).unwrap();
|
||||
assert!(disabled.config_text.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
use tauri::{
|
||||
menu::{Menu, MenuItem},
|
||||
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
|
||||
Emitter, Manager, WindowEvent,
|
||||
};
|
||||
|
||||
const MAIN_WINDOW_LABEL: &str = "main";
|
||||
const TRAY_ID: &str = "codex-x-tray";
|
||||
const SHOW_WINDOW_MENU_ID: &str = "show-main-window";
|
||||
const QUIT_APP_MENU_ID: &str = "quit-codex-x";
|
||||
const SHOW_TRAY_MENU_ON_LEFT_CLICK: bool = cfg!(target_os = "macos");
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn set_macos_tray_mode(app: &tauri::AppHandle, dock_visible: bool) -> tauri::Result<()> {
|
||||
let policy = if dock_visible {
|
||||
tauri::ActivationPolicy::Regular
|
||||
} else {
|
||||
tauri::ActivationPolicy::Accessory
|
||||
};
|
||||
|
||||
// Attempt both operations: either one alone can leave a stale Dock entry on some macOS versions.
|
||||
let dock_result = app.set_dock_visibility(dock_visible);
|
||||
let policy_result = app.set_activation_policy(policy);
|
||||
dock_result?;
|
||||
policy_result
|
||||
}
|
||||
|
||||
fn retain_first_error(first_error: &mut Option<tauri::Error>, result: tauri::Result<()>) {
|
||||
if let Err(error) = result {
|
||||
if first_error.is_none() {
|
||||
*first_error = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn show_main_window(app: &tauri::AppHandle) -> tauri::Result<()> {
|
||||
let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let mut first_error = None;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
retain_first_error(&mut first_error, window.set_skip_taskbar(false));
|
||||
#[cfg(target_os = "macos")]
|
||||
retain_first_error(&mut first_error, app.show());
|
||||
|
||||
retain_first_error(&mut first_error, window.unminimize());
|
||||
retain_first_error(&mut first_error, window.show());
|
||||
retain_first_error(&mut first_error, window.set_focus());
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
retain_first_error(&mut first_error, set_macos_tray_mode(app, true));
|
||||
|
||||
first_error.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
pub(crate) fn restore_main_window(app: &tauri::AppHandle) {
|
||||
if let Err(error) = show_main_window(app) {
|
||||
eprintln!("failed to restore the Codex-X window: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn setup_system_tray(app: &tauri::App) -> tauri::Result<()> {
|
||||
let show_window =
|
||||
MenuItem::with_id(app, SHOW_WINDOW_MENU_ID, "显示 Codex-X", true, None::<&str>)?;
|
||||
let quit_app = MenuItem::with_id(app, QUIT_APP_MENU_ID, "退出 Codex-X", true, None::<&str>)?;
|
||||
let menu = Menu::with_items(app, &[&show_window, &quit_app])?;
|
||||
|
||||
let mut tray = TrayIconBuilder::with_id(TRAY_ID)
|
||||
.menu(&menu)
|
||||
.tooltip("Codex-X")
|
||||
.show_menu_on_left_click(SHOW_TRAY_MENU_ON_LEFT_CLICK)
|
||||
.on_menu_event(|app, event| match event.id().as_ref() {
|
||||
SHOW_WINDOW_MENU_ID => restore_main_window(app),
|
||||
QUIT_APP_MENU_ID => app.exit(0),
|
||||
_ => {}
|
||||
})
|
||||
.on_tray_icon_event(|tray, event| {
|
||||
if !SHOW_TRAY_MENU_ON_LEFT_CLICK
|
||||
&& matches!(
|
||||
event,
|
||||
TrayIconEvent::Click {
|
||||
button: MouseButton::Left,
|
||||
button_state: MouseButtonState::Up,
|
||||
..
|
||||
}
|
||||
)
|
||||
{
|
||||
restore_main_window(tray.app_handle());
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(icon) = app.default_window_icon().cloned() {
|
||||
tray = tray.icon(icon);
|
||||
}
|
||||
|
||||
tray.build(app)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn handle_window_event(window: &tauri::Window, event: &WindowEvent) {
|
||||
if window.label() != MAIN_WINDOW_LABEL {
|
||||
return;
|
||||
}
|
||||
|
||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||
api.prevent_close();
|
||||
if let Err(error) = window.hide() {
|
||||
eprintln!("failed to hide the Codex-X window: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
if let Err(error) = window.set_skip_taskbar(true) {
|
||||
eprintln!("failed to remove Codex-X from the taskbar: {error}");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Err(error) = set_macos_tray_mode(window.app_handle(), false) {
|
||||
eprintln!("failed to move Codex-X to the menu bar: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn report_failover_lifecycle_error(app: &tauri::AppHandle, title: &str, reason: &str) {
|
||||
let title = title.to_string();
|
||||
let reason = reason.to_string();
|
||||
eprintln!("{title}: {reason}");
|
||||
let _ = app.emit("provider-failover-error", &reason);
|
||||
tauri::async_runtime::spawn(async move {
|
||||
rfd::AsyncMessageDialog::new()
|
||||
.set_title(title)
|
||||
.set_description(reason)
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show()
|
||||
.await;
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn handle_run_event(app: &tauri::AppHandle, event: tauri::RunEvent) {
|
||||
if let tauri::RunEvent::ExitRequested { api, .. } = &event {
|
||||
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.
|
||||
api.prevent_exit();
|
||||
restore_main_window(app);
|
||||
report_failover_lifecycle_error(
|
||||
app,
|
||||
"暂时无法退出 Codex-X",
|
||||
&format!("自动切换的连接配置还未恢复,Codex-X 将继续运行。\n\n{error}\n\n请检查配置文件是否被占用,再重试退出。"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
if let tauri::RunEvent::Reopen { .. } = event {
|
||||
restore_main_window(app);
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = (app, event);
|
||||
}
|
||||
@@ -0,0 +1,638 @@
|
||||
// Adapted from CC Switch 06082e189d65e6d6dbadc35dacdac1ce6c79d89a,
|
||||
// src-tauri/src/proxy/circuit_breaker.rs. The state transitions and counters
|
||||
// retain the upstream behavior; locks are synchronous and logs are omitted.
|
||||
//
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2025 Jason Young
|
||||
//
|
||||
// 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.
|
||||
|
||||
//! 熔断器模块
|
||||
//!
|
||||
//! 实现熔断器模式,用于防止向不健康的供应商发送请求
|
||||
|
||||
use super::config::RoutingTuning;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
// The upstream state machine is retained; Codex-X forwards on bounded blocking
|
||||
// workers, so its short state locks use std rather than awaiting Tokio locks.
|
||||
struct RwLock<T>(std::sync::RwLock<T>);
|
||||
impl<T> RwLock<T> {
|
||||
fn new(value: T) -> Self {
|
||||
Self(std::sync::RwLock::new(value))
|
||||
}
|
||||
fn read(&self) -> std::sync::RwLockReadGuard<'_, T> {
|
||||
self.0.read().unwrap_or_else(|error| error.into_inner())
|
||||
}
|
||||
fn write(&self) -> std::sync::RwLockWriteGuard<'_, T> {
|
||||
self.0.write().unwrap_or_else(|error| error.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
/// 熔断器状态
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CircuitState {
|
||||
/// 关闭状态 - 正常工作
|
||||
Closed,
|
||||
/// 打开状态 - 熔断激活,拒绝请求
|
||||
Open,
|
||||
/// 半开状态 - 尝试恢复,允许部分请求通过
|
||||
HalfOpen,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CircuitState {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
CircuitState::Closed => write!(f, "closed"),
|
||||
CircuitState::Open => write!(f, "open"),
|
||||
CircuitState::HalfOpen => write!(f, "half_open"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 熔断器配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CircuitBreakerConfig {
|
||||
/// 失败阈值 - 连续失败多少次后打开熔断器
|
||||
pub failure_threshold: u32,
|
||||
/// 成功阈值 - 半开状态下成功多少次后关闭熔断器
|
||||
pub success_threshold: u32,
|
||||
/// 超时时间 - 熔断器打开后多久尝试半开(秒)
|
||||
pub timeout_seconds: u64,
|
||||
/// 错误率阈值 - 错误率超过此值时打开熔断器 (0.0-1.0)
|
||||
pub error_rate_threshold: f64,
|
||||
/// 最小请求数 - 计算错误率前的最小请求数
|
||||
pub min_requests: u32,
|
||||
}
|
||||
|
||||
impl From<&RoutingTuning> for CircuitBreakerConfig {
|
||||
fn from(config: &RoutingTuning) -> Self {
|
||||
Self {
|
||||
failure_threshold: config.circuit_failure_threshold,
|
||||
success_threshold: config.circuit_success_threshold,
|
||||
timeout_seconds: config.circuit_timeout_seconds as u64,
|
||||
error_rate_threshold: config.circuit_error_rate_threshold,
|
||||
min_requests: config.circuit_min_requests,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CircuitBreakerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
failure_threshold: 4,
|
||||
success_threshold: 2,
|
||||
timeout_seconds: 60,
|
||||
error_rate_threshold: 0.6,
|
||||
min_requests: 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 熔断器实例
|
||||
pub struct CircuitBreaker {
|
||||
/// 当前状态
|
||||
state: Arc<RwLock<CircuitState>>,
|
||||
/// 连续失败计数
|
||||
consecutive_failures: Arc<AtomicU32>,
|
||||
/// 连续成功计数(半开状态)
|
||||
consecutive_successes: Arc<AtomicU32>,
|
||||
/// 总请求计数
|
||||
total_requests: Arc<AtomicU32>,
|
||||
/// 失败请求计数
|
||||
failed_requests: Arc<AtomicU32>,
|
||||
/// 上次打开时间
|
||||
last_opened_at: Arc<RwLock<Option<Instant>>>,
|
||||
/// 配置(支持热更新)
|
||||
config: Arc<RwLock<CircuitBreakerConfig>>,
|
||||
/// 半开状态已放行的请求数(用于限流)
|
||||
half_open_requests: Arc<AtomicU32>,
|
||||
}
|
||||
|
||||
/// 熔断器放行结果
|
||||
///
|
||||
/// `used_half_open_permit` 表示本次放行是否占用了 HalfOpen 探测名额。
|
||||
/// 调用方应在请求结束后把该值传回 `record_success` / `record_failure` 用于正确释放名额。
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct AllowResult {
|
||||
pub allowed: bool,
|
||||
pub used_half_open_permit: bool,
|
||||
}
|
||||
|
||||
impl CircuitBreaker {
|
||||
/// 创建新的熔断器
|
||||
pub fn new(config: CircuitBreakerConfig) -> Self {
|
||||
Self {
|
||||
state: Arc::new(RwLock::new(CircuitState::Closed)),
|
||||
consecutive_failures: Arc::new(AtomicU32::new(0)),
|
||||
consecutive_successes: Arc::new(AtomicU32::new(0)),
|
||||
total_requests: Arc::new(AtomicU32::new(0)),
|
||||
failed_requests: Arc::new(AtomicU32::new(0)),
|
||||
last_opened_at: Arc::new(RwLock::new(None)),
|
||||
config: Arc::new(RwLock::new(config)),
|
||||
half_open_requests: Arc::new(AtomicU32::new(0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新熔断器配置(热更新,不重置状态)
|
||||
pub fn update_config(&self, new_config: CircuitBreakerConfig) {
|
||||
*self.config.write() = new_config;
|
||||
}
|
||||
|
||||
/// 判断当前 Provider 是否“可被纳入候选链路”
|
||||
///
|
||||
/// 这个方法不会占用 HalfOpen 探测名额,仅用于路由选择阶段的“可用性判断”:
|
||||
/// - Closed / HalfOpen:可用(返回 true)
|
||||
/// - Open:若超时到达则切到 HalfOpen 并返回 true,否则返回 false
|
||||
///
|
||||
/// 注意:真正发起请求前仍需调用 `allow_request()` 来获取 HalfOpen 探测名额,
|
||||
/// 并在请求结束后通过 `record_success()` / `record_failure()` 释放。
|
||||
pub fn is_available(&self) -> bool {
|
||||
let state = *self.state.read();
|
||||
let config = self.config.read();
|
||||
|
||||
match state {
|
||||
CircuitState::Closed | CircuitState::HalfOpen => true,
|
||||
CircuitState::Open => {
|
||||
if let Some(opened_at) = *self.last_opened_at.read() {
|
||||
if opened_at.elapsed().as_secs() >= config.timeout_seconds {
|
||||
drop(config); // 释放读锁再转换状态
|
||||
self.transition_to_half_open();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查是否允许请求通过
|
||||
pub fn allow_request(&self) -> AllowResult {
|
||||
let state = *self.state.read();
|
||||
|
||||
match state {
|
||||
CircuitState::Closed => AllowResult {
|
||||
allowed: true,
|
||||
used_half_open_permit: false,
|
||||
},
|
||||
CircuitState::Open => {
|
||||
let config = self.config.read();
|
||||
// 检查是否应该尝试半开
|
||||
if let Some(opened_at) = *self.last_opened_at.read() {
|
||||
if opened_at.elapsed().as_secs() >= config.timeout_seconds {
|
||||
drop(config); // 释放读锁再转换状态
|
||||
self.transition_to_half_open();
|
||||
|
||||
// 转换后按当前状态决定是否需要获取 HalfOpen 探测名额
|
||||
let current_state = *self.state.read();
|
||||
return match current_state {
|
||||
CircuitState::Closed => AllowResult {
|
||||
allowed: true,
|
||||
used_half_open_permit: false,
|
||||
},
|
||||
CircuitState::HalfOpen => self.allow_half_open_probe(),
|
||||
CircuitState::Open => AllowResult {
|
||||
allowed: false,
|
||||
used_half_open_permit: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
AllowResult {
|
||||
allowed: false,
|
||||
used_half_open_permit: false,
|
||||
}
|
||||
}
|
||||
CircuitState::HalfOpen => self.allow_half_open_probe(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 记录成功
|
||||
pub fn record_success(&self, used_half_open_permit: bool) {
|
||||
let state = *self.state.read();
|
||||
let config = self.config.read();
|
||||
|
||||
if used_half_open_permit {
|
||||
self.release_half_open_permit();
|
||||
}
|
||||
|
||||
// 重置失败计数
|
||||
self.consecutive_failures.store(0, Ordering::SeqCst);
|
||||
self.total_requests.fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
if state == CircuitState::HalfOpen {
|
||||
let successes = self.consecutive_successes.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
|
||||
if successes >= config.success_threshold {
|
||||
drop(config); // 释放读锁再转换状态
|
||||
self.transition_to_closed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 记录失败
|
||||
pub fn record_failure(&self, used_half_open_permit: bool) {
|
||||
let state = *self.state.read();
|
||||
let config = self.config.read();
|
||||
|
||||
if used_half_open_permit {
|
||||
self.release_half_open_permit();
|
||||
}
|
||||
|
||||
// 更新计数器
|
||||
let failures = self.consecutive_failures.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
self.total_requests.fetch_add(1, Ordering::SeqCst);
|
||||
self.failed_requests.fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
// 重置成功计数
|
||||
self.consecutive_successes.store(0, Ordering::SeqCst);
|
||||
|
||||
// 检查是否应该打开熔断器
|
||||
match state {
|
||||
CircuitState::HalfOpen => {
|
||||
// HalfOpen 状态下失败,立即转为 Open
|
||||
drop(config);
|
||||
self.transition_to_open();
|
||||
}
|
||||
CircuitState::Closed => {
|
||||
// 检查连续失败次数
|
||||
if failures >= config.failure_threshold {
|
||||
drop(config); // 释放读锁再转换状态
|
||||
self.transition_to_open();
|
||||
} else {
|
||||
// 检查错误率
|
||||
let total = self.total_requests.load(Ordering::SeqCst);
|
||||
let failed = self.failed_requests.load(Ordering::SeqCst);
|
||||
|
||||
if total >= config.min_requests {
|
||||
let error_rate = failed as f64 / total as f64;
|
||||
|
||||
if error_rate >= config.error_rate_threshold {
|
||||
drop(config); // 释放读锁再转换状态
|
||||
self.transition_to_open();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取当前状态
|
||||
#[allow(dead_code)]
|
||||
pub fn get_state(&self) -> CircuitState {
|
||||
*self.state.read()
|
||||
}
|
||||
|
||||
/// 获取统计信息
|
||||
#[allow(dead_code)]
|
||||
pub fn get_stats(&self) -> CircuitBreakerStats {
|
||||
CircuitBreakerStats {
|
||||
state: *self.state.read(),
|
||||
consecutive_failures: self.consecutive_failures.load(Ordering::SeqCst),
|
||||
consecutive_successes: self.consecutive_successes.load(Ordering::SeqCst),
|
||||
total_requests: self.total_requests.load(Ordering::SeqCst),
|
||||
failed_requests: self.failed_requests.load(Ordering::SeqCst),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cooldown_seconds(&self) -> u64 {
|
||||
if *self.state.read() != CircuitState::Open {
|
||||
return 0;
|
||||
}
|
||||
let config = self.config.read();
|
||||
self.last_opened_at.read().as_ref().map_or(0, |opened| {
|
||||
config
|
||||
.timeout_seconds
|
||||
.saturating_sub(opened.elapsed().as_secs())
|
||||
})
|
||||
}
|
||||
|
||||
/// 重置熔断器(手动恢复)
|
||||
#[allow(dead_code)]
|
||||
pub fn reset(&self) {
|
||||
self.transition_to_closed();
|
||||
}
|
||||
|
||||
fn allow_half_open_probe(&self) -> AllowResult {
|
||||
// 半开状态限流:只允许有限请求通过进行探测
|
||||
let max_half_open_requests = 1u32;
|
||||
let current = self.half_open_requests.fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
if current < max_half_open_requests {
|
||||
AllowResult {
|
||||
allowed: true,
|
||||
used_half_open_permit: true,
|
||||
}
|
||||
} else {
|
||||
// 超过限额,回退计数,拒绝请求
|
||||
self.half_open_requests.fetch_sub(1, Ordering::SeqCst);
|
||||
AllowResult {
|
||||
allowed: false,
|
||||
used_half_open_permit: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 仅释放 HalfOpen permit,不影响健康统计
|
||||
///
|
||||
/// 用于整流器等场景:请求结果不应计入 Provider 健康度,
|
||||
/// 但仍需释放占用的探测名额,避免 HalfOpen 状态卡死
|
||||
pub fn release_half_open_permit(&self) {
|
||||
let mut current = self.half_open_requests.load(Ordering::SeqCst);
|
||||
loop {
|
||||
if current == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
match self.half_open_requests.compare_exchange(
|
||||
current,
|
||||
current - 1,
|
||||
Ordering::SeqCst,
|
||||
Ordering::SeqCst,
|
||||
) {
|
||||
Ok(_) => return,
|
||||
Err(actual) => current = actual,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 转换到打开状态
|
||||
fn transition_to_open(&self) {
|
||||
*self.state.write() = CircuitState::Open;
|
||||
*self.last_opened_at.write() = Some(Instant::now());
|
||||
self.consecutive_failures.store(0, Ordering::SeqCst);
|
||||
self.consecutive_successes.store(0, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// 转换到半开状态
|
||||
fn transition_to_half_open(&self) {
|
||||
let mut state = self.state.write();
|
||||
if *state != CircuitState::Open {
|
||||
return;
|
||||
}
|
||||
|
||||
*state = CircuitState::HalfOpen;
|
||||
self.consecutive_successes.store(0, Ordering::SeqCst);
|
||||
// 重置半开状态的请求限流计数
|
||||
self.half_open_requests.store(0, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// 转换到关闭状态
|
||||
fn transition_to_closed(&self) {
|
||||
*self.state.write() = CircuitState::Closed;
|
||||
self.consecutive_failures.store(0, Ordering::SeqCst);
|
||||
self.consecutive_successes.store(0, Ordering::SeqCst);
|
||||
// 重置计数器
|
||||
self.total_requests.store(0, Ordering::SeqCst);
|
||||
self.failed_requests.store(0, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// 熔断器统计信息
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CircuitBreakerStats {
|
||||
pub state: CircuitState,
|
||||
pub consecutive_failures: u32,
|
||||
pub consecutive_successes: u32,
|
||||
pub total_requests: u32,
|
||||
pub failed_requests: u32,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_circuit_breaker_closed_to_open() {
|
||||
let config = CircuitBreakerConfig {
|
||||
failure_threshold: 3,
|
||||
..Default::default()
|
||||
};
|
||||
let breaker = CircuitBreaker::new(config);
|
||||
|
||||
// 初始状态应该是关闭
|
||||
assert_eq!(breaker.get_state(), CircuitState::Closed);
|
||||
assert!(breaker.allow_request().allowed);
|
||||
|
||||
// 记录 3 次失败
|
||||
for _ in 0..3 {
|
||||
breaker.record_failure(false);
|
||||
}
|
||||
|
||||
// 应该转换到打开状态
|
||||
assert_eq!(breaker.get_state(), CircuitState::Open);
|
||||
assert!(!breaker.allow_request().allowed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_circuit_breaker_half_open_to_closed() {
|
||||
let config = CircuitBreakerConfig {
|
||||
failure_threshold: 2,
|
||||
success_threshold: 2,
|
||||
..Default::default()
|
||||
};
|
||||
let breaker = CircuitBreaker::new(config);
|
||||
|
||||
// 打开熔断器
|
||||
breaker.record_failure(false);
|
||||
breaker.record_failure(false);
|
||||
assert_eq!(breaker.get_state(), CircuitState::Open);
|
||||
|
||||
// 手动转换到半开状态
|
||||
breaker.transition_to_half_open();
|
||||
assert_eq!(breaker.get_state(), CircuitState::HalfOpen);
|
||||
|
||||
// 记录 2 次成功
|
||||
breaker.record_success(false);
|
||||
breaker.record_success(false);
|
||||
|
||||
// 应该转换到关闭状态
|
||||
assert_eq!(breaker.get_state(), CircuitState::Closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_half_open_transition_does_not_reset_inflight_permit() {
|
||||
let config = CircuitBreakerConfig {
|
||||
timeout_seconds: 0,
|
||||
..Default::default()
|
||||
};
|
||||
let breaker = CircuitBreaker::new(config);
|
||||
|
||||
// 进入 Open,然后由于 timeout_seconds=0,allow_request 会立即切换到 HalfOpen 并占用探测名额
|
||||
breaker.transition_to_open();
|
||||
let first = breaker.allow_request();
|
||||
assert!(first.allowed);
|
||||
assert!(first.used_half_open_permit);
|
||||
assert_eq!(breaker.get_state(), CircuitState::HalfOpen);
|
||||
|
||||
// 模拟并发下的“重复 HalfOpen 转换调用”,不应重置 in-flight 计数
|
||||
breaker.transition_to_half_open();
|
||||
|
||||
// 由于名额仍被占用,第二次请求应被拒绝
|
||||
let second = breaker.allow_request();
|
||||
assert!(!second.allowed);
|
||||
assert!(!second.used_half_open_permit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_circuit_breaker_reset() {
|
||||
let config = CircuitBreakerConfig {
|
||||
failure_threshold: 2,
|
||||
..Default::default()
|
||||
};
|
||||
let breaker = CircuitBreaker::new(config);
|
||||
|
||||
// 打开熔断器
|
||||
breaker.record_failure(false);
|
||||
breaker.record_failure(false);
|
||||
assert_eq!(breaker.get_state(), CircuitState::Open);
|
||||
|
||||
// 重置
|
||||
breaker.reset();
|
||||
assert_eq!(breaker.get_state(), CircuitState::Closed);
|
||||
assert!(breaker.allow_request().allowed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_rate_waits_for_minimum_requests_and_uses_inclusive_threshold() {
|
||||
let config = CircuitBreakerConfig {
|
||||
failure_threshold: 20,
|
||||
min_requests: 5,
|
||||
error_rate_threshold: 0.6,
|
||||
..Default::default()
|
||||
};
|
||||
let breaker = CircuitBreaker::new(config.clone());
|
||||
breaker.record_failure(false);
|
||||
breaker.record_success(false);
|
||||
breaker.record_failure(false);
|
||||
breaker.record_success(false);
|
||||
assert_eq!(breaker.get_stats().total_requests, 4);
|
||||
assert_eq!(breaker.get_state(), CircuitState::Closed);
|
||||
breaker.record_failure(false);
|
||||
assert_eq!(breaker.get_state(), CircuitState::Open);
|
||||
let higher = CircuitBreaker::new(CircuitBreakerConfig {
|
||||
error_rate_threshold: 0.8,
|
||||
..config.clone()
|
||||
});
|
||||
let minimum = CircuitBreaker::new(CircuitBreakerConfig {
|
||||
min_requests: 10,
|
||||
..config
|
||||
});
|
||||
for breaker in [&higher, &minimum] {
|
||||
breaker.record_failure(false);
|
||||
breaker.record_success(false);
|
||||
breaker.record_failure(false);
|
||||
breaker.record_success(false);
|
||||
breaker.record_failure(false);
|
||||
assert_eq!(breaker.get_state(), CircuitState::Closed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successes_break_consecutive_failures_without_clearing_error_rate_history() {
|
||||
let breaker = CircuitBreaker::new(CircuitBreakerConfig {
|
||||
failure_threshold: 2,
|
||||
min_requests: 100,
|
||||
..Default::default()
|
||||
});
|
||||
breaker.record_failure(false);
|
||||
breaker.record_success(false);
|
||||
breaker.record_failure(false);
|
||||
assert_eq!(breaker.get_state(), CircuitState::Closed);
|
||||
assert_eq!(breaker.get_stats().failed_requests, 2);
|
||||
assert_eq!(breaker.get_stats().consecutive_failures, 1);
|
||||
breaker.record_failure(false);
|
||||
assert_eq!(breaker.get_state(), CircuitState::Open);
|
||||
assert_eq!(breaker.get_stats().total_requests, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_wait_and_hot_configuration_preserve_existing_evidence() {
|
||||
let mut config = CircuitBreakerConfig {
|
||||
failure_threshold: 1,
|
||||
timeout_seconds: 2,
|
||||
..Default::default()
|
||||
};
|
||||
let breaker = CircuitBreaker::new(config.clone());
|
||||
breaker.record_failure(false);
|
||||
*breaker.last_opened_at.write() = Some(Instant::now() - std::time::Duration::from_secs(1));
|
||||
assert!(!breaker.allow_request().allowed);
|
||||
assert_eq!(breaker.cooldown_seconds(), 1);
|
||||
config.timeout_seconds = 1;
|
||||
breaker.update_config(config);
|
||||
assert_eq!(breaker.get_stats().failed_requests, 1);
|
||||
let probe = breaker.allow_request();
|
||||
assert!(probe.allowed && probe.used_half_open_permit);
|
||||
assert_eq!(breaker.get_state(), CircuitState::HalfOpen);
|
||||
assert!(!breaker.allow_request().allowed);
|
||||
breaker.release_half_open_permit();
|
||||
let probe = breaker.allow_request();
|
||||
assert!(probe.allowed);
|
||||
breaker.record_failure(probe.used_half_open_permit);
|
||||
assert_eq!(breaker.get_state(), CircuitState::Open);
|
||||
assert!(!breaker.allow_request().allowed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_open_requires_configured_successes_and_reset_clears_all_statistics() {
|
||||
let breaker = CircuitBreaker::new(CircuitBreakerConfig {
|
||||
failure_threshold: 1,
|
||||
success_threshold: 3,
|
||||
timeout_seconds: 0,
|
||||
..Default::default()
|
||||
});
|
||||
breaker.record_failure(false);
|
||||
for completed in 0..3 {
|
||||
let probe = breaker.allow_request();
|
||||
assert!(probe.allowed && probe.used_half_open_permit);
|
||||
assert!(!breaker.allow_request().allowed);
|
||||
breaker.record_success(probe.used_half_open_permit);
|
||||
assert_eq!(
|
||||
breaker.get_state(),
|
||||
if completed < 2 {
|
||||
CircuitState::HalfOpen
|
||||
} else {
|
||||
CircuitState::Closed
|
||||
}
|
||||
);
|
||||
}
|
||||
assert_eq!(breaker.get_stats().total_requests, 0);
|
||||
breaker.record_failure(false);
|
||||
breaker.reset();
|
||||
let stats = breaker.get_stats();
|
||||
assert_eq!(
|
||||
(
|
||||
stats.total_requests,
|
||||
stats.failed_requests,
|
||||
stats.consecutive_failures,
|
||||
stats.consecutive_successes
|
||||
),
|
||||
(0, 0, 0, 0)
|
||||
);
|
||||
assert!(breaker.allow_request().allowed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Codex defaults/ranges follow CC Switch 06082e1 AppProxyConfig and its
|
||||
//! AutoFailoverConfigPanel. Both IPC and the UI validate these settings.
|
||||
|
||||
use crate::error::{CodexxError, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
pub(crate) const DEFAULT_LISTEN_ADDRESS: &str = "127.0.0.1";
|
||||
pub(crate) const DEFAULT_LISTEN_PORT: u16 = 15721;
|
||||
pub(crate) const MAX_QUEUE: usize = 64;
|
||||
pub(crate) const ROUTE_TOKEN_HEADER: &str = "x-codex-x-route-token";
|
||||
pub(crate) const ROUTE_GENERATION_HEADER: &str = "x-codex-x-route-generation";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub(crate) struct RoutingTuning {
|
||||
pub(crate) max_retries: u32,
|
||||
pub(crate) streaming_first_byte_timeout: u64,
|
||||
pub(crate) streaming_idle_timeout: u64,
|
||||
pub(crate) non_streaming_timeout: u64,
|
||||
pub(crate) circuit_failure_threshold: u32,
|
||||
pub(crate) circuit_success_threshold: u32,
|
||||
pub(crate) circuit_timeout_seconds: u64,
|
||||
pub(crate) circuit_error_rate_threshold: f64,
|
||||
pub(crate) circuit_min_requests: u32,
|
||||
}
|
||||
|
||||
impl Default for RoutingTuning {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_retries: 3,
|
||||
streaming_first_byte_timeout: 60,
|
||||
streaming_idle_timeout: 120,
|
||||
non_streaming_timeout: 600,
|
||||
circuit_failure_threshold: 4,
|
||||
circuit_success_threshold: 2,
|
||||
circuit_timeout_seconds: 60,
|
||||
circuit_error_rate_threshold: 0.6,
|
||||
circuit_min_requests: 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RoutingTuning {
|
||||
pub(crate) fn validate(&self) -> Result<()> {
|
||||
for (valid, message) in [
|
||||
(self.max_retries <= 10, "最大重试次数须为 0–10"),
|
||||
(
|
||||
(1..=120).contains(&self.streaming_first_byte_timeout),
|
||||
"流式首字节超时须为 1–120 秒",
|
||||
),
|
||||
(
|
||||
self.streaming_idle_timeout <= 600,
|
||||
"流式静默超时须为 0–600 秒,0 表示禁用",
|
||||
),
|
||||
(
|
||||
(60..=1200).contains(&self.non_streaming_timeout),
|
||||
"非流式超时须为 60–1200 秒",
|
||||
),
|
||||
(
|
||||
(1..=20).contains(&self.circuit_failure_threshold),
|
||||
"失败阈值须为 1–20",
|
||||
),
|
||||
(
|
||||
(1..=10).contains(&self.circuit_success_threshold),
|
||||
"恢复成功阈值须为 1–10",
|
||||
),
|
||||
(
|
||||
self.circuit_timeout_seconds <= 300,
|
||||
"恢复等待时间须为 0–300 秒",
|
||||
),
|
||||
(
|
||||
self.circuit_error_rate_threshold.is_finite()
|
||||
&& (0.0..=1.0).contains(&self.circuit_error_rate_threshold),
|
||||
"错误率阈值须为 0–100%",
|
||||
),
|
||||
(
|
||||
(5..=100).contains(&self.circuit_min_requests),
|
||||
"最小请求数须为 5–100",
|
||||
),
|
||||
] {
|
||||
if !valid {
|
||||
return Err(CodexxError::Config(message.into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn listen_ip(address: &str) -> Result<IpAddr> {
|
||||
let address = address.trim();
|
||||
if address.eq_ignore_ascii_case("localhost") {
|
||||
return Ok(IpAddr::V4(Ipv4Addr::LOCALHOST));
|
||||
}
|
||||
let address = address
|
||||
.strip_prefix('[')
|
||||
.and_then(|value| value.strip_suffix(']'))
|
||||
.unwrap_or(address);
|
||||
address
|
||||
.parse()
|
||||
.map_err(|_| CodexxError::Config("监听地址须为 IPv4、IPv6 或 localhost".into()))
|
||||
}
|
||||
|
||||
pub(crate) fn client_ip(address: IpAddr) -> IpAddr {
|
||||
match address {
|
||||
IpAddr::V4(ip) if ip.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST),
|
||||
IpAddr::V6(ip) if ip.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST),
|
||||
address => address,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn local_url(address: IpAddr, port: u16) -> String {
|
||||
match client_ip(address) {
|
||||
IpAddr::V4(ip) => format!("http://{ip}:{port}/v1"),
|
||||
IpAddr::V6(ip) => format!("http://[{ip}]:{port}/v1"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn codex_defaults_and_valid_boundaries_match_reference() {
|
||||
let defaults = RoutingTuning::default();
|
||||
defaults.validate().unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
defaults.max_retries,
|
||||
defaults.streaming_first_byte_timeout,
|
||||
defaults.streaming_idle_timeout,
|
||||
defaults.non_streaming_timeout
|
||||
),
|
||||
(3, 60, 120, 600)
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
defaults.circuit_failure_threshold,
|
||||
defaults.circuit_success_threshold,
|
||||
defaults.circuit_timeout_seconds,
|
||||
defaults.circuit_min_requests
|
||||
),
|
||||
(4, 2, 60, 10)
|
||||
);
|
||||
assert_eq!(defaults.circuit_error_rate_threshold, 0.6);
|
||||
RoutingTuning {
|
||||
max_retries: 0,
|
||||
streaming_first_byte_timeout: 1,
|
||||
streaming_idle_timeout: 0,
|
||||
non_streaming_timeout: 60,
|
||||
circuit_failure_threshold: 1,
|
||||
circuit_success_threshold: 1,
|
||||
circuit_timeout_seconds: 0,
|
||||
circuit_error_rate_threshold: 0.0,
|
||||
circuit_min_requests: 5,
|
||||
}
|
||||
.validate()
|
||||
.unwrap();
|
||||
RoutingTuning {
|
||||
max_retries: 10,
|
||||
streaming_first_byte_timeout: 120,
|
||||
streaming_idle_timeout: 600,
|
||||
non_streaming_timeout: 1200,
|
||||
circuit_failure_threshold: 20,
|
||||
circuit_success_threshold: 10,
|
||||
circuit_timeout_seconds: 300,
|
||||
circuit_error_rate_threshold: 1.0,
|
||||
circuit_min_requests: 100,
|
||||
}
|
||||
.validate()
|
||||
.unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn invalid_tuning_is_rejected_in_backend() {
|
||||
for invalid in [
|
||||
RoutingTuning {
|
||||
max_retries: 11,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
streaming_first_byte_timeout: 0,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
streaming_first_byte_timeout: 121,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
streaming_idle_timeout: 601,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
non_streaming_timeout: 59,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
non_streaming_timeout: 1201,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
circuit_failure_threshold: 0,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
circuit_failure_threshold: 21,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
circuit_success_threshold: 0,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
circuit_success_threshold: 11,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
circuit_timeout_seconds: 301,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
circuit_error_rate_threshold: f64::NAN,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
circuit_error_rate_threshold: 1.1,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
circuit_min_requests: 4,
|
||||
..Default::default()
|
||||
},
|
||||
RoutingTuning {
|
||||
circuit_min_requests: 101,
|
||||
..Default::default()
|
||||
},
|
||||
] {
|
||||
assert!(invalid.validate().is_err(), "{invalid:?}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn listen_addresses_and_client_urls_support_ipv4_ipv6_and_wildcards() {
|
||||
assert_eq!(listen_ip("localhost").unwrap().to_string(), "127.0.0.1");
|
||||
assert_eq!(
|
||||
local_url(listen_ip("0.0.0.0").unwrap(), 15721),
|
||||
"http://127.0.0.1:15721/v1"
|
||||
);
|
||||
assert_eq!(
|
||||
local_url(listen_ip("::").unwrap(), 15721),
|
||||
"http://[::1]:15721/v1"
|
||||
);
|
||||
assert_eq!(
|
||||
local_url(listen_ip("[::1]").unwrap(), 15721),
|
||||
"http://[::1]:15721/v1"
|
||||
);
|
||||
for value in [
|
||||
"256.0.0.1",
|
||||
"host.example",
|
||||
"127.0.0.1:15721",
|
||||
"::1/path",
|
||||
"",
|
||||
] {
|
||||
assert!(listen_ip(value).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
mod circuit_breaker;
|
||||
pub(crate) mod config;
|
||||
mod controller;
|
||||
pub(crate) mod native_official;
|
||||
mod proxy;
|
||||
|
||||
#[cfg(any(test, target_os = "windows"))]
|
||||
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,
|
||||
};
|
||||
@@ -0,0 +1,577 @@
|
||||
//! Native Codex official routing. Codex remains the owner of its login and token
|
||||
//! refresh; this layer only verifies the selected live login and forwards it to
|
||||
//! its fixed official origin. No credential is loaded from an inactive profile.
|
||||
|
||||
use super::proxy::ProxyRoute;
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::providers::document_is_official;
|
||||
use crate::providers::official_profiles::{list_official_profiles_inner, selected_profile_id};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use toml_edit::DocumentMut;
|
||||
|
||||
const CHATGPT_BASE: &str = "https://chatgpt.com/backend-api/codex";
|
||||
const OPENAI_API_BASE: &str = "https://api.openai.com/v1";
|
||||
const MAX_CONFIG_BYTES: usize = 2 * 1024 * 1024;
|
||||
const MAX_AUTH_BYTES: usize = 1024 * 1024;
|
||||
const MAX_CATALOG_BYTES: usize = 1024 * 1024;
|
||||
const MAX_TOKEN_BYTES: usize = 32 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct OfficialRouteSpec {
|
||||
pub(crate) codex_dir: PathBuf,
|
||||
pub(crate) profile_id: String,
|
||||
}
|
||||
|
||||
// Intentionally not Debug/Serialize: these values must never appear in status,
|
||||
// frontend events, or error logs.
|
||||
pub(crate) struct OfficialRequestAuth {
|
||||
pub(crate) authorization: String,
|
||||
pub(crate) account_id: Option<String>,
|
||||
pub(crate) base_url: String,
|
||||
}
|
||||
|
||||
struct LiveAuth {
|
||||
token: String,
|
||||
account_id: Option<String>,
|
||||
base_url: &'static str,
|
||||
}
|
||||
|
||||
fn error(message: &str) -> CodexxError {
|
||||
CodexxError::Config(message.to_owned())
|
||||
}
|
||||
|
||||
fn read_bounded(path: &Path, limit: usize, missing_allowed: bool) -> Result<Vec<u8>> {
|
||||
let file = match fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(err) if missing_allowed && err.kind() == std::io::ErrorKind::NotFound => {
|
||||
return Ok(Vec::new())
|
||||
}
|
||||
Err(_) => return Err(error("无法读取当前官方登录配置,请检查文件后重试")),
|
||||
};
|
||||
if !file
|
||||
.metadata()
|
||||
.is_ok_and(|metadata| metadata.is_file() && metadata.len() <= limit as u64)
|
||||
{
|
||||
return Err(error("当前官方登录配置无法读取,请检查文件大小和格式"));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.take(limit as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| error("读取当前官方登录配置失败,请重试"))?;
|
||||
if bytes.len() > limit {
|
||||
return Err(error("当前官方登录配置过大,请检查文件"));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn logical_document(dir: &Path) -> Result<(Vec<u8>, DocumentMut)> {
|
||||
let bytes = read_bounded(&crate::config_path(dir), MAX_CONFIG_BYTES, true)?;
|
||||
let text = std::str::from_utf8(&bytes)
|
||||
.map_err(|_| error("当前 Codex 配置格式不正确,请先修复配置"))?;
|
||||
let doc = text
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|_| error("当前 Codex 配置格式不正确,请先修复配置"))?;
|
||||
let doc = super::direct_document(dir, &doc)
|
||||
.map_err(|_| error("无法确认当前官方路由,请检查本地路由状态"))?;
|
||||
Ok((bytes, doc))
|
||||
}
|
||||
|
||||
fn checked_secret(value: Option<&Value>) -> Option<String> {
|
||||
let value = value?.as_str()?.trim();
|
||||
(!value.is_empty()
|
||||
&& value.len() <= MAX_TOKEN_BYTES
|
||||
&& value.bytes().all(|byte| byte.is_ascii_graphic())
|
||||
&& value != "PROXY_MANAGED")
|
||||
.then(|| value.to_owned())
|
||||
}
|
||||
|
||||
fn checked_account(value: Option<&str>) -> Result<Option<String>> {
|
||||
let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if value.len() > 512 || !value.bytes().all(|byte| byte.is_ascii_graphic()) {
|
||||
return Err(error("当前官方账号信息无效,请重新登录 Codex"));
|
||||
}
|
||||
Ok(Some(value.to_owned()))
|
||||
}
|
||||
|
||||
fn parse_live_auth(bytes: &[u8]) -> Result<LiveAuth> {
|
||||
let auth: Value = serde_json::from_slice(bytes)
|
||||
.map_err(|_| error("官方账号尚未登录或认证无效,请在 Codex 中重新登录"))?;
|
||||
if !auth.is_object()
|
||||
|| ["base_url", "baseUrl", "api_base", "endpoint"]
|
||||
.iter()
|
||||
.any(|key| auth.get(key).is_some())
|
||||
{
|
||||
return Err(error("当前官方认证格式无效,请在 Codex 中重新登录"));
|
||||
}
|
||||
let mode = auth.get("auth_mode").and_then(Value::as_str);
|
||||
let api_key = checked_secret(auth.get("OPENAI_API_KEY"));
|
||||
let tokens = auth.get("tokens");
|
||||
let has_tokens = tokens.is_some_and(|value| {
|
||||
!value.is_null() && value.as_object().is_none_or(|values| !values.is_empty())
|
||||
});
|
||||
if let Some(token) = api_key {
|
||||
if mode.is_some_and(|value| !value.eq_ignore_ascii_case("apikey")) || has_tokens {
|
||||
return Err(error("官方登录与 API Key 认证混用,请在 Codex 中重新登录"));
|
||||
}
|
||||
return Ok(LiveAuth {
|
||||
token,
|
||||
account_id: None,
|
||||
base_url: OPENAI_API_BASE,
|
||||
});
|
||||
}
|
||||
if auth.get("OPENAI_API_KEY").is_some_and(|value| {
|
||||
!value.is_null() && value.as_str().is_none_or(|text| !text.trim().is_empty())
|
||||
}) {
|
||||
return Err(error("当前 OpenAI API Key 无效,请重新设置"));
|
||||
}
|
||||
if mode.is_some_and(|value| {
|
||||
!value.eq_ignore_ascii_case("chatgpt") && !value.eq_ignore_ascii_case("chatgptAuthTokens")
|
||||
}) {
|
||||
return Err(error(
|
||||
"此登录方式暂不支持本地路由,请使用 ChatGPT 登录或 OpenAI API Key",
|
||||
));
|
||||
}
|
||||
let token = checked_secret(auth.pointer("/tokens/access_token"))
|
||||
.ok_or_else(|| error("官方账号尚未登录,请在 Codex 中完成 ChatGPT 登录"))?;
|
||||
let account_id = checked_account(auth.pointer("/tokens/account_id").and_then(Value::as_str))?;
|
||||
Ok(LiveAuth {
|
||||
token,
|
||||
account_id,
|
||||
base_url: CHATGPT_BASE,
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_selected(spec: &OfficialRouteSpec) -> Result<(Vec<u8>, DocumentMut)> {
|
||||
let (bytes, doc) = logical_document(&spec.codex_dir)?;
|
||||
if !document_is_official(&doc)
|
||||
|| selected_profile_id(&spec.codex_dir)
|
||||
.map_err(|_| error("无法确认当前官方账号,请刷新后重试"))?
|
||||
!= spec.profile_id
|
||||
{
|
||||
return Err(error("当前官方账号已切换,请重启 Codex 或新建会话后重试"));
|
||||
}
|
||||
Ok((bytes, doc))
|
||||
}
|
||||
|
||||
pub(crate) fn route_for_current(dir: &Path) -> Result<Option<ProxyRoute>> {
|
||||
let (_, doc) = logical_document(dir)?;
|
||||
if !document_is_official(&doc) {
|
||||
return Ok(None);
|
||||
}
|
||||
let profile_id = selected_profile_id(dir)?;
|
||||
let name = list_official_profiles_inner(Some(dir.display().to_string()))?
|
||||
.into_iter()
|
||||
.find(|profile| profile.id == profile_id)
|
||||
.map(|profile| profile.provider_name)
|
||||
.unwrap_or_else(|| "OpenAI Official".to_owned());
|
||||
// A logged-out official route can still be taken over. Codex may complete
|
||||
// login or refresh after startup; every request re-reads and verifies it.
|
||||
let base_url = read_bounded(&crate::auth_path(dir), MAX_AUTH_BYTES, true)
|
||||
.ok()
|
||||
.and_then(|bytes| parse_live_auth(&bytes).ok())
|
||||
.map_or(CHATGPT_BASE, |auth| auth.base_url)
|
||||
.to_owned();
|
||||
let models = crate::string_value(&doc, "model")
|
||||
.into_iter()
|
||||
.collect::<HashSet<_>>();
|
||||
Ok(Some(ProxyRoute {
|
||||
id: format!("official:{profile_id}"),
|
||||
name,
|
||||
base_url,
|
||||
api_key: None,
|
||||
headers: Vec::new(),
|
||||
models,
|
||||
official: Some(OfficialRouteSpec {
|
||||
codex_dir: dir.to_path_buf(),
|
||||
profile_id,
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn verify_request(
|
||||
spec: &OfficialRouteSpec,
|
||||
authorization: &str,
|
||||
account_id: Option<&str>,
|
||||
) -> Result<OfficialRequestAuth> {
|
||||
let (config_before, _) = ensure_selected(spec)?;
|
||||
if authorization.len() > MAX_TOKEN_BYTES + 32 || authorization.chars().any(char::is_control) {
|
||||
return Err(error("官方请求认证无效,请在 Codex 中重新登录"));
|
||||
}
|
||||
let parts: Vec<_> = authorization.split_whitespace().collect();
|
||||
if parts.len() != 2 || !parts[0].eq_ignore_ascii_case("Bearer") {
|
||||
return Err(error("缺少官方请求认证,请在 Codex 中完成登录"));
|
||||
}
|
||||
let auth_before = read_bounded(&crate::auth_path(&spec.codex_dir), MAX_AUTH_BYTES, true)?;
|
||||
let auth = parse_live_auth(&auth_before)?;
|
||||
if parts[1] != auth.token || checked_account(account_id)? != auth.account_id {
|
||||
return Err(error(
|
||||
"此会话没有加载当前官方账号,请重启 Codex 或新建会话后重试",
|
||||
));
|
||||
}
|
||||
// Avoid trusting a token across a simultaneous account switch/logout/refresh.
|
||||
// This reads files only; acquiring the live mutation lock here would deadlock
|
||||
// callers constructing routes while holding their own configuration guard.
|
||||
let (config_after, _) = ensure_selected(spec)?;
|
||||
let auth_after = read_bounded(&crate::auth_path(&spec.codex_dir), MAX_AUTH_BYTES, true)?;
|
||||
if config_before != config_after || auth_before != auth_after {
|
||||
return Err(error("官方登录正在更新,请稍后重试"));
|
||||
}
|
||||
Ok(OfficialRequestAuth {
|
||||
authorization: format!("Bearer {}", auth.token),
|
||||
account_id: auth.account_id,
|
||||
base_url: auth.base_url.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
fn is_link(metadata: &fs::Metadata) -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
metadata.file_type().is_symlink() || metadata.file_attributes() & 0x400 != 0
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
metadata.file_type().is_symlink()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn native_models(spec: &OfficialRouteSpec) -> Result<Value> {
|
||||
let (_, doc) = ensure_selected(spec)?;
|
||||
let Some(pointer) = doc.get("model_catalog_json").and_then(|item| item.as_str()) else {
|
||||
return Ok(json!({"models":[]}));
|
||||
};
|
||||
let path = Path::new(pointer);
|
||||
if path
|
||||
.components()
|
||||
.any(|part| matches!(part, Component::ParentDir))
|
||||
{
|
||||
return Ok(json!({"models":[]}));
|
||||
}
|
||||
let path = if path.is_absolute() {
|
||||
path.to_owned()
|
||||
} else {
|
||||
spec.codex_dir.join(path)
|
||||
};
|
||||
let owned = spec.codex_dir.join(".codex-x").join("model-catalogs");
|
||||
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
|
||||
return Ok(json!({"models":[]}));
|
||||
};
|
||||
if !name
|
||||
.strip_suffix(".json")
|
||||
.is_some_and(|hash| hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()))
|
||||
{
|
||||
return Ok(json!({"models":[]}));
|
||||
}
|
||||
for directory in [spec.codex_dir.join(".codex-x"), owned.clone()] {
|
||||
if !fs::symlink_metadata(directory)
|
||||
.is_ok_and(|metadata| !is_link(&metadata) && metadata.is_dir())
|
||||
{
|
||||
return Ok(json!({"models":[]}));
|
||||
}
|
||||
}
|
||||
if !fs::symlink_metadata(&path).is_ok_and(|metadata| !is_link(&metadata) && metadata.is_file())
|
||||
|| !path
|
||||
.parent()
|
||||
.and_then(|parent| parent.canonicalize().ok())
|
||||
.zip(owned.canonicalize().ok())
|
||||
.is_some_and(|(parent, owned)| parent == owned)
|
||||
{
|
||||
return Ok(json!({"models":[]}));
|
||||
}
|
||||
let Ok(bytes) = read_bounded(&path, MAX_CATALOG_BYTES, false) else {
|
||||
return Ok(json!({"models":[]}));
|
||||
};
|
||||
let Ok(value) = serde_json::from_slice::<Value>(&bytes) else {
|
||||
return Ok(json!({"models":[]}));
|
||||
};
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(b"codex-x-provider-model-catalog-v2\0");
|
||||
digest.update(serde_json::to_vec(&value).map_err(|_| error("本地模型目录格式无效"))?);
|
||||
if value
|
||||
.pointer("/_codex_x_model_catalog/source")
|
||||
.and_then(Value::as_str)
|
||||
!= Some("codex-x")
|
||||
|| !value.get("models").is_some_and(Value::is_array)
|
||||
|| format!("{:x}.json", digest.finalize()) != name
|
||||
{
|
||||
return Ok(json!({"models":[]}));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::providers::official_profiles::{
|
||||
save_official_profile_inner, switch_official_profile_inner, OfficialProfileInput,
|
||||
DEFAULT_OFFICIAL_PROFILE_ID,
|
||||
};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
dir: PathBuf,
|
||||
}
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static COUNT: AtomicU64 = AtomicU64::new(0);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"codex-x-native-official-{}-{}",
|
||||
std::process::id(),
|
||||
COUNT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(crate::config_path(&dir), "model_provider = 'custom'\nmodel='official-model'\n[model_providers.custom]\nname='OpenAI'\nrequires_openai_auth=true\nsupports_websockets=true\nwire_api='responses'\n[mcp_servers.keep]\ncommand='fixture-mcp'\n").unwrap();
|
||||
Self { dir }
|
||||
}
|
||||
fn oauth(&self, access: &str, account: &str) {
|
||||
fs::write(crate::auth_path(&self.dir), serde_json::to_vec(&json!({"auth_mode":"chatgpt","tokens":{"access_token":access,"refresh_token":"unused-refresh-fixture","account_id":account}})).unwrap()).unwrap();
|
||||
}
|
||||
fn spec(&self) -> OfficialRouteSpec {
|
||||
OfficialRouteSpec {
|
||||
codex_dir: self.dir.clone(),
|
||||
profile_id: DEFAULT_OFFICIAL_PROFILE_ID.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_official_checks_exact_live_token_even_for_team_members_sharing_workspace() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.oauth("live-user-a-token", "shared-team-workspace");
|
||||
let auth_before = fs::read(crate::auth_path(&fixture.dir)).unwrap();
|
||||
let config_before = fs::read(crate::config_path(&fixture.dir)).unwrap();
|
||||
let spec = fixture.spec();
|
||||
let allowed = verify_request(
|
||||
&spec,
|
||||
"Bearer live-user-a-token",
|
||||
Some("shared-team-workspace"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(allowed.base_url, CHATGPT_BASE);
|
||||
assert_eq!(allowed.account_id.as_deref(), Some("shared-team-workspace"));
|
||||
for (authorization, account) in [
|
||||
("Bearer another-user-token", Some("shared-team-workspace")),
|
||||
("Bearer live-user-a-token", Some("other-workspace")),
|
||||
("Bearer live-user-a-token", None),
|
||||
("Bearer PROXY_MANAGED", Some("shared-team-workspace")),
|
||||
("Bearer\nlive-user-a-token", Some("shared-team-workspace")),
|
||||
("", Some("shared-team-workspace")),
|
||||
] {
|
||||
let failure = verify_request(&spec, authorization, account)
|
||||
.err()
|
||||
.expect("must reject stale or wrong account credentials")
|
||||
.to_string();
|
||||
assert!(!failure.contains("live-user-a-token"));
|
||||
assert!(!failure.contains("another-user-token"));
|
||||
assert!(!failure.contains("shared-team-workspace"));
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read(crate::auth_path(&fixture.dir)).unwrap(),
|
||||
auth_before
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(crate::config_path(&fixture.dir)).unwrap(),
|
||||
config_before
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_official_login_and_token_refresh_are_owned_by_codex_without_cached_credentials() {
|
||||
let fixture = Fixture::new();
|
||||
let route = route_for_current(&fixture.dir).unwrap().unwrap();
|
||||
assert!(route.api_key.is_none());
|
||||
assert!(route.headers.is_empty());
|
||||
let spec = route.official.unwrap();
|
||||
assert!(verify_request(&spec, "Bearer absent", None).is_err());
|
||||
fixture.oauth("first-token", "account");
|
||||
assert!(verify_request(&spec, "Bearer first-token", Some("account")).is_ok());
|
||||
fixture.oauth("refreshed-token", "account");
|
||||
assert!(verify_request(&spec, "Bearer first-token", Some("account")).is_err());
|
||||
assert!(verify_request(&spec, "Bearer refreshed-token", Some("account")).is_ok());
|
||||
let latest = fs::read(crate::auth_path(&fixture.dir)).unwrap();
|
||||
route_for_current(&fixture.dir).unwrap();
|
||||
assert_eq!(fs::read(crate::auth_path(&fixture.dir)).unwrap(), latest);
|
||||
fs::remove_file(crate::auth_path(&fixture.dir)).unwrap();
|
||||
assert!(verify_request(&spec, "Bearer refreshed-token", Some("account")).is_err());
|
||||
assert!(route_for_current(&fixture.dir).unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_official_does_not_reuse_inactive_profile_or_third_party_oauth() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.oauth("account-a-token", "workspace");
|
||||
let scope = Some(fixture.dir.display().to_string());
|
||||
let other = save_official_profile_inner(OfficialProfileInput {
|
||||
config_dir: scope.clone(), id: None, provider_name: "Account B".into(),
|
||||
model: Some("official-model".into()), config_text: Some(fs::read_to_string(crate::config_path(&fixture.dir)).unwrap()),
|
||||
auth_json: Some(json!({"auth_mode":"chatgpt","tokens":{"access_token":"account-b-token","account_id":"workspace"}}).to_string()),
|
||||
}).unwrap();
|
||||
let spec = fixture.spec();
|
||||
assert!(verify_request(&spec, "Bearer account-b-token", Some("workspace")).is_err());
|
||||
switch_official_profile_inner(scope, other.profile.id.clone()).unwrap();
|
||||
assert!(verify_request(&spec, "Bearer account-b-token", Some("workspace")).is_err());
|
||||
let current = route_for_current(&fixture.dir)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.official
|
||||
.unwrap();
|
||||
assert_eq!(current.profile_id, other.profile.id);
|
||||
assert!(verify_request(¤t, "Bearer account-b-token", Some("workspace")).is_ok());
|
||||
fs::write(crate::config_path(&fixture.dir), "model_provider='custom'\nmodel='third'\n[model_providers.custom]\nname='Third'\nbase_url='https://third.example.test/v1'\nrequires_openai_auth=false\n").unwrap();
|
||||
assert!(route_for_current(&fixture.dir).unwrap().is_none());
|
||||
assert!(verify_request(¤t, "Bearer account-b-token", Some("workspace")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_api_key_uses_only_openai_api_origin_and_never_accepts_oauth_or_mixed_auth() {
|
||||
let fixture = Fixture::new();
|
||||
fs::write(
|
||||
crate::auth_path(&fixture.dir),
|
||||
json!({"auth_mode":"apikey","OPENAI_API_KEY":"api-key-fixture","tokens":null})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = fixture.spec();
|
||||
let verified = verify_request(&spec, "Bearer api-key-fixture", None).unwrap();
|
||||
assert_eq!(verified.base_url, OPENAI_API_BASE);
|
||||
assert!(verified.account_id.is_none());
|
||||
assert!(verify_request(&spec, "Bearer oauth-fixture", None).is_err());
|
||||
assert!(
|
||||
verify_request(&spec, "Bearer api-key-fixture", Some("old-oauth-account")).is_err()
|
||||
);
|
||||
fs::write(
|
||||
crate::auth_path(&fixture.dir),
|
||||
json!({"OPENAI_API_KEY":"api-key-fixture","tokens":{"access_token":"oauth-fixture"}})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(verify_request(&spec, "Bearer api-key-fixture", None).is_err());
|
||||
assert!(verify_request(&spec, "Bearer oauth-fixture", None).is_err());
|
||||
fs::write(crate::auth_path(&fixture.dir), "{ broken-secret-json").unwrap();
|
||||
let failure = verify_request(&spec, "Bearer api-key-fixture", None)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert!(!failure.contains("broken-secret-json"));
|
||||
assert!(!failure.contains("api-key-fixture"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_models_serve_only_verified_owned_catalog_and_never_read_arbitrary_json() {
|
||||
let fixture = Fixture::new();
|
||||
let spec = fixture.spec();
|
||||
assert_eq!(native_models(&spec).unwrap(), json!({"models":[]}));
|
||||
let config_path = crate::config_path(&fixture.dir);
|
||||
let mut doc = fs::read_to_string(&config_path)
|
||||
.unwrap()
|
||||
.parse::<DocumentMut>()
|
||||
.unwrap();
|
||||
crate::providers::model_catalog::prepare_model_catalog(
|
||||
&fixture.dir,
|
||||
"native-test",
|
||||
&[crate::providers::model_catalog::ProviderModelMapping {
|
||||
model: "local-model".into(),
|
||||
display_name: "Local".into(),
|
||||
context_window: None,
|
||||
}],
|
||||
"local-model",
|
||||
&mut doc,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(&config_path, doc.to_string()).unwrap();
|
||||
let owned = PathBuf::from(doc["model_catalog_json"].as_str().unwrap());
|
||||
let before = fs::read(&config_path).unwrap();
|
||||
assert_eq!(
|
||||
native_models(&spec).unwrap()["models"][0]["slug"],
|
||||
"local-model"
|
||||
);
|
||||
assert_eq!(fs::read(&config_path).unwrap(), before);
|
||||
let outside = fixture.dir.join("unrelated-auth.json");
|
||||
fs::write(&outside, r#"{"models":["must-not-leak"]}"#).unwrap();
|
||||
doc["model_catalog_json"] = toml_edit::value(outside.display().to_string());
|
||||
fs::write(&config_path, doc.to_string()).unwrap();
|
||||
assert_eq!(native_models(&spec).unwrap(), json!({"models":[]}));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::remove_file(&owned).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, &owned).unwrap();
|
||||
doc["model_catalog_json"] = toml_edit::value(owned.display().to_string());
|
||||
fs::write(&config_path, doc.to_string()).unwrap();
|
||||
assert_eq!(native_models(&spec).unwrap(), json!({"models":[]}));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn native_local_models_endpoint_accepts_owned_live_oauth_without_network_refresh_or_fallback() {
|
||||
use super::super::config::{RoutingTuning, ROUTE_TOKEN_HEADER};
|
||||
use super::super::proxy::{ProxyHandle, ProxyOptions};
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::time::Duration;
|
||||
struct Server(ProxyHandle);
|
||||
impl Drop for Server {
|
||||
fn drop(&mut self) {
|
||||
self.0.shutdown();
|
||||
}
|
||||
}
|
||||
let fixture = Fixture::new();
|
||||
fixture.oauth("local-native-access", "local-native-account");
|
||||
let route = route_for_current(&fixture.dir).unwrap().unwrap();
|
||||
let local_token = "native-local-route-token-fixture-000000000000";
|
||||
let server = Server(
|
||||
ProxyHandle::start(
|
||||
IpAddr::V4(Ipv4Addr::LOCALHOST),
|
||||
0,
|
||||
local_token.into(),
|
||||
vec![route],
|
||||
ProxyOptions {
|
||||
auto_failover_enabled: true,
|
||||
tuning: RoutingTuning::default(),
|
||||
},
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let client = reqwest::blocking::Client::builder()
|
||||
.no_proxy()
|
||||
.timeout(Duration::from_secs(5))
|
||||
.build()
|
||||
.unwrap();
|
||||
for access in ["local-native-access", "local-native-refreshed"] {
|
||||
fixture.oauth(access, "local-native-account");
|
||||
let auth_before = fs::read(crate::auth_path(&fixture.dir)).unwrap();
|
||||
let response = client
|
||||
.get(format!("http://127.0.0.1:{}/v1/models", server.0.port()))
|
||||
.header(ROUTE_TOKEN_HEADER, local_token)
|
||||
.header("authorization", format!("Bearer {access}"))
|
||||
.header("chatgpt-account-id", "local-native-account")
|
||||
.send()
|
||||
.unwrap();
|
||||
assert_eq!(response.status().as_u16(), 200);
|
||||
let body: Value = serde_json::from_str(&response.text().unwrap()).unwrap();
|
||||
assert_eq!(body, json!({"models":[]}));
|
||||
assert_eq!(
|
||||
fs::read(crate::auth_path(&fixture.dir)).unwrap(),
|
||||
auth_before
|
||||
);
|
||||
}
|
||||
let snapshot = server.0.snapshot();
|
||||
assert_eq!(snapshot.success_count, 2);
|
||||
assert_eq!(snapshot.failover_count, 0);
|
||||
assert_eq!(
|
||||
snapshot.last_provider_id.as_deref(),
|
||||
Some("official:openai-official")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,824 @@
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
|
||||
struct Fixture {
|
||||
dir: PathBuf,
|
||||
providers: Vec<SavedProvider>,
|
||||
original: String,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let number = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let tag = format!("failover-test-{}-{number}", std::process::id());
|
||||
let dir = std::env::temp_dir().join(&tag);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let dir = dir.canonicalize().unwrap();
|
||||
let mut providers = Vec::new();
|
||||
for index in 0..3 {
|
||||
let provider = SavedProvider {
|
||||
id: format!("{tag}-{index}"),
|
||||
provider_name: format!("Provider {index}"),
|
||||
base_url: format!("https://{tag}-{index}.example.test/v1"),
|
||||
model: "same-model".into(),
|
||||
api_key: Some(format!("fixture-provider-secret-{index}")),
|
||||
toml_config: None,
|
||||
wire_api: "responses".into(),
|
||||
requires_openai_auth: false,
|
||||
model_mappings: vec![],
|
||||
};
|
||||
providers.push(crate::providers::save_provider_inner(provider).unwrap());
|
||||
}
|
||||
let primary = &providers[0];
|
||||
let original = format!("# preserve user config\nmodel_provider = \"custom\"\nmodel = \"same-model\"\nmodel_reasoning_effort = \"high\"\n\n[model_providers.custom]\nname = \"Provider 0\"\nbase_url = {:?}\nwire_api = \"responses\"\nrequires_openai_auth = false\nsupports_websockets = true\nexperimental_bearer_token = {:?}\nrequest_max_retries = 4\n\n[model_providers.custom.http_headers]\nx-fixture = \"primary-header\"\n\n[mcp_servers.fixture]\ncommand = \"fixture-tool\"\n", primary.base_url, primary.api_key.as_deref().unwrap());
|
||||
fs::write(crate::config_path(&dir), &original).unwrap();
|
||||
fs::write(
|
||||
dir.join("auth.json"),
|
||||
"{\"OPENAI_API_KEY\":\"untouched-official-auth-fixture\"}",
|
||||
)
|
||||
.unwrap();
|
||||
crate::providers::remember_active_provider_on_connection(
|
||||
&crate::app_db::open().unwrap(),
|
||||
&dir,
|
||||
&primary.id,
|
||||
)
|
||||
.unwrap();
|
||||
Self {
|
||||
dir,
|
||||
providers,
|
||||
original,
|
||||
port: free_port(),
|
||||
}
|
||||
}
|
||||
fn scope(&self) -> Option<String> {
|
||||
Some(self.dir.display().to_string())
|
||||
}
|
||||
fn settings(&self) -> FailoverSettings {
|
||||
FailoverSettings {
|
||||
router_enabled: true,
|
||||
takeover_enabled: true,
|
||||
auto_failover_enabled: true,
|
||||
listen_port: self.port,
|
||||
provider_ids: vec![self.providers[0].id.clone(), self.providers[1].id.clone()],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
fn text(&self) -> String {
|
||||
fs::read_to_string(crate::config_path(&self.dir)).unwrap()
|
||||
}
|
||||
fn enable(&self) -> FailoverStatus {
|
||||
save_settings(self.scope(), self.settings()).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
SHUTTING_DOWN.store(false, Ordering::Release);
|
||||
// If a test deliberately left invalid TOML, repair only its private fixture.
|
||||
if let Ok(record) = load_record(&self.dir) {
|
||||
if let Ok(mut runtimes) = lock_manager() {
|
||||
if let Some(runtime) = runtimes.remove(&self.dir) {
|
||||
runtime.proxy.shutdown();
|
||||
}
|
||||
}
|
||||
let _ = record;
|
||||
}
|
||||
if let Ok(conn) = crate::app_db::open() {
|
||||
let _ = conn.execute(
|
||||
"DELETE FROM provider_failover WHERE codex_dir = ?1",
|
||||
[normalized_path_scope(&self.dir)],
|
||||
);
|
||||
let _ = conn.execute(
|
||||
"DELETE FROM active_provider_selections WHERE codex_dir = ?1",
|
||||
[normalized_path_scope(&self.dir)],
|
||||
);
|
||||
for provider in &self.providers {
|
||||
let _ = conn.execute("DELETE FROM providers WHERE id = ?1", [&provider.id]);
|
||||
}
|
||||
}
|
||||
let _ = fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
fn free_port() -> u16 {
|
||||
std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port()
|
||||
}
|
||||
fn stop(fixture: &Fixture) {
|
||||
let mut settings = load_record(&fixture.dir).unwrap().settings;
|
||||
settings.router_enabled = false;
|
||||
save_settings(fixture.scope(), settings).unwrap();
|
||||
}
|
||||
fn parsed(fixture: &Fixture) -> DocumentMut {
|
||||
fixture.text().parse().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_takeover_and_auto_switches_are_independent() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let auth = fs::read(fixture.dir.join("auth.json")).unwrap();
|
||||
let mut settings = fixture.settings();
|
||||
settings.takeover_enabled = false;
|
||||
settings.auto_failover_enabled = false;
|
||||
let listening = save_settings(fixture.scope(), settings.clone()).unwrap();
|
||||
assert!(listening.running);
|
||||
assert!(!listening.takeover_active);
|
||||
assert!(!listening.auto_failover_active);
|
||||
assert_eq!(fixture.text(), fixture.original);
|
||||
settings.takeover_enabled = true;
|
||||
let single = save_settings(fixture.scope(), settings.clone()).unwrap();
|
||||
assert!(single.takeover_active);
|
||||
assert!(!single.auto_failover_active);
|
||||
assert_eq!(single.runtime.providers.len(), 1);
|
||||
assert_eq!(single.primary.as_ref().unwrap().id, fixture.providers[0].id);
|
||||
settings.auto_failover_enabled = true;
|
||||
let automatic = save_settings(fixture.scope(), settings).unwrap();
|
||||
assert!(automatic.auto_failover_active);
|
||||
assert_eq!(automatic.runtime.providers.len(), 2);
|
||||
assert_eq!(fs::read(fixture.dir.join("auth.json")).unwrap(), auth);
|
||||
stop(&fixture);
|
||||
let stopped = get_status(fixture.scope()).unwrap();
|
||||
assert!(!stopped.running && !stopped.takeover_active);
|
||||
assert!(stopped.settings.auto_failover_enabled);
|
||||
assert_eq!(stopped.settings.provider_ids.len(), 2);
|
||||
assert_eq!(
|
||||
parsed(&fixture)["mcp_servers"]["fixture"]["command"].as_str(),
|
||||
Some("fixture-tool")
|
||||
);
|
||||
assert_eq!(
|
||||
parsed(&fixture)["model_providers"]["custom"]["base_url"].as_str(),
|
||||
Some(fixture.providers[0].base_url.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_auto_switches_to_p1_even_if_current_is_elsewhere() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let mut settings = fixture.settings();
|
||||
settings.provider_ids = vec![
|
||||
fixture.providers[2].id.clone(),
|
||||
fixture.providers[0].id.clone(),
|
||||
];
|
||||
let status = save_settings(fixture.scope(), settings).unwrap();
|
||||
assert!(status.auto_failover_active);
|
||||
assert_eq!(status.primary.as_ref().unwrap().id, fixture.providers[2].id);
|
||||
assert_eq!(status.runtime.providers[0].id, fixture.providers[2].id);
|
||||
assert_eq!(status.settings.provider_ids[0], fixture.providers[2].id);
|
||||
stop(&fixture);
|
||||
assert_eq!(
|
||||
parsed(&fixture)["model_providers"]["custom"]["base_url"].as_str(),
|
||||
Some(fixture.providers[2].base_url.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_provider_queue_and_an_empty_running_queue_are_valid() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let mut settings = fixture.settings();
|
||||
settings.provider_ids.clear();
|
||||
let single = save_settings(fixture.scope(), settings).unwrap();
|
||||
assert_eq!(
|
||||
single.settings.provider_ids,
|
||||
vec![fixture.providers[0].id.clone()]
|
||||
);
|
||||
assert!(single.auto_failover_active);
|
||||
let mut settings = single.settings;
|
||||
settings.provider_ids.clear();
|
||||
let empty = save_settings(fixture.scope(), settings).unwrap();
|
||||
assert!(empty.running && empty.auto_failover_active);
|
||||
assert!(empty.runtime.providers.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_accepts_different_models_and_can_be_prepared_while_stopped() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.providers[1].model = "another-model".into();
|
||||
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(
|
||||
status
|
||||
.providers
|
||||
.iter()
|
||||
.find(|p| p.id == fixture.providers[1].id)
|
||||
.unwrap()
|
||||
.eligible
|
||||
);
|
||||
let mut settings = fixture.settings();
|
||||
settings.router_enabled = false;
|
||||
settings.takeover_enabled = false;
|
||||
settings.auto_failover_enabled = false;
|
||||
let saved = save_settings(fixture.scope(), settings).unwrap();
|
||||
assert!(!saved.running);
|
||||
assert_eq!(fixture.text(), fixture.original);
|
||||
assert_eq!(saved.settings.provider_ids.len(), 2);
|
||||
fixture.enable();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_and_scope_validation_have_no_live_side_effects() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let mut invalid = fixture.settings();
|
||||
invalid.listen_port = 1000;
|
||||
assert!(save_settings(fixture.scope(), invalid).is_err());
|
||||
let mut invalid = fixture.settings();
|
||||
invalid.provider_ids.push(invalid.provider_ids[0].clone());
|
||||
assert!(save_settings(fixture.scope(), invalid).is_err());
|
||||
let mut invalid = fixture.settings();
|
||||
invalid.provider_ids = vec!["official:openai-official".into()];
|
||||
assert!(save_settings(fixture.scope(), invalid).is_err());
|
||||
let mut invalid = fixture.settings();
|
||||
invalid.takeover_enabled = false;
|
||||
assert!(save_settings(fixture.scope(), invalid).is_err());
|
||||
assert_eq!(fixture.text(), fixture.original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_bind_and_missing_p1_leave_configuration_and_settings_unchanged() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let blocker =
|
||||
std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, fixture.port)).unwrap();
|
||||
assert!(save_settings(fixture.scope(), fixture.settings()).is_err());
|
||||
assert_eq!(fixture.text(), fixture.original);
|
||||
assert!(!get_status(fixture.scope()).unwrap().running);
|
||||
drop(blocker);
|
||||
let mut settings = fixture.settings();
|
||||
settings.provider_ids = vec!["missing-p1".into()];
|
||||
assert!(save_settings(fixture.scope(), settings).is_err());
|
||||
assert_eq!(fixture.text(), fixture.original);
|
||||
assert!(!get_status(fixture.scope()).unwrap().settings.router_enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_and_tuning_updates_keep_the_endpoint_and_update_all_parameters() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let before = fixture.text();
|
||||
let mut settings = fixture.settings();
|
||||
settings.provider_ids.reverse();
|
||||
settings.tuning = RoutingTuning {
|
||||
max_retries: 8,
|
||||
streaming_first_byte_timeout: 10,
|
||||
streaming_idle_timeout: 0,
|
||||
non_streaming_timeout: 900,
|
||||
circuit_failure_threshold: 7,
|
||||
circuit_success_threshold: 4,
|
||||
circuit_timeout_seconds: 45,
|
||||
circuit_error_rate_threshold: 0.75,
|
||||
circuit_min_requests: 15,
|
||||
};
|
||||
let status = save_settings(fixture.scope(), settings.clone()).unwrap();
|
||||
assert_eq!(status.settings, settings);
|
||||
assert_eq!(fixture.text(), before);
|
||||
assert_eq!(status.runtime.providers[0].id, fixture.providers[1].id);
|
||||
let mut bad = status.settings;
|
||||
bad.listen_port = free_port();
|
||||
assert!(save_settings(fixture.scope(), bad).is_err());
|
||||
assert_eq!(fixture.text(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_switch_keeps_routing_and_auto_but_official_never_joins_api_queue() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
with_provider_change(fixture.scope(), || {
|
||||
crate::providers::activate_saved_provider_inner(
|
||||
fixture.scope(),
|
||||
fixture.providers[2].id.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let switched = get_status(fixture.scope()).unwrap();
|
||||
assert!(switched.running && switched.auto_failover_active);
|
||||
assert_eq!(switched.primary.unwrap().id, fixture.providers[2].id);
|
||||
with_provider_change(fixture.scope(), || {
|
||||
crate::providers::official_profiles::switch_official_profile_inner(
|
||||
fixture.scope(),
|
||||
crate::providers::official_profiles::DEFAULT_OFFICIAL_PROFILE_ID.into(),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let official = get_status(fixture.scope()).unwrap();
|
||||
assert!(official.running && official.takeover_active);
|
||||
assert!(!official.auto_failover_active);
|
||||
assert!(official.settings.auto_failover_enabled);
|
||||
assert!(official.primary.unwrap().official);
|
||||
assert!(official
|
||||
.runtime
|
||||
.providers
|
||||
.iter()
|
||||
.all(|p| p.id.starts_with("official:")));
|
||||
assert!(official.providers.iter().all(|p| !p.official));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn official_takeover_preserves_auth_and_can_restore_a_builtin_route() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let original = "model='official-model'\n[mcp_servers.test]\ncommand='tool'\n";
|
||||
fs::write(crate::config_path(&fixture.dir), original).unwrap();
|
||||
let auth = fs::read(fixture.dir.join("auth.json")).unwrap();
|
||||
let mut settings = fixture.settings();
|
||||
settings.auto_failover_enabled = false;
|
||||
settings.provider_ids.clear();
|
||||
let status = save_settings(fixture.scope(), settings).unwrap();
|
||||
assert!(status.primary.unwrap().official);
|
||||
assert!(status.takeover_active && !status.auto_failover_active);
|
||||
let doc = parsed(&fixture);
|
||||
assert_eq!(
|
||||
doc["model_providers"]["openai"]["requires_openai_auth"].as_bool(),
|
||||
Some(true)
|
||||
);
|
||||
assert!(doc["model_providers"]["openai"]
|
||||
.get("experimental_bearer_token")
|
||||
.is_none());
|
||||
assert!(doc["model_providers"]["openai"]["http_headers"]
|
||||
.get(ROUTE_TOKEN_HEADER)
|
||||
.is_some());
|
||||
assert_eq!(fs::read(fixture.dir.join("auth.json")).unwrap(), auth);
|
||||
stop(&fixture);
|
||||
assert!(parsed(&fixture).get("model_providers").is_none());
|
||||
assert_eq!(
|
||||
parsed(&fixture)["mcp_servers"]["test"]["command"].as_str(),
|
||||
Some("tool")
|
||||
);
|
||||
assert_eq!(fs::read(fixture.dir.join("auth.json")).unwrap(), auth);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_manual_switch_reattaches_original_route() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let error = with_provider_change::<()>(fixture.scope(), || {
|
||||
Err(CodexxError::Config("expected switch failure".into()))
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("expected switch failure"));
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(status.running && status.takeover_active);
|
||||
assert_eq!(status.primary.unwrap().id, fixture.providers[0].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_keeps_external_edits_and_does_not_leave_local_headers() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let mut doc = parsed(&fixture);
|
||||
doc["model_reasoning_effort"] = value("max");
|
||||
doc["model_providers"]["custom"]["request_max_retries"] = value(9);
|
||||
doc["model_providers"]["custom"]["external_new_setting"] = value("preserved");
|
||||
fs::write(crate::config_path(&fixture.dir), doc.to_string()).unwrap();
|
||||
stop(&fixture);
|
||||
let restored = parsed(&fixture);
|
||||
assert_eq!(restored["model_reasoning_effort"].as_str(), Some("max"));
|
||||
assert_eq!(
|
||||
restored["model_providers"]["custom"]["request_max_retries"].as_integer(),
|
||||
Some(9)
|
||||
);
|
||||
assert_eq!(
|
||||
restored["model_providers"]["custom"]["external_new_setting"].as_str(),
|
||||
Some("preserved")
|
||||
);
|
||||
assert_eq!(
|
||||
restored["model_providers"]["custom"]["http_headers"]["x-fixture"].as_str(),
|
||||
Some("primary-header")
|
||||
);
|
||||
assert!(!fixture.text().contains(ROUTE_GENERATION_HEADER));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_provider_change_detaches_without_stopping_the_listener() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let external = fixture
|
||||
.original
|
||||
.replace(
|
||||
&fixture.providers[0].base_url,
|
||||
&fixture.providers[2].base_url,
|
||||
)
|
||||
.replace("fixture-provider-secret-0", "fixture-provider-secret-2");
|
||||
fs::write(crate::config_path(&fixture.dir), &external).unwrap();
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(status.running && !status.takeover_active);
|
||||
assert!(!status.settings.takeover_enabled);
|
||||
assert_eq!(fixture.text(), external);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_restore_keeps_the_listener_alive() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let managed = fixture.text();
|
||||
fs::write(crate::config_path(&fixture.dir), "invalid = [").unwrap();
|
||||
let mut off = fixture.settings();
|
||||
off.router_enabled = false;
|
||||
assert!(save_settings(fixture.scope(), off).is_err());
|
||||
assert!(lock_manager().unwrap().contains_key(&fixture.dir));
|
||||
fs::write(crate::config_path(&fixture.dir), managed).unwrap();
|
||||
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();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
shutdown_all().unwrap();
|
||||
assert!(!fixture.text().contains("http://127.0.0.1:"));
|
||||
let record = load_record(&fixture.dir).unwrap();
|
||||
assert!(record.settings.router_enabled && record.settings.takeover_enabled);
|
||||
assert!(save_settings(fixture.scope(), fixture.settings()).is_err());
|
||||
SHUTTING_DOWN.store(false, Ordering::Release);
|
||||
initialize().unwrap();
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(status.takeover_active);
|
||||
assert_eq!(status.settings.listen_port, fixture.port);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_managed_backups_keep_their_original_provider_after_later_takeovers() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let old = fixture.text();
|
||||
with_provider_change(fixture.scope(), || {
|
||||
crate::providers::activate_saved_provider_inner(
|
||||
fixture.scope(),
|
||||
fixture.providers[2].id.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
stop(&fixture);
|
||||
fs::write(crate::config_path(&fixture.dir), old).unwrap();
|
||||
recover_stale_route(fixture.scope()).unwrap();
|
||||
assert_eq!(
|
||||
parsed(&fixture)["model_providers"]["custom"]["base_url"].as_str(),
|
||||
Some(fixture.providers[0].base_url.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_enabled_backups_settings_migrate_to_full_p1_queue() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let old = serde_json::json!({"settings":{"enabled":true,"providerIds":[fixture.providers[1].id]},"journals":[{"primaryId":fixture.providers[0].id,"providerKey":"custom","originalTable":"name='old'","port":fixture.port,"token":"old-only-test-token"}]});
|
||||
crate::app_db::open()
|
||||
.unwrap()
|
||||
.execute(
|
||||
"INSERT INTO provider_failover(codex_dir,record_json) VALUES(?1,?2)",
|
||||
params![normalized_path_scope(&fixture.dir), old.to_string()],
|
||||
)
|
||||
.unwrap();
|
||||
let migrated = load_record(&fixture.dir).unwrap();
|
||||
assert_eq!(migrated.version, 2);
|
||||
assert!(
|
||||
migrated.settings.router_enabled
|
||||
&& migrated.settings.takeover_enabled
|
||||
&& migrated.settings.auto_failover_enabled
|
||||
);
|
||||
assert_eq!(
|
||||
migrated.settings.provider_ids,
|
||||
vec![
|
||||
fixture.providers[0].id.clone(),
|
||||
fixture.providers[1].id.clone()
|
||||
]
|
||||
);
|
||||
assert_eq!(migrated.settings.tuning, RoutingTuning::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_never_serializes_provider_credentials_or_local_tokens() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let status = fixture.enable();
|
||||
let text = serde_json::to_string(&status).unwrap();
|
||||
assert!(!text.contains("fixture-provider-secret"));
|
||||
let record = load_record(&fixture.dir).unwrap();
|
||||
assert!(!text.contains(&record.journals.last().unwrap().token));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_one_queue_member_keeps_the_rest_and_listener() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
crate::providers::delete_provider_inner(&fixture.providers[1].id).unwrap();
|
||||
refresh_saved_routes().unwrap();
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(status.running && status.takeover_active);
|
||||
assert_eq!(status.runtime.providers.len(), 1);
|
||||
assert_eq!(status.runtime.providers[0].id, fixture.providers[0].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_can_run_without_a_configured_provider() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fs::remove_file(crate::config_path(&fixture.dir)).unwrap();
|
||||
let status = save_settings(
|
||||
fixture.scope(),
|
||||
FailoverSettings {
|
||||
router_enabled: true,
|
||||
listen_port: fixture.port,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(status.running && !status.takeover_active);
|
||||
assert!(!crate::config_path(&fixture.dir).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_fallback_updates_logical_provider_and_preserves_old_backup_identity() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.providers[1].model = "different-default".into();
|
||||
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
|
||||
fixture.enable();
|
||||
let earlier_backup = fixture.text();
|
||||
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();
|
||||
drop(runtimes);
|
||||
let selected = get_status(fixture.scope()).unwrap();
|
||||
assert_eq!(selected.primary.unwrap().id, fixture.providers[1].id);
|
||||
assert_eq!(parsed(&fixture)["model"].as_str(), Some("same-model"));
|
||||
let direct = direct_document(&fixture.dir, &parsed(&fixture)).unwrap();
|
||||
assert_eq!(
|
||||
direct["model_providers"]["custom"]["name"].as_str(),
|
||||
Some("Provider 1")
|
||||
);
|
||||
assert_eq!(
|
||||
direct["model_providers"]["custom"]["experimental_bearer_token"].as_str(),
|
||||
Some("fixture-provider-secret-1")
|
||||
);
|
||||
stop(&fixture);
|
||||
assert_eq!(
|
||||
parsed(&fixture)["model_providers"]["custom"]["base_url"].as_str(),
|
||||
Some(fixture.providers[1].base_url.as_str())
|
||||
);
|
||||
fs::write(crate::config_path(&fixture.dir), earlier_backup).unwrap();
|
||||
recover_stale_route(fixture.scope()).unwrap();
|
||||
assert_eq!(
|
||||
parsed(&fixture)["model_providers"]["custom"]["base_url"].as_str(),
|
||||
Some(fixture.providers[0].base_url.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_success_cannot_override_a_manual_switch_or_a_changed_queue() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let notice = {
|
||||
let runtimes = lock_manager().unwrap();
|
||||
let runtime = runtimes.get(&fixture.dir).unwrap();
|
||||
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(),
|
||||
},
|
||||
}
|
||||
};
|
||||
with_provider_change(fixture.scope(), || {
|
||||
crate::providers::activate_saved_provider_inner(
|
||||
fixture.scope(),
|
||||
fixture.providers[2].id.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
record_selection(notice, &mut lock_manager().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
get_status(fixture.scope()).unwrap().primary.unwrap().id,
|
||||
fixture.providers[2].id
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_success_from_a_stopped_listener_cannot_change_the_restarted_route() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let notice = {
|
||||
let runtimes = lock_manager().unwrap();
|
||||
let runtime = runtimes.get(&fixture.dir).unwrap();
|
||||
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(),
|
||||
},
|
||||
}
|
||||
};
|
||||
stop(&fixture);
|
||||
fixture.enable();
|
||||
let mut runtimes = lock_manager().unwrap();
|
||||
let restarted = runtimes.get(&fixture.dir).unwrap();
|
||||
assert_eq!(notice.token, restarted.token);
|
||||
assert_eq!(notice.event.revision, restarted.proxy.revision());
|
||||
assert_ne!(notice.instance_id, restarted.instance_id);
|
||||
record_selection(notice, &mut runtimes).unwrap();
|
||||
drop(runtimes);
|
||||
assert_eq!(
|
||||
get_status(fixture.scope()).unwrap().primary.unwrap().id,
|
||||
fixture.providers[0].id
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_journal_write_failure_after_p1_rolls_back_files_and_common_recovery_marker() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
let target = &fixture.providers[2].id;
|
||||
crate::app_db::open().unwrap().execute_batch(&format!("CREATE TRIGGER reject_p1_journal BEFORE UPDATE ON provider_failover WHEN json_extract(NEW.record_json,'$.journals[#-1].primaryId') = '{target}' BEGIN SELECT RAISE(ABORT,'fixture-journal-failure'); END;")).unwrap();
|
||||
let mut settings = fixture.settings();
|
||||
settings.provider_ids = vec![target.clone()];
|
||||
let result = save_settings(fixture.scope(), settings);
|
||||
crate::app_db::open()
|
||||
.unwrap()
|
||||
.execute_batch("DROP TRIGGER reject_p1_journal")
|
||||
.unwrap();
|
||||
assert!(result.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);
|
||||
assert_eq!(before.common_handled, after.common_handled);
|
||||
assert!(!get_status(fixture.scope()).unwrap().running);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn p1_journal_failure_restores_official_endpoint_before_oauth() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let mut fixture = Fixture::new();
|
||||
fs::write(crate::config_path(&fixture.dir), "model='official-model'\n").unwrap();
|
||||
fs::write(crate::auth_path(&fixture.dir),r#"{"auth_mode":"chatgpt","tokens":{"access_token":"fixture-oauth","account_id":"fixture-account"}}"#).unwrap();
|
||||
fixture.providers[2].requires_openai_auth = true;
|
||||
fixture.providers[2] =
|
||||
crate::providers::save_provider_inner(fixture.providers[2].clone()).unwrap();
|
||||
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
let mut settings = fixture.settings();
|
||||
settings.provider_ids = vec![fixture.providers[2].id.clone()];
|
||||
// Verify the prepared direct route really reads the global auth file. This
|
||||
// is the interval a failed journal write must undo before publishing OAuth.
|
||||
switch_to_p1(&fixture.dir, &mut settings).unwrap();
|
||||
let prepared = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
let doc = parsed(&fixture);
|
||||
let key = doc["model_provider"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
doc["model_providers"][key]["requires_openai_auth"].as_bool(),
|
||||
Some(true)
|
||||
);
|
||||
assert!(doc["model_providers"][key]
|
||||
.get("experimental_bearer_token")
|
||||
.is_none());
|
||||
assert_eq!(
|
||||
crate::providers::replacement_write_order(
|
||||
prepared.config.as_deref(),
|
||||
before.config.as_deref()
|
||||
),
|
||||
crate::providers::LiveWriteOrder::ConfigFirst
|
||||
);
|
||||
before.restore(&fixture.dir, &prepared).unwrap();
|
||||
let target = &fixture.providers[2].id;
|
||||
crate::app_db::open().unwrap().execute_batch(&format!("CREATE TRIGGER reject_official_p1 BEFORE UPDATE ON provider_failover WHEN json_extract(NEW.record_json,'$.journals[#-1].primaryId') = '{target}' BEGIN SELECT RAISE(ABORT,'fixture-journal-failure'); END;")).unwrap();
|
||||
let result = save_settings(fixture.scope(), settings);
|
||||
crate::app_db::open()
|
||||
.unwrap()
|
||||
.execute_batch("DROP TRIGGER reject_official_p1")
|
||||
.unwrap();
|
||||
assert!(result
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("fixture-journal-failure"));
|
||||
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);
|
||||
assert!(!get_status(fixture.scope()).unwrap().running);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_persisted_settings_restore_direct_without_restarting_listener() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let runtime = lock_manager().unwrap().remove(&fixture.dir).unwrap();
|
||||
runtime.proxy.shutdown();
|
||||
let mut record = load_record(&fixture.dir).unwrap();
|
||||
record.settings.tuning.max_retries = 11;
|
||||
save_record(&fixture.dir, &record).unwrap();
|
||||
initialize().unwrap();
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(!status.running && !status.takeover_active);
|
||||
assert!(!fixture.text().contains("http://127.0.0.1:"));
|
||||
assert!(status.message.unwrap().contains("路由设置需要检查"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_status_write_failure_keeps_the_attached_listener_alive() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
shutdown_all().unwrap();
|
||||
let conn = crate::app_db::open().unwrap();
|
||||
conn.execute_batch("CREATE TRIGGER reject_redundant_status BEFORE UPDATE ON provider_failover WHEN NEW.record_json=OLD.record_json BEGIN SELECT RAISE(ABORT,'fixture-status-failure'); END;").unwrap();
|
||||
SHUTTING_DOWN.store(false, Ordering::Release);
|
||||
let result = initialize();
|
||||
conn.execute_batch("DROP TRIGGER reject_redundant_status")
|
||||
.unwrap();
|
||||
assert!(result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("fixture-status-failure"));
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(status.running && status.takeover_active);
|
||||
assert!(fixture.text().contains("http://127.0.0.1:"));
|
||||
assert!(std::net::TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, fixture.port)).is_ok());
|
||||
stop(&fixture);
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
use super::*;
|
||||
|
||||
struct OwnedRouteFixture {
|
||||
dir: PathBuf,
|
||||
raw: String,
|
||||
local_token: String,
|
||||
}
|
||||
|
||||
impl OwnedRouteFixture {
|
||||
fn new() -> Self {
|
||||
let unique = format!(
|
||||
"{}-{}",
|
||||
std::process::id(),
|
||||
Local::now().timestamp_nanos_opt().unwrap()
|
||||
);
|
||||
let dir = std::env::temp_dir().join(format!("codex-x-failover-integration-{unique}"));
|
||||
fs::create_dir_all(&dir).expect("create isolated Codex directory");
|
||||
let local_token = format!("local-token-{unique}");
|
||||
let original = r#"name = "Primary"
|
||||
base_url = "https://primary.example.test/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
experimental_bearer_token = "real-test-key"
|
||||
supports_websockets = true
|
||||
"#;
|
||||
let raw = format!(
|
||||
r#"model_provider = "custom"
|
||||
model = "test-model"
|
||||
model_reasoning_effort = "high"
|
||||
|
||||
[model_providers.custom]
|
||||
name = "Primary"
|
||||
base_url = "http://127.0.0.1:45555/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
experimental_bearer_token = "{local_token}"
|
||||
supports_websockets = false
|
||||
request_max_retries = 0
|
||||
stream_max_retries = 0
|
||||
|
||||
[mcp_servers.example]
|
||||
command = "local-fixture-command"
|
||||
"#
|
||||
);
|
||||
fs::write(config_path(&dir), &raw).expect("write synthetic local route");
|
||||
let record = json!({
|
||||
"settings": {"enabled":false,"providerIds":[]},
|
||||
"journals": [{"primaryId":"fixture-primary", "providerKey":"custom",
|
||||
"originalTable":original, "port":45555, "token":local_token}],
|
||||
});
|
||||
app_db::open()
|
||||
.expect("open isolated test store")
|
||||
.execute(
|
||||
"INSERT INTO provider_failover (codex_dir, record_json) VALUES (?1, ?2)",
|
||||
params![paths::normalized_path_scope(&dir), record.to_string()],
|
||||
)
|
||||
.expect("seed owned route journal");
|
||||
Self {
|
||||
dir,
|
||||
raw,
|
||||
local_token,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OwnedRouteFixture {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(conn) = app_db::open() {
|
||||
let _ = conn.execute(
|
||||
"DELETE FROM provider_failover WHERE codex_dir = ?1",
|
||||
[paths::normalized_path_scope(&self.dir)],
|
||||
);
|
||||
}
|
||||
let _ = fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_route_state_detection_and_drafts_use_original_provider_without_writes() {
|
||||
let fixture = OwnedRouteFixture::new();
|
||||
let mut detected = providers::detected_live_custom_provider(&fixture.dir)
|
||||
.expect("detect logical provider")
|
||||
.expect("third-party provider");
|
||||
assert_eq!(detected.base_url, "https://primary.example.test/v1");
|
||||
assert_eq!(detected.api_key.as_deref(), Some("real-test-key"));
|
||||
assert!(!detected
|
||||
.toml_config
|
||||
.as_deref()
|
||||
.unwrap()
|
||||
.contains(&fixture.local_token));
|
||||
detected.toml_config = None;
|
||||
let draft = build_provider_toml_draft_inner(detected, Some(fixture.dir.display().to_string()))
|
||||
.expect("inherit direct route in editor draft");
|
||||
assert!(!draft.contains("127.0.0.1"));
|
||||
assert!(!draft.contains(&fixture.local_token));
|
||||
assert!(draft.contains("local-fixture-command"));
|
||||
let state =
|
||||
build_state_after_migration(fixture.dir.clone()).expect("read logical application state");
|
||||
let state_json = serde_json::to_value(&state).expect("serialize public state");
|
||||
assert_eq!(
|
||||
state_json["providers"][0]["baseUrl"],
|
||||
"https://primary.example.test/v1"
|
||||
);
|
||||
assert_eq!(state.model.as_deref(), Some("test-model"));
|
||||
assert_eq!(
|
||||
fs::read_to_string(config_path(&fixture.dir)).unwrap(),
|
||||
fixture.raw
|
||||
);
|
||||
assert!(!auth_path(&fixture.dir).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_managed_toml_submission_restores_owned_route_but_preserves_new_api_key() {
|
||||
let fixture = OwnedRouteFixture::new();
|
||||
for (input_key, expected_key) in [
|
||||
(
|
||||
Some(fixture.local_token.clone()),
|
||||
Some("real-test-key".to_string()),
|
||||
),
|
||||
(
|
||||
Some("new-user-key".to_string()),
|
||||
Some("new-user-key".to_string()),
|
||||
),
|
||||
(
|
||||
Some(format!(" {} ", fixture.local_token)),
|
||||
Some("real-test-key".to_string()),
|
||||
),
|
||||
(None, None),
|
||||
] {
|
||||
let input = direct_provider_toml_input(ProviderTomlInput {
|
||||
config_dir: Some(fixture.dir.display().to_string()),
|
||||
config_text: fixture.raw.replace("\"high\"", "\"low\""),
|
||||
api_key: input_key,
|
||||
})
|
||||
.expect("unwrap stale editor payload");
|
||||
assert_eq!(input.api_key, expected_key);
|
||||
let doc = input
|
||||
.config_text
|
||||
.parse::<DocumentMut>()
|
||||
.expect("parse direct payload");
|
||||
assert_eq!(doc["model_reasoning_effort"].as_str(), Some("low"));
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["base_url"].as_str(),
|
||||
Some("https://primary.example.test/v1")
|
||||
);
|
||||
assert!(!input.config_text.contains(&fixture.local_token));
|
||||
assert!(input.config_text.contains("local-fixture-command"));
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read_to_string(config_path(&fixture.dir)).unwrap(),
|
||||
fixture.raw
|
||||
);
|
||||
assert!(!auth_path(&fixture.dir).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_unwrap_handles_multiple_owned_tables_before_detecting_selected_provider() {
|
||||
let mut fixture = OwnedRouteFixture::new();
|
||||
let second_original = "name = \"Inactive\"\nbase_url = \"https://secondary.example.test/v1\"\nwire_api = \"responses\"\nrequires_openai_auth = false\nexperimental_bearer_token = \"secondary-test-key\"\n";
|
||||
fixture.raw.push_str("\n[model_providers.inactive]\nname = \"Inactive\"\nbase_url = \"http://127.0.0.1:45556/v1\"\nwire_api = \"responses\"\nrequires_openai_auth = false\nexperimental_bearer_token = \"secondary-local-token\"\n");
|
||||
fs::write(config_path(&fixture.dir), &fixture.raw).expect("write second local table");
|
||||
let conn = app_db::open().expect("read fixture store");
|
||||
let scope = paths::normalized_path_scope(&fixture.dir);
|
||||
let text: String = conn
|
||||
.query_row(
|
||||
"SELECT record_json FROM provider_failover WHERE codex_dir = ?1",
|
||||
[&scope],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.expect("read recovery journal");
|
||||
let mut record: Value = serde_json::from_str(&text).expect("parse recovery journal");
|
||||
record["journals"].as_array_mut().unwrap().push(json!({
|
||||
"primaryId":"inactive", "providerKey":"inactive", "originalTable":second_original,
|
||||
"port":45556, "token":"secondary-local-token"
|
||||
}));
|
||||
conn.execute(
|
||||
"UPDATE provider_failover SET record_json = ?1 WHERE codex_dir = ?2",
|
||||
params![record.to_string(), scope],
|
||||
)
|
||||
.expect("append recovery identity");
|
||||
drop(conn);
|
||||
let detected = providers::detected_live_custom_provider(&fixture.dir)
|
||||
.expect("detect selected provider")
|
||||
.expect("selected third-party provider");
|
||||
assert_eq!(detected.base_url, "https://primary.example.test/v1");
|
||||
assert_eq!(detected.api_key.as_deref(), Some("real-test-key"));
|
||||
assert!(!detected.toml_config.unwrap().contains("127.0.0.1"));
|
||||
assert_eq!(
|
||||
fs::read_to_string(config_path(&fixture.dir)).unwrap(),
|
||||
fixture.raw
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_owned_route_keeps_official_status_quota_refresh_and_snapshot_credentials_scoped() {
|
||||
let _guard = app_db::test_db_guard();
|
||||
let mut fixture = OwnedRouteFixture::new();
|
||||
let original = "name = 'OpenAI'\nwire_api = 'responses'\nrequires_openai_auth = true\nsupports_websockets = true\n";
|
||||
fixture.raw = format!("model_provider='custom'\nmodel='official-model'\n[model_providers.custom]\nname='OpenAI'\nwire_api='responses'\nrequires_openai_auth=true\nsupports_websockets=false\nbase_url='http://127.0.0.1:45555/v1'\nhttp_headers={{'x-codex-x-route-token'='{}'}}\n[mcp_servers.keep]\ncommand='keep-native-mcp'\n", fixture.local_token);
|
||||
fs::write(config_path(&fixture.dir), &fixture.raw).unwrap();
|
||||
let record = json!({
|
||||
"version":2,
|
||||
"settings":{"routerEnabled":false,"takeoverEnabled":false,"autoFailoverEnabled":false,"providerIds":[]},
|
||||
"journals":[{"primaryId":"official:openai-official","providerKey":"custom","originalTable":original,
|
||||
"listenAddress":"127.0.0.1","port":45555,"token":fixture.local_token,"official":true,"tableExisted":true,"providersExisted":true}]
|
||||
});
|
||||
app_db::open()
|
||||
.unwrap()
|
||||
.execute(
|
||||
"UPDATE provider_failover SET record_json=?1 WHERE codex_dir=?2",
|
||||
params![
|
||||
record.to_string(),
|
||||
paths::normalized_path_scope(&fixture.dir)
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let auth = json!({"auth_mode":"chatgpt","tokens":{"access_token":"native-current-access","refresh_token":"native-refresh","account_id":"native-account"}});
|
||||
fs::write(auth_path(&fixture.dir), auth.to_string()).unwrap();
|
||||
let config_before = fs::read(config_path(&fixture.dir)).unwrap();
|
||||
let auth_before = fs::read(auth_path(&fixture.dir)).unwrap();
|
||||
let state = build_state_after_migration(fixture.dir.clone()).unwrap();
|
||||
assert!(state.is_official_provider);
|
||||
assert_eq!(
|
||||
state.active_official_profile_id.as_deref(),
|
||||
Some("openai-official")
|
||||
);
|
||||
assert!(providers::detected_live_custom_provider(&fixture.dir)
|
||||
.unwrap()
|
||||
.is_none());
|
||||
let profiles = list_official_profiles_inner(Some(fixture.dir.display().to_string())).unwrap();
|
||||
assert!(profiles[0].is_current);
|
||||
assert!(profiles[0].can_query_quota);
|
||||
let credentials = providers::official_profiles::official_profile_quota_credentials(
|
||||
&fixture.dir,
|
||||
"openai-official",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(credentials.access_token, "native-current-access");
|
||||
let route = failover::native_official::route_for_current(&fixture.dir)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(route.api_key.is_none());
|
||||
let spec = route.official.unwrap();
|
||||
assert!(failover::native_official::verify_request(
|
||||
&spec,
|
||||
"Bearer native-current-access",
|
||||
Some("native-account")
|
||||
)
|
||||
.is_ok());
|
||||
assert_eq!(fs::read(config_path(&fixture.dir)).unwrap(), config_before);
|
||||
assert_eq!(fs::read(auth_path(&fixture.dir)).unwrap(), auth_before);
|
||||
let refreshed = json!({"auth_mode":"chatgpt","tokens":{"access_token":"native-refreshed-access","refresh_token":"native-refreshed-refresh","account_id":"native-account"}});
|
||||
fs::write(auth_path(&fixture.dir), refreshed.to_string()).unwrap();
|
||||
assert_eq!(
|
||||
providers::official_profiles::official_profile_quota_credentials(
|
||||
&fixture.dir,
|
||||
"openai-official"
|
||||
)
|
||||
.unwrap()
|
||||
.access_token,
|
||||
"native-refreshed-access"
|
||||
);
|
||||
assert!(failover::native_official::verify_request(
|
||||
&spec,
|
||||
"Bearer native-current-access",
|
||||
Some("native-account")
|
||||
)
|
||||
.is_err());
|
||||
assert!(failover::native_official::verify_request(
|
||||
&spec,
|
||||
"Bearer native-refreshed-access",
|
||||
Some("native-account")
|
||||
)
|
||||
.is_ok());
|
||||
assert!(providers::capture_live_chatgpt_config(&fixture.dir).unwrap());
|
||||
let snapshot_path = providers::official_snapshot_path_for_test(&fixture.dir).unwrap();
|
||||
let snapshot: Value = serde_json::from_slice(&fs::read(&snapshot_path).unwrap()).unwrap();
|
||||
let saved_config = snapshot["config"].as_str().unwrap();
|
||||
assert!(!saved_config.contains("127.0.0.1"));
|
||||
assert!(!saved_config.contains("x-codex-x-route-token"));
|
||||
assert!(!saved_config.contains(&fixture.local_token));
|
||||
assert!(saved_config.contains("keep-native-mcp"));
|
||||
assert_eq!(
|
||||
snapshot["auth"]["tokens"]["access_token"],
|
||||
"native-refreshed-access"
|
||||
);
|
||||
assert_eq!(fs::read(config_path(&fixture.dir)).unwrap(), config_before);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<Value>(&fs::read(auth_path(&fixture.dir)).unwrap()).unwrap(),
|
||||
refreshed
|
||||
);
|
||||
fs::remove_file(snapshot_path).unwrap();
|
||||
}
|
||||
@@ -2,6 +2,7 @@ use crate::error::{CodexxError, Result};
|
||||
use chrono::Local;
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use toml_edit::DocumentMut;
|
||||
@@ -107,6 +108,30 @@ pub(crate) fn read_to_string_if_exists(path: &Path) -> Result<String> {
|
||||
fs::read_to_string(path).map_err(|e| io_err(path, e))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn harden_sensitive_file_permissions(path: &Path) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let metadata = match fs::metadata(path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(io_err(path, error)),
|
||||
};
|
||||
if !metadata.is_file() || metadata.permissions().mode() & 0o777 == 0o600 {
|
||||
return Ok(());
|
||||
}
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o600))
|
||||
.map_err(|error| io_err(path, error))?;
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let _ = path;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn parse_toml_document(path: &Path, text: &str) -> Result<DocumentMut> {
|
||||
if text.trim().is_empty() {
|
||||
return Ok(DocumentMut::new());
|
||||
@@ -117,7 +142,55 @@ pub(crate) fn parse_toml_document(path: &Path, text: &str) -> Result<DocumentMut
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
fn atomic_write_mode(path: &Path) -> Option<u32> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let sensitive = path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| matches!(name, "config.toml" | "auth.json"));
|
||||
if sensitive {
|
||||
return Some(0o600);
|
||||
}
|
||||
fs::metadata(path)
|
||||
.ok()
|
||||
.map(|metadata| metadata.permissions().mode() & 0o777)
|
||||
}
|
||||
|
||||
fn create_atomic_temp(path: &Path, tmp: &Path, private: bool) -> Result<fs::File> {
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
|
||||
let mode = private.then_some(0o600).or_else(|| atomic_write_mode(path));
|
||||
if let Some(mode) = mode {
|
||||
options.mode(mode);
|
||||
let file = options.open(tmp).map_err(|error| io_err(tmp, error))?;
|
||||
fs::set_permissions(tmp, fs::Permissions::from_mode(mode))
|
||||
.map_err(|error| io_err(tmp, error))?;
|
||||
return Ok(file);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let _ = private;
|
||||
|
||||
options.open(tmp).map_err(|error| io_err(tmp, error))
|
||||
}
|
||||
|
||||
fn atomic_write_with_privacy_and_check<F>(
|
||||
path: &Path,
|
||||
bytes: &[u8],
|
||||
private: bool,
|
||||
pre_commit: F,
|
||||
) -> Result<()>
|
||||
where
|
||||
F: FnOnce() -> Result<()>,
|
||||
{
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static WRITE_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
if let Some(parent) = path.parent() {
|
||||
@@ -129,13 +202,29 @@ pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
Local::now().timestamp_nanos_opt().unwrap_or_default(),
|
||||
WRITE_COUNTER.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
{
|
||||
let mut file = fs::File::create(&tmp).map_err(|e| io_err(&tmp, e))?;
|
||||
let result = (|| {
|
||||
let mut file = create_atomic_temp(path, &tmp, private)?;
|
||||
file.write_all(bytes).map_err(|e| io_err(&tmp, e))?;
|
||||
file.sync_all().map_err(|e| io_err(&tmp, e))?;
|
||||
drop(file);
|
||||
pre_commit()?;
|
||||
fs::rename(&tmp, path).map_err(|e| io_err(path, e))
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
fs::rename(&tmp, path).map_err(|e| io_err(path, e))?;
|
||||
Ok(())
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
atomic_write_with_privacy_and_check(path, bytes, false, || Ok(()))
|
||||
}
|
||||
|
||||
pub(crate) fn atomic_write_checked<F>(path: &Path, bytes: &[u8], pre_commit: F) -> Result<()>
|
||||
where
|
||||
F: FnOnce() -> Result<()>,
|
||||
{
|
||||
atomic_write_with_privacy_and_check(path, bytes, false, pre_commit)
|
||||
}
|
||||
|
||||
pub(crate) fn write_text(path: &Path, text: &str) -> Result<()> {
|
||||
@@ -147,6 +236,11 @@ pub(crate) fn write_json(path: &Path, value: &Value) -> Result<()> {
|
||||
write_text(path, &(text + "\n"))
|
||||
}
|
||||
|
||||
pub(crate) fn write_private_json(path: &Path, value: &Value) -> Result<()> {
|
||||
let text = serde_json::to_string_pretty(value).map_err(|e| json_err(path, e))?;
|
||||
atomic_write_with_privacy_and_check(path, (text + "\n").as_bytes(), true, || Ok(()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -182,6 +276,91 @@ mod tests {
|
||||
fs::remove_dir_all(dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checked_atomic_write_rejects_a_change_immediately_before_replace() {
|
||||
let dir = temp_dir("checked-race");
|
||||
let path = dir.join("config.toml");
|
||||
fs::write(&path, b"old").expect("write original file");
|
||||
|
||||
let error = atomic_write_checked(&path, b"codex-x", || {
|
||||
fs::write(&path, b"external").expect("simulate external writer");
|
||||
Err(CodexxError::Config("stale snapshot".to_string()))
|
||||
})
|
||||
.expect_err("stale checked write must fail");
|
||||
|
||||
assert!(error.to_string().contains("stale snapshot"));
|
||||
assert_eq!(fs::read(&path).expect("read external value"), b"external");
|
||||
assert_eq!(fs::read_dir(&dir).expect("read directory").count(), 1);
|
||||
fs::remove_dir_all(dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn atomic_write_restricts_sensitive_codex_files_and_preserves_other_modes() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = temp_dir("permissions");
|
||||
let config = dir.join("config.toml");
|
||||
let auth = dir.join("auth.json");
|
||||
let script = dir.join("tool.sh");
|
||||
for path in [&config, &auth, &script] {
|
||||
fs::write(path, b"old").expect("seed file");
|
||||
}
|
||||
fs::set_permissions(&config, fs::Permissions::from_mode(0o644)).expect("set config mode");
|
||||
fs::set_permissions(&auth, fs::Permissions::from_mode(0o644)).expect("set auth mode");
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).expect("set script mode");
|
||||
|
||||
atomic_write(&config, b"new config").expect("replace config");
|
||||
atomic_write(&auth, b"new auth").expect("replace auth");
|
||||
atomic_write(&script, b"new script").expect("replace script");
|
||||
|
||||
let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode(&config), 0o600);
|
||||
assert_eq!(mode(&auth), 0o600);
|
||||
assert_eq!(mode(&script), 0o755);
|
||||
fs::remove_dir_all(dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn harden_sensitive_permissions_updates_existing_files_without_creating_missing_files() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = temp_dir("harden-permissions");
|
||||
let config = dir.join("config.toml");
|
||||
let missing = dir.join("auth.json");
|
||||
fs::write(&config, b"model = \"gpt\"\n").expect("seed config");
|
||||
fs::set_permissions(&config, fs::Permissions::from_mode(0o644)).expect("set open mode");
|
||||
|
||||
harden_sensitive_file_permissions(&config).expect("harden config");
|
||||
harden_sensitive_file_permissions(&missing).expect("ignore missing auth");
|
||||
|
||||
assert_eq!(
|
||||
fs::metadata(&config).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
assert!(!missing.exists());
|
||||
fs::remove_dir_all(dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn private_json_is_private_from_its_first_atomic_write() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = temp_dir("private-json");
|
||||
let path = dir.join("official-snapshot.json");
|
||||
|
||||
write_private_json(&path, &serde_json::json!({"token": "secret"}))
|
||||
.expect("write private JSON");
|
||||
|
||||
assert_eq!(
|
||||
fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
fs::remove_dir_all(dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ensure_directory_accepts_existing_and_missing_directories() {
|
||||
let root = temp_dir("ensure-directory");
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::{atomic_write_checked, ensure_directory, io_err};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) struct LiveConfigLock {
|
||||
file: fs::File,
|
||||
}
|
||||
|
||||
impl Drop for LiveConfigLock {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.file.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn acquire_live_config_lock(codex_dir: &Path) -> Result<LiveConfigLock> {
|
||||
let tmp_dir = codex_dir.join("tmp");
|
||||
ensure_directory(&tmp_dir)?;
|
||||
let path = tmp_dir.join("codex-x-live-config.lock");
|
||||
if path.is_dir() {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"Codex live 配置锁被同名目录占用: {}",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.map_err(|error| io_err(&path, error))?;
|
||||
file.try_lock().map_err(|_| {
|
||||
CodexxError::Config(format!(
|
||||
"另一个 Codex-X 正在修改 Codex live 配置,请稍后重试: {}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
file.set_len(0).map_err(|error| io_err(&path, error))?;
|
||||
writeln!(file, "pid={}", std::process::id()).map_err(|error| io_err(&path, error))?;
|
||||
file.sync_all().map_err(|error| io_err(&path, error))?;
|
||||
Ok(LiveConfigLock { file })
|
||||
}
|
||||
|
||||
pub(crate) fn read_file_snapshot(path: &Path) -> Result<Option<Vec<u8>>> {
|
||||
match fs::read(path) {
|
||||
Ok(bytes) => Ok(Some(bytes)),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(error) => Err(io_err(path, error)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn text_from_snapshot(path: &Path, snapshot: Option<&[u8]>) -> Result<String> {
|
||||
String::from_utf8(snapshot.unwrap_or_default().to_vec())
|
||||
.map_err(|_| CodexxError::Config(format!("{} 不是有效的 UTF-8 文本", path.display())))
|
||||
}
|
||||
|
||||
pub(crate) fn ensure_file_snapshot_unchanged(path: &Path, expected: Option<&[u8]>) -> Result<()> {
|
||||
if read_file_snapshot(path)?.as_deref() == expected {
|
||||
return Ok(());
|
||||
}
|
||||
Err(CodexxError::Config(format!(
|
||||
"{} 已被其他程序修改,本次写入已取消,请刷新后重试",
|
||||
path.display()
|
||||
)))
|
||||
}
|
||||
|
||||
pub(crate) fn atomic_write_if_unchanged(
|
||||
path: &Path,
|
||||
expected: Option<&[u8]>,
|
||||
replacement: &[u8],
|
||||
) -> Result<()> {
|
||||
atomic_write_checked(path, replacement, || {
|
||||
ensure_file_snapshot_unchanged(path, expected)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn remove_file_if_unchanged(path: &Path, expected: Option<&[u8]>) -> Result<()> {
|
||||
ensure_file_snapshot_unchanged(path, expected)?;
|
||||
match fs::remove_file(path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(io_err(path, error)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn restore_file_snapshot_if_unchanged(
|
||||
path: &Path,
|
||||
expected_current: Option<&[u8]>,
|
||||
snapshot: Option<&[u8]>,
|
||||
) -> Result<()> {
|
||||
match snapshot {
|
||||
Some(bytes) => atomic_write_if_unchanged(path, expected_current, bytes),
|
||||
None => remove_file_if_unchanged(path, expected_current),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct AppliedFileChange {
|
||||
path: std::path::PathBuf,
|
||||
before: Option<Vec<u8>>,
|
||||
after: Option<Vec<u8>>,
|
||||
changed: bool,
|
||||
}
|
||||
|
||||
impl AppliedFileChange {
|
||||
pub(crate) fn rollback(&self) -> Result<()> {
|
||||
if !self.changed {
|
||||
return Ok(());
|
||||
}
|
||||
restore_file_snapshot_if_unchanged(
|
||||
&self.path,
|
||||
self.after.as_deref(),
|
||||
self.before.as_deref(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply_file_change(
|
||||
path: &Path,
|
||||
before: Option<Vec<u8>>,
|
||||
after: Option<Vec<u8>>,
|
||||
) -> Result<AppliedFileChange> {
|
||||
let changed = before != after;
|
||||
if changed {
|
||||
match after.as_deref() {
|
||||
Some(bytes) => atomic_write_if_unchanged(path, before.as_deref(), bytes)?,
|
||||
None => remove_file_if_unchanged(path, before.as_deref())?,
|
||||
}
|
||||
}
|
||||
Ok(AppliedFileChange {
|
||||
path: path.to_path_buf(),
|
||||
before,
|
||||
after,
|
||||
changed,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn rollback_file_changes(changes: &[AppliedFileChange]) -> Result<()> {
|
||||
for change in changes.iter().filter(|change| change.changed) {
|
||||
ensure_file_snapshot_unchanged(&change.path, change.after.as_deref())?;
|
||||
}
|
||||
|
||||
let mut failures = Vec::new();
|
||||
for change in changes.iter().rev() {
|
||||
if let Err(error) = change.rollback() {
|
||||
failures.push(error.to_string());
|
||||
}
|
||||
}
|
||||
if failures.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CodexxError::Config(failures.join(";")))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fail_with_file_rollback<T>(
|
||||
error: CodexxError,
|
||||
changes: &[AppliedFileChange],
|
||||
) -> Result<T> {
|
||||
match rollback_file_changes(changes) {
|
||||
Ok(()) => Err(error),
|
||||
Err(rollback_error) => Err(CodexxError::Config(format!(
|
||||
"{error};文件回滚失败:{rollback_error}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
fn temp_dir(name: &str) -> std::path::PathBuf {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"codex-x-live-config-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create test directory");
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_rejects_a_second_writer_and_releases_on_drop() {
|
||||
let dir = temp_dir("lock");
|
||||
let first = acquire_live_config_lock(&dir).expect("acquire first lock");
|
||||
let error = acquire_live_config_lock(&dir)
|
||||
.err()
|
||||
.expect("second lock must fail");
|
||||
assert!(error.to_string().contains("另一个 Codex-X"));
|
||||
drop(first);
|
||||
acquire_live_config_lock(&dir).expect("lock is released on drop");
|
||||
fs::remove_dir_all(dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_checked_write_preserves_the_external_value() {
|
||||
let dir = temp_dir("stale");
|
||||
let path = dir.join("config.toml");
|
||||
fs::write(&path, b"old").expect("seed file");
|
||||
let old = read_file_snapshot(&path).expect("capture file");
|
||||
fs::write(&path, b"external").expect("simulate external writer");
|
||||
|
||||
atomic_write_if_unchanged(&path, old.as_deref(), b"codex-x")
|
||||
.expect_err("stale write must fail");
|
||||
|
||||
assert_eq!(fs::read(&path).expect("read file"), b"external");
|
||||
fs::remove_dir_all(dir).expect("remove test directory");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::error::{CodexxError, Result};
|
||||
#[cfg(test)]
|
||||
use chrono::Local;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) fn home_dir() -> Result<PathBuf> {
|
||||
dirs::home_dir().ok_or(CodexxError::NoHomeDir)
|
||||
@@ -33,3 +33,13 @@ pub(crate) fn app_home() -> Result<PathBuf> {
|
||||
Ok(home_dir()?.join(".codexx"))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn normalized_path_scope(path: &Path) -> String {
|
||||
let resolved = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
|
||||
let normalized = resolved.to_string_lossy().replace('\\', "/");
|
||||
if cfg!(target_os = "windows") {
|
||||
normalized.to_ascii_lowercase()
|
||||
} else {
|
||||
normalized
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
use super::store::normalize_prompt_filename;
|
||||
use super::store::{
|
||||
builtin_prompt_override_ids_inner, builtin_prompt_override_inner, normalize_prompt_filename,
|
||||
};
|
||||
use super::types::{
|
||||
BuiltinPromptStatus, BundledPromptMeta, CachedBuiltinPrompt, GithubContentEntry,
|
||||
BuiltinPromptDetail, BuiltinPromptStatus, BundledPromptMeta, CachedBuiltinPrompt,
|
||||
GithubContentEntry,
|
||||
};
|
||||
use crate::constants::{
|
||||
GITHUB_EXAMPLES_API, GITHUB_EXAMPLES_BASE, INSTRUCTION_54_CONTENT, INSTRUCTION_54_FILENAME,
|
||||
@@ -20,7 +23,8 @@ use serde::Deserialize;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Mutex;
|
||||
|
||||
static BUILTIN_PROMPT_CACHE_LOCK: Mutex<()> = Mutex::new(());
|
||||
// Only serialize remote syncs. Local reads must stay available during downloads.
|
||||
static BUILTIN_PROMPT_SYNC_LOCK: Mutex<()> = Mutex::new(());
|
||||
const CATALOG_CDN_KEY: &str = "模板 CDN";
|
||||
const CATALOG_GITHUB_KEY: &str = "GitHub 模板目录";
|
||||
const PROMPT_CDN_KEY: &str = "模板 CDN";
|
||||
@@ -140,6 +144,42 @@ pub(crate) fn stable_remote_prompt_id(filename: &str) -> String {
|
||||
}
|
||||
|
||||
fn prompt_display_meta(filename: &str) -> (String, String, String) {
|
||||
let curated = match filename.to_ascii_lowercase().as_str() {
|
||||
"software-development-maintainer.md" => Some((
|
||||
"长期维护工程师",
|
||||
"正式项目的最小改动、复用、测试与安全规范",
|
||||
"软件开发",
|
||||
)),
|
||||
"software-development-debugging.md" => Some((
|
||||
"系统化调试与根因修复",
|
||||
"从稳定复现、证据采集到最小修复与回归验证",
|
||||
"软件开发",
|
||||
)),
|
||||
"software-development-code-review.md" => Some((
|
||||
"严格代码审查",
|
||||
"按严重级别发现缺陷、回归、安全风险与测试缺口",
|
||||
"软件开发",
|
||||
)),
|
||||
"writing-clarity-editor.md" => Some((
|
||||
"清晰表达与润色",
|
||||
"保留原意与事实,优化中文或英文的结构、语气和可读性",
|
||||
"写作辅助",
|
||||
)),
|
||||
"writing-technical-docs.md" => Some((
|
||||
"技术文档写作",
|
||||
"基于代码和事实编写 README、指南、API 与变更文档",
|
||||
"写作辅助",
|
||||
)),
|
||||
"writing-structured-draft.md" => Some((
|
||||
"结构化长文起草",
|
||||
"把零散材料整理为提纲清晰、论证连贯的完整初稿",
|
||||
"写作辅助",
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((title, subtitle, badge)) = curated {
|
||||
return (title.to_string(), subtitle.to_string(), badge.to_string());
|
||||
}
|
||||
if let Some(meta) = bundled_prompt_metas()
|
||||
.into_iter()
|
||||
.find(|item| item.filename.eq_ignore_ascii_case(filename))
|
||||
@@ -266,6 +306,13 @@ pub(crate) fn delete_cached_prompt_ids(
|
||||
|
||||
fn prune_builtin_prompt_cache(active_ids: &HashSet<String>) -> Result<usize> {
|
||||
let mut conn = open_db()?;
|
||||
prune_builtin_prompt_cache_on_connection(&mut conn, active_ids)
|
||||
}
|
||||
|
||||
fn prune_builtin_prompt_cache_on_connection(
|
||||
conn: &mut Connection,
|
||||
active_ids: &HashSet<String>,
|
||||
) -> Result<usize> {
|
||||
let transaction = conn
|
||||
.transaction_with_behavior(TransactionBehavior::Immediate)
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
@@ -276,7 +323,14 @@ fn prune_builtin_prompt_cache(active_ids: &HashSet<String>) -> Result<usize> {
|
||||
let mut deleted = 0;
|
||||
for id in stale_ids {
|
||||
deleted += transaction
|
||||
.execute("DELETE FROM builtin_prompt_cache WHERE id = ?1", [id])
|
||||
.execute(
|
||||
"DELETE FROM builtin_prompt_cache
|
||||
WHERE id = ?1
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM builtin_prompt_overrides WHERE template_id = ?1
|
||||
)",
|
||||
[id],
|
||||
)
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
}
|
||||
transaction
|
||||
@@ -455,6 +509,22 @@ fn fetch_github_prompt_catalog() -> Result<RemotePromptCatalog> {
|
||||
fetch_first_valid(&sources, parse_prompt_catalog)
|
||||
}
|
||||
|
||||
fn confirm_prompt_catalog_with<Fetch>(
|
||||
catalog: RemotePromptCatalog,
|
||||
fetch_authoritative: Fetch,
|
||||
) -> (RemotePromptCatalog, bool)
|
||||
where
|
||||
Fetch: FnOnce() -> Result<RemotePromptCatalog>,
|
||||
{
|
||||
if catalog.authoritative {
|
||||
return (catalog, false);
|
||||
}
|
||||
match fetch_authoritative() {
|
||||
Ok(authoritative) => (authoritative, false),
|
||||
Err(_) => (catalog, true),
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_status_from_cache(cache: CachedBuiltinPrompt, message: &str) -> BuiltinPromptStatus {
|
||||
let (title, subtitle, badge) = prompt_display_meta(&cache.filename);
|
||||
BuiltinPromptStatus {
|
||||
@@ -470,6 +540,7 @@ fn prompt_status_from_cache(cache: CachedBuiltinPrompt, message: &str) -> Builti
|
||||
sync_issue: None,
|
||||
checked_at: Some(cache.checked_at),
|
||||
message: message.to_string(),
|
||||
customized: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -526,6 +597,7 @@ fn refresh_builtin_prompt_from_source(
|
||||
"已是最新在线模板"
|
||||
}
|
||||
.to_string(),
|
||||
customized: false,
|
||||
})
|
||||
}
|
||||
Err(_) => {
|
||||
@@ -557,6 +629,7 @@ fn refresh_builtin_prompt_from_source(
|
||||
"在线模板暂时不可用,且没有本地副本"
|
||||
}
|
||||
.to_string(),
|
||||
customized: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -576,9 +649,72 @@ fn bundled_prompt_status(meta: BundledPromptMeta, message: &str) -> BuiltinPromp
|
||||
sync_issue: None,
|
||||
checked_at: None,
|
||||
message: message.to_string(),
|
||||
customized: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn customized_prompt_status(id: &str, filename: &str) -> Result<BuiltinPromptStatus> {
|
||||
let mut status = if let Some(cache) = cached_builtin_prompt(id)? {
|
||||
prompt_status_from_cache(cache, "本地已修改,GitHub 同步已跳过")
|
||||
} else if let Some(meta) = bundled_prompt_meta(id) {
|
||||
bundled_prompt_status(meta, "本地已修改,GitHub 同步已跳过")
|
||||
} else {
|
||||
let (title, subtitle, badge) = prompt_display_meta(filename);
|
||||
BuiltinPromptStatus {
|
||||
id: id.to_string(),
|
||||
filename: filename.to_string(),
|
||||
title,
|
||||
subtitle,
|
||||
badge,
|
||||
source_url: builtin_prompt_source_url(filename),
|
||||
cached: false,
|
||||
updated: false,
|
||||
content_source: "local".to_string(),
|
||||
sync_issue: None,
|
||||
checked_at: None,
|
||||
message: "本地已修改,GitHub 同步已跳过".to_string(),
|
||||
customized: true,
|
||||
}
|
||||
};
|
||||
status.customized = true;
|
||||
status.message = "本地已修改,GitHub 同步已跳过".to_string();
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
fn mark_customized_prompt_statuses(
|
||||
statuses: &mut [BuiltinPromptStatus],
|
||||
customized_ids: &HashSet<String>,
|
||||
) {
|
||||
for status in statuses {
|
||||
if customized_ids.contains(&status.id) {
|
||||
status.customized = true;
|
||||
status.message = "本地已修改,GitHub 同步已跳过".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn include_customized_prompt_statuses(
|
||||
statuses: &mut Vec<BuiltinPromptStatus>,
|
||||
customized_ids: &HashSet<String>,
|
||||
caches: Vec<CachedBuiltinPrompt>,
|
||||
) {
|
||||
for cache in caches {
|
||||
if customized_ids.contains(&cache.id)
|
||||
&& !statuses.iter().any(|status| status.id == cache.id)
|
||||
{
|
||||
statuses.push(prompt_status_from_cache(
|
||||
cache,
|
||||
"本地已修改,GitHub 同步已跳过",
|
||||
));
|
||||
}
|
||||
}
|
||||
mark_customized_prompt_statuses(statuses, customized_ids);
|
||||
}
|
||||
|
||||
fn should_sync_prompt_content(id: &str, customized_ids: &HashSet<String>) -> bool {
|
||||
!customized_ids.contains(id)
|
||||
}
|
||||
|
||||
pub(crate) fn cached_prompt_fallback_statuses(
|
||||
caches: Vec<CachedBuiltinPrompt>,
|
||||
) -> Vec<BuiltinPromptStatus> {
|
||||
@@ -621,47 +757,38 @@ pub(crate) fn cached_prompt_fallback_statuses(
|
||||
}
|
||||
|
||||
pub(crate) fn builtin_prompt_status_inner() -> Result<Vec<BuiltinPromptStatus>> {
|
||||
Ok(cached_prompt_fallback_statuses(cached_builtin_prompts()?))
|
||||
let customized_ids = builtin_prompt_override_ids_inner()?;
|
||||
let mut statuses = cached_prompt_fallback_statuses(cached_builtin_prompts()?);
|
||||
mark_customized_prompt_statuses(&mut statuses, &customized_ids);
|
||||
Ok(statuses)
|
||||
}
|
||||
|
||||
pub(crate) fn refresh_builtin_prompts_with_active(
|
||||
active_remote_builtin_prompt_id: impl FnOnce() -> Option<String>,
|
||||
) -> Result<Vec<BuiltinPromptStatus>> {
|
||||
let _cache_guard = BUILTIN_PROMPT_CACHE_LOCK
|
||||
let _sync_guard = BUILTIN_PROMPT_SYNC_LOCK
|
||||
.lock()
|
||||
.map_err(|_| CodexxError::Database("提示词缓存锁已损坏".to_string()))?;
|
||||
let mut catalog = match fetch_prompt_catalog() {
|
||||
let customized_ids = builtin_prompt_override_ids_inner()?;
|
||||
let catalog = match fetch_prompt_catalog() {
|
||||
Ok(catalog) => catalog,
|
||||
Err(_) => {
|
||||
let mut statuses = builtin_prompt_status_inner()?;
|
||||
for status in &mut statuses {
|
||||
status.sync_issue = Some("catalog".to_string());
|
||||
status.message = "在线模板目录暂时不可用,已保留本地内容".to_string();
|
||||
if !status.customized {
|
||||
status.message = "在线模板目录暂时不可用,已保留本地内容".to_string();
|
||||
}
|
||||
}
|
||||
return Ok(statuses);
|
||||
}
|
||||
};
|
||||
let cached_before = cached_builtin_prompts()?;
|
||||
let mut catalog_confirmation_failed = false;
|
||||
if !catalog.authoritative {
|
||||
let cdn_ids = catalog
|
||||
.prompts
|
||||
.iter()
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
let cache_may_be_newer = cached_before
|
||||
.iter()
|
||||
.any(|cache| !cdn_ids.contains(&cache.id));
|
||||
let bundled_missing = bundled_prompt_metas()
|
||||
.into_iter()
|
||||
.any(|meta| !cdn_ids.contains(meta.id));
|
||||
if cache_may_be_newer || bundled_missing {
|
||||
match fetch_github_prompt_catalog() {
|
||||
Ok(authoritative) => catalog = authoritative,
|
||||
Err(_) => catalog_confirmation_failed = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
// A successful CDN response can still contain an old @main directory. Always
|
||||
// confirm directory membership with GitHub so newly added and removed files
|
||||
// become visible immediately; keep the CDN result as the offline fallback.
|
||||
let (catalog, catalog_confirmation_failed) =
|
||||
confirm_prompt_catalog_with(catalog, fetch_github_prompt_catalog);
|
||||
let remote_ids = catalog
|
||||
.prompts
|
||||
.iter()
|
||||
@@ -674,29 +801,46 @@ pub(crate) fn refresh_builtin_prompts_with_active(
|
||||
.collect::<HashSet<_>>();
|
||||
let mut statuses = Vec::new();
|
||||
for (id, filename) in catalog.prompts {
|
||||
let bundled = bundled_prompt_meta(&id).map(|meta| meta.content);
|
||||
statuses.push(refresh_builtin_prompt_from_source(&id, &filename, bundled)?);
|
||||
if !should_sync_prompt_content(&id, &customized_ids) {
|
||||
statuses.push(customized_prompt_status(&id, &filename)?);
|
||||
} else {
|
||||
let bundled = bundled_prompt_meta(&id).map(|meta| meta.content);
|
||||
statuses.push(refresh_builtin_prompt_from_source(&id, &filename, bundled)?);
|
||||
}
|
||||
}
|
||||
for meta in bundled_prompt_metas() {
|
||||
if !remote_ids.contains(meta.id) {
|
||||
statuses.push(bundled_prompt_status(
|
||||
meta,
|
||||
"在线目录暂未提供该模板,使用软件内置版本",
|
||||
));
|
||||
statuses.push(if customized_ids.contains(meta.id) {
|
||||
customized_prompt_status(meta.id, meta.filename)?
|
||||
} else {
|
||||
bundled_prompt_status(meta, "在线目录暂未提供该模板,使用软件内置版本")
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if catalog.authoritative {
|
||||
let mut retained_ids = remote_ids.clone();
|
||||
for customized_id in &customized_ids {
|
||||
retained_ids.insert(customized_id.clone());
|
||||
if !remote_ids.contains(customized_id)
|
||||
&& !statuses.iter().any(|status| status.id == *customized_id)
|
||||
{
|
||||
if let Some(cache) = cached_builtin_prompt(customized_id)? {
|
||||
statuses.push(customized_prompt_status(customized_id, &cache.filename)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(active_id) = active_remote_builtin_prompt_id() {
|
||||
if !remote_ids.contains(&active_id) {
|
||||
if let Some(cache) = cached_builtin_prompt(&active_id)? {
|
||||
let mut status = prompt_status_from_cache(
|
||||
cache,
|
||||
"该在线模板已下架,当前配置继续使用本地副本",
|
||||
);
|
||||
status.content_source = "removed".to_string();
|
||||
statuses.push(status);
|
||||
if !statuses.iter().any(|status| status.id == active_id) {
|
||||
let mut status = prompt_status_from_cache(
|
||||
cache,
|
||||
"该在线模板已下架,当前配置继续使用本地副本",
|
||||
);
|
||||
status.content_source = "removed".to_string();
|
||||
statuses.push(status);
|
||||
}
|
||||
}
|
||||
retained_ids.insert(active_id);
|
||||
}
|
||||
@@ -717,6 +861,10 @@ pub(crate) fn refresh_builtin_prompts_with_active(
|
||||
if catalog_confirmation_failed {
|
||||
mark_catalog_confirmation_failed(&mut statuses);
|
||||
}
|
||||
// Local edits can finish while remote requests are pending. Use their
|
||||
// latest IDs and retained cache entries when returning the catalog.
|
||||
let customized_ids = builtin_prompt_override_ids_inner()?;
|
||||
include_customized_prompt_statuses(&mut statuses, &customized_ids, cached_builtin_prompts()?);
|
||||
let order = bundled_prompt_metas()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
@@ -737,9 +885,8 @@ pub(crate) fn refresh_builtin_prompts_with_active(
|
||||
pub(crate) fn builtin_prompt_content(
|
||||
template_id: &str,
|
||||
) -> Result<(String, String, String, String)> {
|
||||
let _cache_guard = BUILTIN_PROMPT_CACHE_LOCK
|
||||
.lock()
|
||||
.map_err(|_| CodexxError::Database("提示词缓存锁已损坏".to_string()))?;
|
||||
// Editing and enabling a template are local operations. Network refreshes
|
||||
// update SQLite separately, whose reads see the last committed cache entry.
|
||||
let id = if template_id.trim().is_empty() {
|
||||
"gpt5.5-unrestricted"
|
||||
} else {
|
||||
@@ -752,17 +899,12 @@ pub(crate) fn builtin_prompt_content(
|
||||
.map(|item| item.filename.clone())
|
||||
.or_else(|| bundled.map(|item| item.filename.to_string()))
|
||||
.ok_or_else(|| CodexxError::Config(format!("提示词模板不存在或尚未同步: {id}")))?;
|
||||
let trust = PromptContentTrust {
|
||||
cached: cached.as_ref().map(|item| item.content.as_str()),
|
||||
bundled: bundled.map(|item| item.content),
|
||||
};
|
||||
if let Ok((remote, source_url)) = fetch_remote_prompt(&filename, trust) {
|
||||
save_builtin_prompt_cache(id, &filename, &source_url, &remote)?;
|
||||
if let Some(content) = builtin_prompt_override_inner(id)? {
|
||||
return Ok((
|
||||
filename.clone(),
|
||||
format!("./{filename}"),
|
||||
remote,
|
||||
"在线最新".to_string(),
|
||||
content,
|
||||
"本地已修改".to_string(),
|
||||
));
|
||||
}
|
||||
if let Some(cache) = cached {
|
||||
@@ -774,7 +916,9 @@ pub(crate) fn builtin_prompt_content(
|
||||
));
|
||||
}
|
||||
let bundled = bundled.ok_or_else(|| {
|
||||
CodexxError::Config(format!("无法下载提示词且没有可用缓存: {template_id}"))
|
||||
CodexxError::Config(format!(
|
||||
"提示词尚无本地内容,请先同步 GitHub 模板: {template_id}"
|
||||
))
|
||||
})?;
|
||||
Ok((
|
||||
bundled.filename.to_string(),
|
||||
@@ -784,10 +928,112 @@ pub(crate) fn builtin_prompt_content(
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn builtin_prompt_detail_inner(template_id: &str) -> Result<BuiltinPromptDetail> {
|
||||
let id = if template_id.trim().is_empty() {
|
||||
"gpt5.5-unrestricted"
|
||||
} else {
|
||||
template_id.trim()
|
||||
};
|
||||
let (filename, _, content, _) = builtin_prompt_content(id)?;
|
||||
let (title, _, _) = prompt_display_meta(&filename);
|
||||
Ok(BuiltinPromptDetail {
|
||||
id: id.to_string(),
|
||||
filename,
|
||||
title,
|
||||
content,
|
||||
customized: builtin_prompt_override_inner(id)?.is_some(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn local_prompt_detail_does_not_wait_for_background_sync() {
|
||||
let _db_guard = crate::app_db::test_db_guard();
|
||||
let id = "github-detail-during-sync";
|
||||
save_builtin_prompt_cache(
|
||||
id,
|
||||
"detail-during-sync.md",
|
||||
"https://example.test/prompt.md",
|
||||
"cached content",
|
||||
)
|
||||
.expect("cache template");
|
||||
super::super::store::save_builtin_prompt_override_inner(id, "local edit")
|
||||
.expect("save local edit");
|
||||
|
||||
let sync_guard = BUILTIN_PROMPT_SYNC_LOCK
|
||||
.lock()
|
||||
.expect("simulate pending sync");
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let reader = std::thread::spawn(move || {
|
||||
sender.send(builtin_prompt_detail_inner(id)).unwrap();
|
||||
});
|
||||
let detail = receiver.recv_timeout(std::time::Duration::from_secs(1));
|
||||
// Release before asserting so a regression cannot leave a blocked worker.
|
||||
drop(sync_guard);
|
||||
reader.join().expect("finish detail reader");
|
||||
let conn = open_db().expect("open test store");
|
||||
conn.execute(
|
||||
"DELETE FROM builtin_prompt_overrides WHERE template_id = ?1",
|
||||
[id],
|
||||
)
|
||||
.unwrap();
|
||||
conn.execute("DELETE FROM builtin_prompt_cache WHERE id = ?1", [id])
|
||||
.unwrap();
|
||||
|
||||
let detail = detail
|
||||
.expect("local detail must finish while sync is pending")
|
||||
.unwrap();
|
||||
assert_eq!(detail.content, "local edit");
|
||||
assert!(detail.customized);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_and_bundled_prompt_content_stays_available_during_sync() {
|
||||
let _db_guard = crate::app_db::test_db_guard();
|
||||
let id = "github-cached-content-during-sync";
|
||||
save_builtin_prompt_cache(
|
||||
id,
|
||||
"cached-during-sync.md",
|
||||
"https://example.test/prompt.md",
|
||||
"last downloaded content",
|
||||
)
|
||||
.expect("cache online template");
|
||||
let before = cached_builtin_prompt(id).unwrap().unwrap().checked_at;
|
||||
let sync_guard = BUILTIN_PROMPT_SYNC_LOCK
|
||||
.lock()
|
||||
.expect("simulate pending sync");
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let reader = std::thread::spawn(move || {
|
||||
let result = (|| -> Result<_> {
|
||||
Ok((
|
||||
builtin_prompt_content(id)?,
|
||||
builtin_prompt_content("gpt5.5-unrestricted")?,
|
||||
))
|
||||
})();
|
||||
sender.send(result).unwrap();
|
||||
});
|
||||
let result = receiver.recv_timeout(std::time::Duration::from_secs(1));
|
||||
drop(sync_guard);
|
||||
reader.join().expect("finish content reader");
|
||||
let after = cached_builtin_prompt(id).unwrap().unwrap().checked_at;
|
||||
open_db()
|
||||
.unwrap()
|
||||
.execute("DELETE FROM builtin_prompt_cache WHERE id = ?1", [id])
|
||||
.unwrap();
|
||||
|
||||
let (cached, bundled) = result
|
||||
.expect("local content must not wait for sync")
|
||||
.unwrap();
|
||||
assert_eq!(cached.2, "last downloaded content");
|
||||
assert_eq!(cached.3, "本地缓存");
|
||||
assert_eq!(bundled.2, INSTRUCTION_CONTENT);
|
||||
assert_eq!(bundled.3, "打包内置");
|
||||
assert_eq!(before, after, "reading must not refresh the cache");
|
||||
}
|
||||
|
||||
const TEST_SOURCES: [RemoteSource<'static>; 2] = [
|
||||
RemoteSource::new(PROMPT_CDN_KEY, "https://cdn.test/prompt.md", None),
|
||||
RemoteSource::new(PROMPT_GITHUB_KEY, "https://github.test/prompt.md", None),
|
||||
@@ -802,6 +1048,10 @@ mod tests {
|
||||
content TEXT NOT NULL,
|
||||
checked_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE builtin_prompt_overrides (
|
||||
template_id TEXT PRIMARY KEY,
|
||||
content TEXT NOT NULL
|
||||
);",
|
||||
)
|
||||
.expect("create prompt cache table");
|
||||
@@ -813,6 +1063,65 @@ mod tests {
|
||||
conn
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_saved_during_sync_survives_stale_catalog_pruning_and_returned_statuses() {
|
||||
let mut conn = prompt_cache_connection();
|
||||
for id in [
|
||||
"removed-but-edited",
|
||||
"removed-unedited",
|
||||
"remote-still-present",
|
||||
] {
|
||||
save_builtin_prompt_cache_on_connection(
|
||||
&conn,
|
||||
id,
|
||||
&format!("{id}.md"),
|
||||
"https://example.test/prompt.md",
|
||||
"downloaded content",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
// Sync started before this edit, so its original retained IDs omit it.
|
||||
let retained_at_sync_start = HashSet::from(["remote-still-present".to_string()]);
|
||||
conn.execute(
|
||||
"INSERT INTO builtin_prompt_overrides (template_id, content) VALUES (?1, ?2)",
|
||||
["removed-but-edited", "new local content"],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let removed = prune_builtin_prompt_cache_on_connection(&mut conn, &retained_at_sync_start)
|
||||
.expect("prune the old catalog after the local save");
|
||||
assert_eq!(removed, 1);
|
||||
let cache = cached_builtin_prompt_from_connection(&conn, "removed-but-edited")
|
||||
.unwrap()
|
||||
.expect("keep the filename needed to reopen the saved edit");
|
||||
assert_eq!(cache.filename, "removed-but-edited.md");
|
||||
assert!(
|
||||
cached_builtin_prompt_from_connection(&conn, "removed-unedited")
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
|
||||
let mut statuses = vec![prompt_status_from_cache(
|
||||
cached_builtin_prompt_from_connection(&conn, "remote-still-present")
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
"synced",
|
||||
)];
|
||||
let customized_ids = HashSet::from(["removed-but-edited".to_string()]);
|
||||
include_customized_prompt_statuses(
|
||||
&mut statuses,
|
||||
&customized_ids,
|
||||
cached_builtin_prompts_from_connection(&conn).unwrap(),
|
||||
);
|
||||
assert_eq!(statuses.len(), 2);
|
||||
let edited = statuses
|
||||
.iter()
|
||||
.find(|status| status.id == "removed-but-edited")
|
||||
.expect("include the newly edited template in the sync response");
|
||||
assert!(edited.customized);
|
||||
assert!(edited.message.contains("本地已修改"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synced_remote_prompt_is_available_from_sqlite_after_restart() {
|
||||
let database_path = std::env::temp_dir().join(format!(
|
||||
@@ -853,6 +1162,110 @@ mod tests {
|
||||
std::fs::remove_file(database_path).expect("remove prompt cache database");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curated_remote_prompts_have_user_facing_metadata() {
|
||||
assert_eq!(
|
||||
prompt_display_meta("software-development-maintainer.md"),
|
||||
(
|
||||
"长期维护工程师".to_string(),
|
||||
"正式项目的最小改动、复用、测试与安全规范".to_string(),
|
||||
"软件开发".to_string(),
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
prompt_display_meta("writing-technical-docs.md").2,
|
||||
"写作辅助"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curated_remote_prompt_ids_retain_category_prefixes() {
|
||||
assert!(stable_remote_prompt_id("software-development-debugging.md")
|
||||
.starts_with("github-software-development-debugging-"));
|
||||
assert!(stable_remote_prompt_id("writing-clarity-editor.md")
|
||||
.starts_with("github-writing-clarity-editor-"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locally_modified_prompt_is_excluded_from_content_sync() {
|
||||
let customized_ids = HashSet::from(["edited-template".to_string()]);
|
||||
|
||||
assert!(!should_sync_prompt_content(
|
||||
"edited-template",
|
||||
&customized_ids
|
||||
));
|
||||
assert!(should_sync_prompt_content(
|
||||
"new-github-template",
|
||||
&customized_ids
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locally_modified_prompt_status_is_visible_after_restart() {
|
||||
let cache = CachedBuiltinPrompt {
|
||||
id: "edited-template".to_string(),
|
||||
filename: "edited-template.md".to_string(),
|
||||
source_url: "https://example.test/edited-template.md".to_string(),
|
||||
content: "upstream cache".to_string(),
|
||||
checked_at: "2026-07-28T00:00:00Z".to_string(),
|
||||
};
|
||||
let mut statuses = cached_prompt_fallback_statuses(vec![cache]);
|
||||
let customized_ids = HashSet::from(["edited-template".to_string()]);
|
||||
|
||||
mark_customized_prompt_statuses(&mut statuses, &customized_ids);
|
||||
|
||||
let status = statuses
|
||||
.iter()
|
||||
.find(|status| status.id == "edited-template")
|
||||
.expect("customized cached prompt remains visible");
|
||||
assert!(status.customized);
|
||||
assert!(status.message.contains("同步已跳过"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_cdn_catalog_is_always_replaced_by_github_catalog() {
|
||||
let cdn = RemotePromptCatalog {
|
||||
prompts: vec![("bundled".to_string(), "bundled.md".to_string())],
|
||||
authoritative: false,
|
||||
};
|
||||
let github = RemotePromptCatalog {
|
||||
prompts: vec![
|
||||
("bundled".to_string(), "bundled.md".to_string()),
|
||||
(
|
||||
"github-software-development-debugging-test".to_string(),
|
||||
"software-development-debugging.md".to_string(),
|
||||
),
|
||||
],
|
||||
authoritative: true,
|
||||
};
|
||||
let mut calls = 0;
|
||||
|
||||
let (confirmed, failed) = confirm_prompt_catalog_with(cdn, || {
|
||||
calls += 1;
|
||||
Ok(github)
|
||||
});
|
||||
|
||||
assert_eq!(calls, 1);
|
||||
assert!(!failed);
|
||||
assert!(confirmed.authoritative);
|
||||
assert_eq!(confirmed.prompts.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_github_catalog_keeps_cdn_fallback_for_retry() {
|
||||
let cdn = RemotePromptCatalog {
|
||||
prompts: vec![("bundled".to_string(), "bundled.md".to_string())],
|
||||
authoritative: false,
|
||||
};
|
||||
|
||||
let (fallback, failed) =
|
||||
confirm_prompt_catalog_with(cdn, || Err(CodexxError::Config("offline".to_string())));
|
||||
|
||||
assert!(failed);
|
||||
assert!(!fallback.authoritative);
|
||||
assert_eq!(fallback.prompts.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syncing_remote_prompt_updates_the_existing_sqlite_row() {
|
||||
let conn = prompt_cache_connection();
|
||||
|
||||
@@ -2,8 +2,9 @@ use crate::constants::{
|
||||
AGENTS_FILENAME, AGENTS_MANAGED_BEGIN, AGENTS_MANAGED_END, AGENTS_TEMPLATE_PREFIX,
|
||||
};
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::{io_err, read_to_string_if_exists, write_text};
|
||||
use std::fs;
|
||||
use crate::file_io::read_to_string_if_exists;
|
||||
#[cfg(test)]
|
||||
use crate::live_config::{apply_file_change, read_file_snapshot, text_from_snapshot};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) fn agents_path(codex_dir: &Path) -> PathBuf {
|
||||
@@ -31,7 +32,7 @@ pub(crate) fn managed_agents_bounds(content: &str) -> Result<Option<(usize, usiz
|
||||
Ok(Some((begins[0], ends[0] + AGENTS_MANAGED_END.len())))
|
||||
}
|
||||
|
||||
fn remove_managed_agents_block(content: &str) -> Result<(String, bool)> {
|
||||
pub(crate) fn remove_managed_agents_block_from_content(content: &str) -> Result<(String, bool)> {
|
||||
let Some((start, end)) = managed_agents_bounds(content)? else {
|
||||
return Ok((content.to_string(), false));
|
||||
};
|
||||
@@ -46,6 +47,23 @@ fn remove_managed_agents_block(content: &str) -> Result<(String, bool)> {
|
||||
Ok((merged, true))
|
||||
}
|
||||
|
||||
pub(crate) fn install_managed_agents_block_in_content(
|
||||
existing: &str,
|
||||
template_key: &str,
|
||||
content: &str,
|
||||
) -> Result<String> {
|
||||
let (base, _) = remove_managed_agents_block_from_content(existing)?;
|
||||
let managed = format!(
|
||||
"{AGENTS_MANAGED_BEGIN}\n{AGENTS_TEMPLATE_PREFIX} {template_key} -->\n{}\n{AGENTS_MANAGED_END}",
|
||||
content.trim()
|
||||
);
|
||||
Ok(if base.trim().is_empty() {
|
||||
format!("{managed}\n")
|
||||
} else {
|
||||
format!("{}\n\n{managed}\n", base.trim_end())
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn managed_agents_template_key_from_content(content: &str) -> Option<String> {
|
||||
let (start, end) = managed_agents_bounds(content).ok().flatten()?;
|
||||
content[start..end].lines().find_map(|line| {
|
||||
@@ -64,40 +82,33 @@ pub(crate) fn managed_agents_template_key(codex_dir: &Path) -> Result<Option<Str
|
||||
Ok(managed_agents_template_key_from_content(&content))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn install_managed_agents_block(
|
||||
codex_dir: &Path,
|
||||
template_key: &str,
|
||||
content: &str,
|
||||
) -> Result<()> {
|
||||
let path = agents_path(codex_dir);
|
||||
let existing = read_to_string_if_exists(&path)?;
|
||||
let (base, _) = remove_managed_agents_block(&existing)?;
|
||||
let managed = format!(
|
||||
"{AGENTS_MANAGED_BEGIN}\n{AGENTS_TEMPLATE_PREFIX} {template_key} -->\n{}\n{AGENTS_MANAGED_END}",
|
||||
content.trim()
|
||||
);
|
||||
let next = if base.trim().is_empty() {
|
||||
format!("{managed}\n")
|
||||
} else {
|
||||
format!("{}\n\n{managed}\n", base.trim_end())
|
||||
};
|
||||
write_text(&path, &next)
|
||||
let before = read_file_snapshot(&path)?;
|
||||
let existing = text_from_snapshot(&path, before.as_deref())?;
|
||||
let next = install_managed_agents_block_in_content(&existing, template_key, content)?;
|
||||
apply_file_change(&path, before, Some(next.into_bytes()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn uninstall_managed_agents_block(codex_dir: &Path) -> Result<bool> {
|
||||
let path = agents_path(codex_dir);
|
||||
if !path.exists() {
|
||||
let before = read_file_snapshot(&path)?;
|
||||
if before.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
let existing = read_to_string_if_exists(&path)?;
|
||||
let (next, removed) = remove_managed_agents_block(&existing)?;
|
||||
let existing = text_from_snapshot(&path, before.as_deref())?;
|
||||
let (next, removed) = remove_managed_agents_block_from_content(&existing)?;
|
||||
if !removed {
|
||||
return Ok(false);
|
||||
}
|
||||
if next.trim().is_empty() {
|
||||
fs::remove_file(&path).map_err(|e| io_err(&path, e))?;
|
||||
} else {
|
||||
write_text(&path, &next)?;
|
||||
}
|
||||
let after = (!next.trim().is_empty()).then(|| next.into_bytes());
|
||||
apply_file_change(&path, before, after)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -4,18 +4,20 @@ mod store;
|
||||
mod types;
|
||||
|
||||
pub(crate) use catalog::{
|
||||
builtin_prompt_content, builtin_prompt_status_inner, bundled_prompt_meta, bundled_prompt_metas,
|
||||
refresh_builtin_prompts_with_active,
|
||||
builtin_prompt_content, builtin_prompt_detail_inner, builtin_prompt_status_inner,
|
||||
bundled_prompt_meta, bundled_prompt_metas, refresh_builtin_prompts_with_active,
|
||||
};
|
||||
pub(crate) use managed_agents::{
|
||||
agents_path, install_managed_agents_block, managed_agents_bounds, managed_agents_template_key,
|
||||
uninstall_managed_agents_block,
|
||||
agents_path, install_managed_agents_block_in_content, managed_agents_bounds,
|
||||
managed_agents_template_key, remove_managed_agents_block_from_content,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use managed_agents::{install_managed_agents_block, uninstall_managed_agents_block};
|
||||
pub(crate) use store::{
|
||||
delete_prompt_inner, get_saved_prompt_inner, list_saved_prompts_inner,
|
||||
normalize_prompt_filename, save_prompt_inner,
|
||||
normalize_prompt_filename, save_builtin_prompt_override_inner, save_prompt_inner,
|
||||
};
|
||||
pub(crate) use types::{BuiltinPromptStatus, SavedPrompt};
|
||||
pub(crate) use types::{BuiltinPromptDetail, BuiltinPromptStatus, SavedPrompt};
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use catalog::{
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::types::SavedPrompt;
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::{now_rfc3339, open_db};
|
||||
use rusqlite::params;
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(crate) fn normalize_prompt_filename(input: &str, fallback: &str) -> String {
|
||||
let raw = input.trim().trim_end_matches(".md");
|
||||
@@ -107,6 +108,68 @@ pub(crate) fn delete_prompt_inner(id: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn builtin_prompt_override_from_connection(
|
||||
conn: &rusqlite::Connection,
|
||||
template_id: &str,
|
||||
) -> Result<Option<String>> {
|
||||
match conn.query_row(
|
||||
"SELECT content FROM builtin_prompt_overrides WHERE template_id = ?1",
|
||||
[template_id],
|
||||
|row| row.get(0),
|
||||
) {
|
||||
Ok(content) => Ok(Some(content)),
|
||||
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
|
||||
Err(e) => Err(CodexxError::Database(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn builtin_prompt_override_inner(template_id: &str) -> Result<Option<String>> {
|
||||
let conn = open_db()?;
|
||||
builtin_prompt_override_from_connection(&conn, template_id.trim())
|
||||
}
|
||||
|
||||
pub(crate) fn builtin_prompt_override_ids_inner() -> Result<HashSet<String>> {
|
||||
let conn = open_db()?;
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT template_id FROM builtin_prompt_overrides")
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
let rows = stmt
|
||||
.query_map([], |row| row.get(0))
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
rows.map(|row| row.map_err(|e| CodexxError::Database(e.to_string())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn save_builtin_prompt_override_on_connection(
|
||||
conn: &rusqlite::Connection,
|
||||
template_id: &str,
|
||||
content: &str,
|
||||
) -> Result<()> {
|
||||
let id = template_id.trim();
|
||||
if id.is_empty() {
|
||||
return Err(CodexxError::Config("提示词模板标识不能为空".to_string()));
|
||||
}
|
||||
if content.trim().is_empty() {
|
||||
return Err(CodexxError::Config("提示词内容不能为空".to_string()));
|
||||
}
|
||||
let now = now_rfc3339();
|
||||
conn.execute(
|
||||
"INSERT INTO builtin_prompt_overrides (template_id, content, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?3)
|
||||
ON CONFLICT(template_id) DO UPDATE SET
|
||||
content = excluded.content,
|
||||
updated_at = excluded.updated_at",
|
||||
params![id, content, now],
|
||||
)
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn save_builtin_prompt_override_inner(template_id: &str, content: &str) -> Result<()> {
|
||||
let conn = open_db()?;
|
||||
save_builtin_prompt_override_on_connection(&conn, template_id, content)
|
||||
}
|
||||
|
||||
fn find_saved_prompt_by_content(content: &str) -> Result<Option<SavedPrompt>> {
|
||||
let conn = open_db()?;
|
||||
let mut stmt = conn
|
||||
@@ -167,3 +230,83 @@ pub(super) fn find_saved_prompt_by_current_file(
|
||||
Err(e) => Err(CodexxError::Database(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rusqlite::Connection;
|
||||
|
||||
fn override_connection() -> Connection {
|
||||
let conn = Connection::open_in_memory().expect("open override database");
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE builtin_prompt_overrides (
|
||||
template_id TEXT PRIMARY KEY,
|
||||
content TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);",
|
||||
)
|
||||
.expect("create override table");
|
||||
conn
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_prompt_override_can_be_edited_repeatedly() {
|
||||
let conn = override_connection();
|
||||
save_builtin_prompt_override_on_connection(&conn, "template", "first")
|
||||
.expect("save initial override");
|
||||
save_builtin_prompt_override_on_connection(&conn, "template", "second")
|
||||
.expect("update override");
|
||||
|
||||
assert_eq!(
|
||||
builtin_prompt_override_from_connection(&conn, "template")
|
||||
.expect("read override")
|
||||
.as_deref(),
|
||||
Some("second")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_prompt_override_rejects_empty_content() {
|
||||
let conn = override_connection();
|
||||
let error = save_builtin_prompt_override_on_connection(&conn, "template", " \n")
|
||||
.expect_err("reject empty override");
|
||||
assert!(error.to_string().contains("内容不能为空"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_prompt_override_survives_database_reopen() {
|
||||
let database_path = std::env::temp_dir().join(format!(
|
||||
"codexx-prompt-override-{}-{}.sqlite",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.expect("system time")
|
||||
.as_nanos()
|
||||
));
|
||||
{
|
||||
let conn = Connection::open(&database_path).expect("open override database");
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE builtin_prompt_overrides (
|
||||
template_id TEXT PRIMARY KEY,
|
||||
content TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);",
|
||||
)
|
||||
.expect("create override table");
|
||||
save_builtin_prompt_override_on_connection(&conn, "template", "local content")
|
||||
.expect("save override");
|
||||
}
|
||||
|
||||
let reopened = Connection::open(&database_path).expect("reopen override database");
|
||||
assert_eq!(
|
||||
builtin_prompt_override_from_connection(&reopened, "template")
|
||||
.expect("read persisted override")
|
||||
.as_deref(),
|
||||
Some("local content")
|
||||
);
|
||||
drop(reopened);
|
||||
std::fs::remove_file(database_path).expect("remove override database");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,17 @@ pub(crate) struct BuiltinPromptStatus {
|
||||
pub(crate) sync_issue: Option<String>,
|
||||
pub(crate) checked_at: Option<String>,
|
||||
pub(crate) message: String,
|
||||
pub(crate) customized: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct BuiltinPromptDetail {
|
||||
pub(crate) id: String,
|
||||
pub(crate) filename: String,
|
||||
pub(crate) title: String,
|
||||
pub(crate) content: String,
|
||||
pub(crate) customized: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
use super::{
|
||||
custom_provider_id, experimental_bearer_token_from_doc, list_saved_providers_on_connection,
|
||||
normalize_saved_provider, open_store, upsert_provider_on_connection, ProviderUpsertKind,
|
||||
ProviderUpsertMode, SavedProvider,
|
||||
consolidate_legacy_provider_duplicates_on_connection, custom_provider_id,
|
||||
experimental_bearer_token_from_doc, list_saved_providers_on_connection,
|
||||
normalize_saved_provider, open_store, strip_provider_bearer_tokens,
|
||||
upsert_ccswitch_provider_on_connection, ProviderUpsertKind, SavedProvider,
|
||||
};
|
||||
use crate::ccswitch::{ccswitch_db_candidates, default_ccswitch_db_path};
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::sqlite_utils::table_column_set;
|
||||
use crate::string_value;
|
||||
use crate::toml_utils::ensure_table;
|
||||
use rusqlite::{Connection, OpenFlags, TransactionBehavior};
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use toml_edit::{DocumentMut, Table};
|
||||
use toml_edit::{value, DocumentMut, Item, Table};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -30,6 +32,7 @@ pub(crate) struct ImportResult {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct OfficialAuthCandidate {
|
||||
auth_json: String,
|
||||
config_text: Option<String>,
|
||||
model: Option<String>,
|
||||
source: String,
|
||||
}
|
||||
@@ -91,6 +94,7 @@ pub(crate) struct CcSwitchCodexSection {
|
||||
pub(crate) wire_api: String,
|
||||
pub(crate) requires_openai_auth: bool,
|
||||
pub(crate) experimental_bearer_token: Option<String>,
|
||||
pub(crate) provider_table: Table,
|
||||
}
|
||||
|
||||
fn table_string(table: &Table, key: &str) -> Option<String> {
|
||||
@@ -134,6 +138,7 @@ pub(super) fn codex_section_from_table(
|
||||
.and_then(|item| item.as_bool())
|
||||
.unwrap_or(false),
|
||||
experimental_bearer_token: table_string(table, "experimental_bearer_token"),
|
||||
provider_table: table.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -160,79 +165,130 @@ fn select_ccswitch_section_for_row(
|
||||
global_sections: &HashMap<String, CcSwitchCodexSection>,
|
||||
) -> Option<CcSwitchCodexSection> {
|
||||
let provider_id = custom_provider_id(&row.id);
|
||||
if let Some(section) = global_sections.get(&provider_id) {
|
||||
return Some(section.clone());
|
||||
}
|
||||
if let Some(section) = global_sections.get(row.id.trim()) {
|
||||
return Some(section.clone());
|
||||
}
|
||||
|
||||
let config_text = settings.get("config").and_then(Value::as_str).unwrap_or("");
|
||||
let doc = config_text.parse::<DocumentMut>().ok()?;
|
||||
let model = string_value(&doc, "model");
|
||||
let active_provider = string_value(&doc, "model_provider");
|
||||
let providers = doc.get("model_providers").and_then(|item| item.as_table());
|
||||
let doc = config_text.parse::<DocumentMut>().ok();
|
||||
|
||||
if let Some(providers) = providers {
|
||||
for exact_id in [provider_id.as_str(), row.id.trim()] {
|
||||
if let Some(section) = providers
|
||||
.get(exact_id)
|
||||
.and_then(|item| item.as_table())
|
||||
.and_then(|table| codex_section_from_table(exact_id, table, model.clone()))
|
||||
{
|
||||
return Some(section);
|
||||
}
|
||||
}
|
||||
if let Some(doc) = doc.as_ref() {
|
||||
let model = string_value(doc, "model");
|
||||
let active_provider = string_value(doc, "model_provider");
|
||||
let providers = doc.get("model_providers").and_then(|item| item.as_table());
|
||||
|
||||
if active_provider.as_deref() == Some(row.id.trim())
|
||||
|| active_provider.as_deref() == Some(provider_id.as_str())
|
||||
{
|
||||
if let Some(active) = active_provider.as_deref() {
|
||||
if let Some(providers) = providers {
|
||||
for exact_id in [provider_id.as_str(), row.id.trim()] {
|
||||
if let Some(section) = providers
|
||||
.get(active)
|
||||
.get(exact_id)
|
||||
.and_then(|item| item.as_table())
|
||||
.and_then(|table| codex_section_from_table(active, table, model.clone()))
|
||||
.and_then(|table| codex_section_from_table(exact_id, table, model.clone()))
|
||||
{
|
||||
return Some(section);
|
||||
}
|
||||
}
|
||||
|
||||
if active_provider.as_deref() == Some(row.id.trim())
|
||||
|| active_provider.as_deref() == Some(provider_id.as_str())
|
||||
{
|
||||
if let Some(active) = active_provider.as_deref() {
|
||||
if let Some(section) = providers
|
||||
.get(active)
|
||||
.and_then(|item| item.as_table())
|
||||
.and_then(|table| codex_section_from_table(active, table, model.clone()))
|
||||
{
|
||||
return Some(section);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy cc-switch templates store each third-party provider under
|
||||
// `[model_providers.custom]` in that row's own complete config.
|
||||
if active_provider
|
||||
.as_deref()
|
||||
.is_none_or(|active| active == "custom")
|
||||
{
|
||||
if let Some(section) = providers
|
||||
.get("custom")
|
||||
.and_then(|item| item.as_table())
|
||||
.and_then(|table| codex_section_from_table("custom", table, model.clone()))
|
||||
{
|
||||
return Some(section);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy cc-switch/custom templates often store every third-party provider
|
||||
// under `[model_providers.custom]`. Only use it when the row's own config
|
||||
// explicitly activates custom or contains no other provider identity.
|
||||
if active_provider
|
||||
.as_deref()
|
||||
.is_none_or(|active| active == "custom")
|
||||
{
|
||||
if let Some(section) = providers
|
||||
.get("custom")
|
||||
.and_then(|item| item.as_table())
|
||||
.and_then(|table| codex_section_from_table("custom", table, model.clone()))
|
||||
{
|
||||
return Some(section);
|
||||
}
|
||||
for exact_id in [provider_id.as_str(), row.id.trim()] {
|
||||
if let Some(section) = global_sections.get(exact_id) {
|
||||
return Some(section.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let doc = doc?;
|
||||
let active_provider = string_value(&doc, "model_provider");
|
||||
doc.get("base_url")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|base_url| CcSwitchCodexSection {
|
||||
id: provider_id,
|
||||
name: None,
|
||||
base_url: base_url.trim_end_matches('/').to_string(),
|
||||
model,
|
||||
wire_api: "responses".to_string(),
|
||||
requires_openai_auth: false,
|
||||
experimental_bearer_token: experimental_bearer_token_from_doc(
|
||||
&doc,
|
||||
active_provider.as_deref(),
|
||||
),
|
||||
.map(|base_url| {
|
||||
let base_url = base_url.trim_end_matches('/').to_string();
|
||||
let token = experimental_bearer_token_from_doc(&doc, active_provider.as_deref());
|
||||
let mut provider_table = Table::new();
|
||||
provider_table["base_url"] = value(base_url.clone());
|
||||
provider_table["wire_api"] = value("responses");
|
||||
provider_table["requires_openai_auth"] = value(false);
|
||||
if let Some(token) = token.as_deref() {
|
||||
provider_table["experimental_bearer_token"] = value(token);
|
||||
}
|
||||
CcSwitchCodexSection {
|
||||
id: provider_id,
|
||||
name: None,
|
||||
base_url,
|
||||
model: string_value(&doc, "model"),
|
||||
wire_api: "responses".to_string(),
|
||||
requires_openai_auth: false,
|
||||
experimental_bearer_token: token,
|
||||
provider_table,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn ccswitch_provider_template(
|
||||
settings: &Value,
|
||||
section: &CcSwitchCodexSection,
|
||||
provider_name: &str,
|
||||
model: &str,
|
||||
) -> Option<String> {
|
||||
let config_text = settings.get("config").and_then(Value::as_str).unwrap_or("");
|
||||
let mut doc = if config_text.trim().is_empty() {
|
||||
DocumentMut::new()
|
||||
} else {
|
||||
config_text.parse::<DocumentMut>().ok()?
|
||||
};
|
||||
let provider_id = section.id.trim();
|
||||
if provider_id.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
if string_value(&doc, "model_provider").as_deref() != Some(provider_id) {
|
||||
doc["model_provider"] = value(provider_id);
|
||||
}
|
||||
if string_value(&doc, "model").as_deref() != Some(model) {
|
||||
doc["model"] = value(model);
|
||||
}
|
||||
let providers = ensure_table(doc.as_table_mut(), "model_providers").ok()?;
|
||||
if providers
|
||||
.get(provider_id)
|
||||
.and_then(|item| item.as_table())
|
||||
.is_none()
|
||||
{
|
||||
let mut table = section.provider_table.clone();
|
||||
if table_string(&table, "name").is_none() && !provider_name.trim().is_empty() {
|
||||
table["name"] = value(provider_name.trim());
|
||||
}
|
||||
providers.insert(provider_id, Item::Table(table));
|
||||
}
|
||||
strip_provider_bearer_tokens(&mut doc);
|
||||
Some(doc.to_string().trim_end().to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn build_ccswitch_codex_provider(
|
||||
row: &CcSwitchCodexRow,
|
||||
global_sections: &HashMap<String, CcSwitchCodexSection>,
|
||||
@@ -240,19 +296,26 @@ pub(crate) fn build_ccswitch_codex_provider(
|
||||
let settings: Value = serde_json::from_str(&row.settings_config).ok()?;
|
||||
let section = select_ccswitch_section_for_row(row, &settings, global_sections)?;
|
||||
let api_key = ccswitch_auth_api_key(&settings).or(section.experimental_bearer_token.clone());
|
||||
let provider_name = section
|
||||
.name
|
||||
.clone()
|
||||
.or_else(|| {
|
||||
let name = row.name.trim();
|
||||
(!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 {
|
||||
id: custom_provider_id(&row.id),
|
||||
provider_name: if row.name.trim().is_empty() {
|
||||
section.name.unwrap_or_else(|| row.id.clone())
|
||||
} else {
|
||||
row.name.trim().to_string()
|
||||
},
|
||||
provider_name,
|
||||
base_url: section.base_url,
|
||||
model: section.model.unwrap_or_else(|| "gpt-5.5".to_string()),
|
||||
model,
|
||||
api_key,
|
||||
toml_config: None,
|
||||
toml_config: Some(toml_config),
|
||||
wire_api: section.wire_api,
|
||||
requires_openai_auth: section.requires_openai_auth,
|
||||
model_mappings: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -314,6 +377,7 @@ pub(crate) fn import_ccswitch_codex_providers_inner(path: Option<String>) -> Res
|
||||
let transaction = local_conn
|
||||
.transaction_with_behavior(TransactionBehavior::Immediate)
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
merged += consolidate_legacy_provider_duplicates_on_connection(&transaction)?;
|
||||
|
||||
for row in rows_vec {
|
||||
if is_official_ccswitch_row(&row) {
|
||||
@@ -327,15 +391,11 @@ pub(crate) fn import_ccswitch_codex_providers_inner(path: Option<String>) -> Res
|
||||
match build_ccswitch_codex_provider(&row, &global_sections) {
|
||||
Some(provider) => {
|
||||
let provider = normalize_saved_provider(provider)?;
|
||||
let result = upsert_provider_on_connection(
|
||||
&transaction,
|
||||
provider,
|
||||
ProviderUpsertMode::Imported,
|
||||
)?;
|
||||
let result =
|
||||
upsert_ccswitch_provider_on_connection(&transaction, provider, row.id.trim())?;
|
||||
match result.kind {
|
||||
ProviderUpsertKind::Added => added += 1,
|
||||
ProviderUpsertKind::Updated => updated += 1,
|
||||
ProviderUpsertKind::Merged => merged += 1,
|
||||
}
|
||||
imported += 1;
|
||||
}
|
||||
@@ -348,6 +408,7 @@ pub(crate) fn import_ccswitch_codex_providers_inner(path: Option<String>) -> Res
|
||||
}
|
||||
}
|
||||
}
|
||||
merged += consolidate_legacy_provider_duplicates_on_connection(&transaction)?;
|
||||
transaction
|
||||
.commit()
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
@@ -385,13 +446,22 @@ pub(crate) fn read_ccswitch_official_auth_inner(
|
||||
CodexxError::Database(format!("打开 cc-switch 数据库失败 {}: {e}", db.display()))
|
||||
})?;
|
||||
|
||||
let provider_columns = table_column_set(&conn, "providers")?;
|
||||
let official_filter = if provider_columns.contains("category") {
|
||||
"id = 'codex-official' OR category = 'official'"
|
||||
} else {
|
||||
// Older cc-switch databases predate the category column. The stable
|
||||
// codex-official id is still enough to identify the official row.
|
||||
"id = 'codex-official'"
|
||||
};
|
||||
let query = format!(
|
||||
"SELECT id, name, settings_config FROM providers
|
||||
WHERE app_type = 'codex' AND ({official_filter})
|
||||
ORDER BY CASE WHEN id = 'codex-official' THEN 0 ELSE 1 END
|
||||
LIMIT 1"
|
||||
);
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT id, name, settings_config FROM providers
|
||||
WHERE app_type = 'codex' AND (id = 'codex-official' OR category = 'official')
|
||||
ORDER BY CASE WHEN id = 'codex-official' THEN 0 ELSE 1 END
|
||||
LIMIT 1",
|
||||
)
|
||||
.prepare(&query)
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
|
||||
let mut rows = stmt
|
||||
@@ -426,9 +496,12 @@ pub(crate) fn read_ccswitch_official_auth_inner(
|
||||
CodexxError::Database("cc-switch official provider 缺少 auth object".to_string())
|
||||
})?;
|
||||
|
||||
let model = settings
|
||||
let config_text = settings
|
||||
.get("config")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToString::to_string);
|
||||
let model = config_text
|
||||
.as_deref()
|
||||
.and_then(|text| text.parse::<DocumentMut>().ok())
|
||||
.and_then(|doc| string_value(&doc, "model"));
|
||||
|
||||
@@ -437,7 +510,195 @@ pub(crate) fn read_ccswitch_official_auth_inner(
|
||||
|
||||
Ok(Some(OfficialAuthCandidate {
|
||||
auth_json,
|
||||
config_text,
|
||||
model,
|
||||
source: format!("cc-switch:{name}:{id}"),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn provider_import_round_trips_complete_config_without_bearer_tokens() {
|
||||
let settings_config = json!({
|
||||
"auth": {"OPENAI_API_KEY": "sk-from-auth"},
|
||||
"config": r#"# keep-imported-comment
|
||||
model_provider = "custom"
|
||||
model = "gpt-5.6-sol"
|
||||
model_reasoning_effort = "xhigh"
|
||||
service_tier = "priority"
|
||||
experimental_bearer_token = "sk-top-level"
|
||||
notify = ["C:\\Users\\Thy\\codex-computer-use.exe", "turn-ended"]
|
||||
|
||||
[model_providers.custom]
|
||||
name = "Sky2api"
|
||||
base_url = "https://proxy.example.com/v1/"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
experimental_bearer_token = "sk-from-config"
|
||||
request_max_retries = 7
|
||||
|
||||
[model_providers.other]
|
||||
name = "Other provider"
|
||||
base_url = "https://other.example.com/v1"
|
||||
experimental_bearer_token = "sk-other"
|
||||
|
||||
[projects."/work/project"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[desktop]
|
||||
followUpQueueMode = "queue"
|
||||
localeOverride = "zh-CN"
|
||||
|
||||
[windows]
|
||||
sandbox = "elevated"
|
||||
shell_path = 'D:\Program Files\PowerShell\7\pwsh.exe'
|
||||
|
||||
[plugins."browser@openai-bundled"]
|
||||
enabled = true
|
||||
|
||||
[features]
|
||||
js_repl = false
|
||||
|
||||
[shell_environment_policy.set]
|
||||
CODEX_HOME = 'C:\Users\Thy\.codex'
|
||||
|
||||
[mcp_servers.docs]
|
||||
command = "docs-server"
|
||||
"#,
|
||||
})
|
||||
.to_string();
|
||||
let row = CcSwitchCodexRow {
|
||||
id: "magicai-123".to_string(),
|
||||
name: " Sky2_free ".to_string(),
|
||||
settings_config,
|
||||
category: None,
|
||||
};
|
||||
|
||||
let provider =
|
||||
build_ccswitch_codex_provider(&row, &HashMap::new()).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");
|
||||
assert_eq!(provider.model, "gpt-5.6-sol");
|
||||
assert_eq!(provider.api_key.as_deref(), Some("sk-from-auth"));
|
||||
assert_eq!(provider.wire_api, "responses");
|
||||
assert!(!provider.requires_openai_auth);
|
||||
|
||||
let text = provider.toml_config.expect("complete provider TOML");
|
||||
let doc = text.parse::<DocumentMut>().expect("parse provider TOML");
|
||||
assert!(text.contains("# keep-imported-comment"));
|
||||
assert_eq!(doc["model_provider"].as_str(), Some("custom"));
|
||||
assert_eq!(doc["model_reasoning_effort"].as_str(), Some("xhigh"));
|
||||
assert_eq!(doc["service_tier"].as_str(), Some("priority"));
|
||||
assert_eq!(doc["notify"].as_array().map(|values| values.len()), Some(2));
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["name"].as_str(),
|
||||
Some("Sky2api")
|
||||
);
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["base_url"].as_str(),
|
||||
Some("https://proxy.example.com/v1/")
|
||||
);
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["request_max_retries"].as_integer(),
|
||||
Some(7)
|
||||
);
|
||||
assert_eq!(
|
||||
doc["model_providers"]["other"]["base_url"].as_str(),
|
||||
Some("https://other.example.com/v1")
|
||||
);
|
||||
assert_eq!(
|
||||
doc["projects"]["/work/project"]["trust_level"].as_str(),
|
||||
Some("trusted")
|
||||
);
|
||||
assert_eq!(doc["desktop"]["followUpQueueMode"].as_str(), Some("queue"));
|
||||
assert_eq!(doc["desktop"]["localeOverride"].as_str(), Some("zh-CN"));
|
||||
assert_eq!(doc["windows"]["sandbox"].as_str(), Some("elevated"));
|
||||
assert_eq!(
|
||||
doc["windows"]["shell_path"].as_str(),
|
||||
Some(r"D:\Program Files\PowerShell\7\pwsh.exe")
|
||||
);
|
||||
assert_eq!(
|
||||
doc["plugins"]["browser@openai-bundled"]["enabled"].as_bool(),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(doc["features"]["js_repl"].as_bool(), Some(false));
|
||||
assert_eq!(
|
||||
doc["shell_environment_policy"]["set"]["CODEX_HOME"].as_str(),
|
||||
Some(r"C:\Users\Thy\.codex")
|
||||
);
|
||||
assert_eq!(
|
||||
doc["mcp_servers"]["docs"]["command"].as_str(),
|
||||
Some("docs-server")
|
||||
);
|
||||
assert!(doc.get("experimental_bearer_token").is_none());
|
||||
assert!(doc["model_providers"]
|
||||
.as_table()
|
||||
.expect("model providers table")
|
||||
.iter()
|
||||
.all(|(_, item)| item
|
||||
.as_table()
|
||||
.is_none_or(|table| table.get("experimental_bearer_token").is_none())));
|
||||
assert!(!text.contains("sk-from-auth"));
|
||||
assert!(!text.contains("experimental_bearer_token"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_row_without_a_model_is_not_silently_downgraded() {
|
||||
let row = CcSwitchCodexRow {
|
||||
id: "missing-model".to_string(),
|
||||
name: "Database label".to_string(),
|
||||
settings_config: json!({
|
||||
"auth": {"OPENAI_API_KEY": "sk-test"},
|
||||
"config": r#"model_provider = "custom"
|
||||
|
||||
[model_providers.custom]
|
||||
name = "TOML label"
|
||||
base_url = "https://proxy.example.com/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
"#,
|
||||
})
|
||||
.to_string(),
|
||||
category: None,
|
||||
};
|
||||
|
||||
assert!(build_ccswitch_codex_provider(&row, &HashMap::new()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_row_config_does_not_create_a_sparse_provider() {
|
||||
let section = codex_sections_from_config(
|
||||
r#"model_provider = "broken-row"
|
||||
model = "gpt-5.5"
|
||||
|
||||
[model_providers.broken-row]
|
||||
name = "Recovered only from another row"
|
||||
base_url = "https://proxy.example.com/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
"#,
|
||||
)
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("global provider section");
|
||||
let mut global_sections = HashMap::new();
|
||||
global_sections.insert(section.id.clone(), section);
|
||||
let row = CcSwitchCodexRow {
|
||||
id: "broken-row".to_string(),
|
||||
name: "Broken row".to_string(),
|
||||
settings_config: json!({
|
||||
"auth": {"OPENAI_API_KEY": "sk-must-not-import"},
|
||||
"config": "model = ["
|
||||
})
|
||||
.to_string(),
|
||||
category: None,
|
||||
};
|
||||
|
||||
assert!(build_ccswitch_codex_provider(&row, &global_sections).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
mod ccswitch;
|
||||
mod connection;
|
||||
mod live;
|
||||
pub(crate) mod model_catalog;
|
||||
mod official_auth;
|
||||
pub(crate) mod official_profiles;
|
||||
pub(crate) mod quota;
|
||||
mod selection;
|
||||
mod store;
|
||||
pub(crate) mod transport;
|
||||
|
||||
use crate::error::Result;
|
||||
use rusqlite::Connection;
|
||||
@@ -21,29 +27,48 @@ pub(crate) use connection::{
|
||||
fetch_provider_models_inner, test_provider_connection_inner, ProviderConnectionResult,
|
||||
ProviderModelsResult,
|
||||
};
|
||||
pub(crate) use live::{
|
||||
activate_saved_provider_inner, build_provider_toml_draft_inner,
|
||||
build_provider_toml_draft_with_origin_inner, delete_saved_provider_inner,
|
||||
get_provider_config_base_inner, save_active_provider_inner,
|
||||
save_active_provider_with_common_config_inner, save_official_config_inner,
|
||||
save_provider_toml_config_inner, switch_provider_inner, OfficialConfigInput, ProviderInput,
|
||||
ProviderTomlInput,
|
||||
};
|
||||
pub(crate) use live::{detected_live_custom_provider, replacement_write_order, LiveWriteOrder};
|
||||
#[cfg(test)]
|
||||
pub(crate) use live::{
|
||||
detected_live_custom_provider, save_provider_toml_config_with_pre_persist,
|
||||
reset_official_provider_inner, restore_official_provider_inner,
|
||||
save_provider_toml_config_with_pre_persist, switch_official_provider_inner,
|
||||
switch_official_provider_with_pre_persist, switch_provider_with_pre_persist,
|
||||
};
|
||||
pub(crate) use live::{
|
||||
save_official_config_inner, save_provider_toml_config_inner, switch_official_provider_inner,
|
||||
switch_provider_inner, OfficialConfigInput, ProviderInput, ProviderTomlInput,
|
||||
#[cfg(test)]
|
||||
pub(crate) use official_auth::{
|
||||
capture_live_chatgpt_config, get_official_config_draft_inner, official_snapshot_path_for_test,
|
||||
};
|
||||
pub(crate) use official_auth::{document_is_official, official_auth_available};
|
||||
pub(crate) use selection::{
|
||||
clear_active_provider_on_connection, clear_provider_selections_on_connection,
|
||||
reconcile_active_provider_on_connection, remember_active_provider_on_connection,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use store::{
|
||||
canonical_provider_base_url, merge_duplicate_provider_identities, provider_by_id_on_connection,
|
||||
provider_identity, save_manual_provider_on_connection,
|
||||
canonical_provider_base_url, provider_by_id_on_connection, provider_identity,
|
||||
save_manual_provider_on_connection, upsert_provider_on_connection, ProviderUpsertMode,
|
||||
};
|
||||
pub(crate) use store::{
|
||||
custom_provider_id, delete_provider_inner, experimental_bearer_token_from_doc,
|
||||
list_saved_providers_inner, list_saved_providers_on_connection, normalize_saved_provider,
|
||||
reserved_codex_provider_id, save_detected_provider_inner, save_provider_inner,
|
||||
upsert_provider_on_connection, ProviderUpsertKind, ProviderUpsertMode, SavedProvider,
|
||||
consolidate_legacy_provider_duplicates_on_connection, custom_provider_id,
|
||||
delete_provider_inner, duplicate_provider_inner, experimental_bearer_token_from_doc,
|
||||
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, 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,
|
||||
upsert_ccswitch_provider_on_connection, DuplicateProviderResult, ProviderStoreRollback,
|
||||
ProviderUpsertKind, SavedProvider,
|
||||
};
|
||||
|
||||
pub(crate) fn open_store() -> Result<Connection> {
|
||||
let mut conn = crate::app_db::open()?;
|
||||
store::merge_duplicate_provider_identities(&mut conn)?;
|
||||
Ok(conn)
|
||||
crate::app_db::open()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,946 @@
|
||||
//! Read-only subscription quota lookup for one saved official login. Credentials
|
||||
//! stay in native code; neither network errors nor response bodies are logged.
|
||||
|
||||
use super::official_profiles::{
|
||||
official_profile_quota_credentials, OfficialProfileQuotaCredentials,
|
||||
};
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::live_config::acquire_live_config_lock;
|
||||
use crate::remote::ensure_crypto_provider;
|
||||
use chrono::{DateTime, Duration as ChronoDuration, Utc};
|
||||
use reqwest::blocking::Client;
|
||||
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, USER_AGENT};
|
||||
use reqwest::StatusCode;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
const QUOTA_URL: &str = "https://chatgpt.com/backend-api/wham/usage";
|
||||
const RESET_CREDITS_URL: &str = "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
|
||||
const MAX_RESPONSE_BYTES: usize = 1024 * 1024;
|
||||
// The file lock is nonblocking. Concurrent quota and credit queries share this
|
||||
// brief gate while reading credentials, so they cannot fail each other's read.
|
||||
// Neither this gate nor the file lock is held during a network request.
|
||||
static QUERY_CREDENTIAL_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum OfficialQuery {
|
||||
Quota,
|
||||
ResetCredits,
|
||||
}
|
||||
|
||||
impl OfficialQuery {
|
||||
fn url(self) -> &'static str {
|
||||
match self {
|
||||
Self::Quota => QUOTA_URL,
|
||||
Self::ResetCredits => RESET_CREDITS_URL,
|
||||
}
|
||||
}
|
||||
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Quota => "额度",
|
||||
Self::ResetCredits => "重置次数",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct OfficialResetCreditsSnapshot {
|
||||
profile_id: String,
|
||||
available_count: u32,
|
||||
checked_at: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RawResetCreditsResponse {
|
||||
// Required and unsigned: unknown or invalid counts must never look like 0.
|
||||
available_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct OfficialQuotaSnapshot {
|
||||
profile_id: String,
|
||||
email: Option<String>,
|
||||
plan_type: Option<String>,
|
||||
limits: Vec<OfficialQuotaLimit>,
|
||||
checked_at: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct OfficialQuotaLimit {
|
||||
id: String,
|
||||
name: Option<String>,
|
||||
allowed: Option<bool>,
|
||||
limit_reached: Option<bool>,
|
||||
windows: Vec<OfficialQuotaWindow>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct OfficialQuotaWindow {
|
||||
id: String,
|
||||
window_seconds: Option<i64>,
|
||||
used_percent: Option<f64>,
|
||||
remaining_percent: Option<f64>,
|
||||
resets_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
struct RawWindow {
|
||||
limit_window_seconds: Option<i64>,
|
||||
used_percent: Option<f64>,
|
||||
reset_at: Option<i64>,
|
||||
reset_after_seconds: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
struct RawLimit {
|
||||
allowed: Option<bool>,
|
||||
limit_reached: Option<bool>,
|
||||
primary_window: Option<RawWindow>,
|
||||
secondary_window: Option<RawWindow>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RawAdditionalLimit {
|
||||
limit_name: Option<String>,
|
||||
name: Option<String>,
|
||||
metered_feature: Option<String>,
|
||||
rate_limit: Option<RawLimit>,
|
||||
#[serde(flatten)]
|
||||
direct_limit: RawLimit,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RawQuotaResponse {
|
||||
account_id: Option<String>,
|
||||
email: Option<String>,
|
||||
plan_type: Option<String>,
|
||||
rate_limit: Option<RawLimit>,
|
||||
code_review_rate_limit: Option<RawLimit>,
|
||||
additional_rate_limits: Option<Vec<Option<RawAdditionalLimit>>>,
|
||||
}
|
||||
|
||||
fn config_error(message: &str) -> CodexxError {
|
||||
CodexxError::Config(message.to_owned())
|
||||
}
|
||||
|
||||
fn nonempty(value: Option<&str>) -> Option<&str> {
|
||||
value.map(str::trim).filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn display_email(value: Option<&str>) -> Option<String> {
|
||||
nonempty(value)
|
||||
.filter(|email| email.len() <= 320 && email.contains('@'))
|
||||
.filter(|email| {
|
||||
!email
|
||||
.chars()
|
||||
.any(|character| character.is_control() || character.is_whitespace())
|
||||
})
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn quota_headers(credentials: &OfficialProfileQuotaCredentials) -> Result<HeaderMap> {
|
||||
let token = nonempty(Some(&credentials.access_token))
|
||||
.ok_or_else(|| config_error("此官方配置尚未登录,请先在 Codex 中登录"))?;
|
||||
let mut authorization = HeaderValue::from_str(&format!("Bearer {token}"))
|
||||
.map_err(|_| config_error("此官方配置的登录凭据无效,请重新登录"))?;
|
||||
authorization.set_sensitive(true);
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(AUTHORIZATION, authorization);
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
|
||||
headers.insert(USER_AGENT, HeaderValue::from_static("codex-cli"));
|
||||
if let Some(account_id) = nonempty(credentials.account_id.as_deref()) {
|
||||
let mut account = HeaderValue::from_str(account_id)
|
||||
.map_err(|_| config_error("此官方配置的账号标识无效,请重新登录"))?;
|
||||
account.set_sensitive(true);
|
||||
headers.insert("ChatGPT-Account-Id", account);
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
fn quota_client() -> Result<Client> {
|
||||
ensure_crypto_provider();
|
||||
Client::builder()
|
||||
.https_only(true)
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.timeout(Duration::from_secs(15))
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.build()
|
||||
.map_err(|_| config_error("官方账号查询客户端初始化失败"))
|
||||
}
|
||||
|
||||
fn check_status(status: StatusCode, query: OfficialQuery) -> Result<()> {
|
||||
if status.is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
let label = query.label();
|
||||
let message = match status.as_u16() {
|
||||
401 => format!("官方登录已失效,请重新登录此账号后查询{label}(HTTP 401)"),
|
||||
403 => format!("无法访问官方{label}服务(HTTP 403),请稍后重试或检查网络"),
|
||||
429 => format!("官方{label}查询过于频繁,请稍后重试(HTTP 429)"),
|
||||
300..=399 => format!("官方{label}接口发生重定向,已停止请求,请稍后重试"),
|
||||
code @ 500..=599 => format!("官方{label}服务暂不可用(HTTP {code}),请稍后重试"),
|
||||
code => format!("官方{label}查询失败(HTTP {code}),请稍后重试"),
|
||||
};
|
||||
Err(CodexxError::Config(message))
|
||||
}
|
||||
|
||||
fn read_bounded_body(reader: impl Read, content_length: Option<u64>) -> Result<Vec<u8>> {
|
||||
if content_length.is_some_and(|length| length > MAX_RESPONSE_BYTES as u64) {
|
||||
return Err(config_error("官方查询响应过大,已停止读取"));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
reader
|
||||
.take(MAX_RESPONSE_BYTES as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| config_error("读取官方查询响应失败,请稍后重试"))?;
|
||||
if bytes.len() > MAX_RESPONSE_BYTES {
|
||||
return Err(config_error("官方查询响应过大,已停止读取"));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn window(id: &str, raw: RawWindow, checked_at: DateTime<Utc>) -> OfficialQuotaWindow {
|
||||
let used_percent = raw
|
||||
.used_percent
|
||||
.filter(|value| value.is_finite())
|
||||
.map(|value| value.clamp(0.0, 100.0));
|
||||
let resets_at = raw
|
||||
.reset_at
|
||||
.and_then(|seconds| DateTime::from_timestamp(seconds, 0))
|
||||
.or_else(|| {
|
||||
raw.reset_after_seconds
|
||||
.filter(|seconds| *seconds >= 0)
|
||||
.and_then(ChronoDuration::try_seconds)
|
||||
.and_then(|duration| checked_at.checked_add_signed(duration))
|
||||
})
|
||||
.map(|time| time.to_rfc3339());
|
||||
OfficialQuotaWindow {
|
||||
id: id.to_owned(),
|
||||
window_seconds: raw.limit_window_seconds.filter(|seconds| *seconds > 0),
|
||||
used_percent,
|
||||
remaining_percent: used_percent.map(|value| (100.0 - value).clamp(0.0, 100.0)),
|
||||
resets_at,
|
||||
}
|
||||
}
|
||||
|
||||
fn limit(
|
||||
id: String,
|
||||
name: Option<String>,
|
||||
raw: RawLimit,
|
||||
checked_at: DateTime<Utc>,
|
||||
) -> OfficialQuotaLimit {
|
||||
let windows = [
|
||||
("primary", raw.primary_window),
|
||||
("secondary", raw.secondary_window),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(id, raw)| raw.map(|raw| window(id, raw, checked_at)))
|
||||
.collect();
|
||||
OfficialQuotaLimit {
|
||||
id,
|
||||
name,
|
||||
allowed: raw.allowed,
|
||||
limit_reached: raw.limit_reached,
|
||||
windows,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_quota_response(
|
||||
bytes: &[u8],
|
||||
profile_id: &str,
|
||||
credentials: &OfficialProfileQuotaCredentials,
|
||||
checked_at: DateTime<Utc>,
|
||||
) -> Result<OfficialQuotaSnapshot> {
|
||||
let raw: RawQuotaResponse = serde_json::from_slice(bytes)
|
||||
.map_err(|_| config_error("官方额度响应格式无法识别,请稍后重试"))?;
|
||||
if nonempty(raw.account_id.as_deref())
|
||||
.zip(nonempty(credentials.account_id.as_deref()))
|
||||
.is_some_and(|(actual, expected)| actual != expected)
|
||||
{
|
||||
return Err(config_error(
|
||||
"额度响应与所选官方账号不一致,请重新登录此配置后重试",
|
||||
));
|
||||
}
|
||||
let mut limits = Vec::new();
|
||||
if let Some(raw) = raw.rate_limit {
|
||||
limits.push(limit("main".to_owned(), None, raw, checked_at));
|
||||
}
|
||||
if let Some(raw) = raw.code_review_rate_limit {
|
||||
limits.push(limit("code_review".to_owned(), None, raw, checked_at));
|
||||
}
|
||||
for (index, additional) in raw
|
||||
.additional_rate_limits
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let Some(additional) = additional else {
|
||||
continue;
|
||||
};
|
||||
let name = nonempty(additional.limit_name.as_deref())
|
||||
.or_else(|| nonempty(additional.name.as_deref()))
|
||||
.or_else(|| nonempty(additional.metered_feature.as_deref()))
|
||||
.map(str::to_owned);
|
||||
limits.push(limit(
|
||||
format!("additional-{index}"),
|
||||
name,
|
||||
additional.rate_limit.unwrap_or(additional.direct_limit),
|
||||
checked_at,
|
||||
));
|
||||
}
|
||||
Ok(OfficialQuotaSnapshot {
|
||||
profile_id: profile_id.to_owned(),
|
||||
email: display_email(raw.email.as_deref())
|
||||
.or_else(|| display_email(credentials.email.as_deref())),
|
||||
plan_type: nonempty(raw.plan_type.as_deref()).map(str::to_owned),
|
||||
limits,
|
||||
checked_at: checked_at.to_rfc3339(),
|
||||
})
|
||||
}
|
||||
|
||||
fn credential_fingerprint(credentials: &OfficialProfileQuotaCredentials) -> [u8; 32] {
|
||||
let mut digest = Sha256::new();
|
||||
// Length-delimit components so two different identities cannot have the
|
||||
// same concatenated input. Only this digest is compared after the request.
|
||||
for value in [
|
||||
Some(credentials.access_token.as_str()),
|
||||
credentials.account_id.as_deref(),
|
||||
credentials.email.as_deref(),
|
||||
] {
|
||||
let bytes = value.unwrap_or_default().as_bytes();
|
||||
digest.update((bytes.len() as u64).to_le_bytes());
|
||||
digest.update(bytes);
|
||||
}
|
||||
digest.finalize().into()
|
||||
}
|
||||
|
||||
fn parse_reset_credits_response(
|
||||
bytes: &[u8],
|
||||
profile_id: &str,
|
||||
checked_at: DateTime<Utc>,
|
||||
) -> Result<OfficialResetCreditsSnapshot> {
|
||||
let raw: RawResetCreditsResponse = serde_json::from_slice(bytes)
|
||||
.map_err(|_| config_error("官方重置次数响应格式无法识别,请稍后重试"))?;
|
||||
Ok(OfficialResetCreditsSnapshot {
|
||||
profile_id: profile_id.to_owned(),
|
||||
available_count: raw.available_count,
|
||||
checked_at: checked_at.to_rfc3339(),
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_same_credentials(
|
||||
expected: [u8; 32],
|
||||
current: &OfficialProfileQuotaCredentials,
|
||||
) -> Result<()> {
|
||||
if expected != credential_fingerprint(current) {
|
||||
return Err(config_error("此官方账号的登录信息已变化,请重新刷新"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fetch_official_response(
|
||||
query: OfficialQuery,
|
||||
credentials: &OfficialProfileQuotaCredentials,
|
||||
) -> Result<Vec<u8>> {
|
||||
let headers = quota_headers(credentials)?;
|
||||
let label = query.label();
|
||||
let response = quota_client()?
|
||||
.get(query.url())
|
||||
.headers(headers)
|
||||
.send()
|
||||
.map_err(|error| {
|
||||
if error.is_timeout() {
|
||||
config_error(&format!("官方{label}查询超时,请检查网络后重试"))
|
||||
} else if error.is_connect() {
|
||||
config_error(&format!("无法连接官方{label}接口,请检查网络或代理设置"))
|
||||
} else {
|
||||
config_error(&format!("官方{label}网络请求失败,请稍后重试"))
|
||||
}
|
||||
})?;
|
||||
check_status(response.status(), query)?;
|
||||
let length = response.content_length();
|
||||
read_bounded_body(response, length)
|
||||
}
|
||||
|
||||
fn read_query_credentials(
|
||||
codex_dir: &Path,
|
||||
profile_id: &str,
|
||||
) -> Result<OfficialProfileQuotaCredentials> {
|
||||
let _query_guard = QUERY_CREDENTIAL_LOCK
|
||||
.lock()
|
||||
.map_err(|_| config_error("官方账号查询暂不可用,请重试"))?;
|
||||
let _file_guard = acquire_live_config_lock(codex_dir)
|
||||
.map_err(|_| config_error("官方配置正在修改,请稍后刷新"))?;
|
||||
official_profile_quota_credentials(codex_dir, profile_id)
|
||||
}
|
||||
|
||||
fn read_official_snapshot<T>(
|
||||
codex_dir: &Path,
|
||||
profile_id: &str,
|
||||
fetch: impl FnOnce(&OfficialProfileQuotaCredentials) -> Result<Vec<u8>>,
|
||||
parse: impl FnOnce(&[u8], &str, &OfficialProfileQuotaCredentials, DateTime<Utc>) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let credentials = read_query_credentials(codex_dir, profile_id)?;
|
||||
let fingerprint = credential_fingerprint(&credentials);
|
||||
let bytes = fetch(&credentials)?;
|
||||
let snapshot = parse(&bytes, profile_id, &credentials, Utc::now())?;
|
||||
let current = read_query_credentials(codex_dir, profile_id)
|
||||
.map_err(|_| config_error("此官方配置已变化或被删除,请重新选择账号后查询"))?;
|
||||
ensure_same_credentials(fingerprint, ¤t)?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
pub(crate) fn get_official_profile_quota_inner(
|
||||
config_dir: Option<String>,
|
||||
profile_id: String,
|
||||
) -> Result<OfficialQuotaSnapshot> {
|
||||
let codex_dir = crate::resolve_codex_dir(config_dir)?;
|
||||
read_official_snapshot(
|
||||
&codex_dir,
|
||||
profile_id.trim(),
|
||||
|credentials| fetch_official_response(OfficialQuery::Quota, credentials),
|
||||
parse_quota_response,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn get_official_profile_reset_credits_inner(
|
||||
config_dir: Option<String>,
|
||||
profile_id: String,
|
||||
) -> Result<OfficialResetCreditsSnapshot> {
|
||||
let codex_dir = crate::resolve_codex_dir(config_dir)?;
|
||||
read_official_snapshot(
|
||||
&codex_dir,
|
||||
profile_id.trim(),
|
||||
|credentials| fetch_official_response(OfficialQuery::ResetCredits, credentials),
|
||||
|bytes, profile_id, _, checked_at| {
|
||||
parse_reset_credits_response(bytes, profile_id, checked_at)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn credentials(account: Option<&str>) -> OfficialProfileQuotaCredentials {
|
||||
OfficialProfileQuotaCredentials {
|
||||
access_token: "synthetic-access-token".to_owned(),
|
||||
account_id: account.map(str::to_owned),
|
||||
email: Some("saved@example.test".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
fn checked_at() -> DateTime<Utc> {
|
||||
DateTime::parse_from_rfc3339("2026-09-09T03:00:00Z")
|
||||
.unwrap()
|
||||
.with_timezone(&Utc)
|
||||
}
|
||||
|
||||
fn parse(value: serde_json::Value, account: Option<&str>) -> OfficialQuotaSnapshot {
|
||||
parse_quota_response(
|
||||
&serde_json::to_vec(&value).unwrap(),
|
||||
"official-profile-a",
|
||||
&credentials(account),
|
||||
checked_at(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pro_primary_window_can_be_weekly_and_account_id_can_be_absent() {
|
||||
let snapshot = parse(
|
||||
json!({
|
||||
"plan_type":"pro", "email":"active@example.test", "account_id":"server-account",
|
||||
"rate_limit":{"allowed":true,"limit_reached":false,"primary_window":{"limit_window_seconds":604800,"used_percent":37.5,"reset_after_seconds":600}},
|
||||
"additional_rate_limits":null,"code_review_rate_limit":null
|
||||
}),
|
||||
None,
|
||||
);
|
||||
assert_eq!(snapshot.profile_id, "official-profile-a");
|
||||
assert_eq!(snapshot.email.as_deref(), Some("active@example.test"));
|
||||
assert_eq!(snapshot.plan_type.as_deref(), Some("pro"));
|
||||
assert_eq!(snapshot.limits.len(), 1);
|
||||
let limit = &snapshot.limits[0];
|
||||
assert_eq!(limit.id, "main");
|
||||
assert_eq!(limit.allowed, Some(true));
|
||||
assert_eq!(limit.windows[0].id, "primary");
|
||||
assert_eq!(limit.windows[0].window_seconds, Some(604800));
|
||||
assert_eq!(limit.windows[0].remaining_percent, Some(62.5));
|
||||
assert_eq!(
|
||||
limit.windows[0].resets_at.as_deref(),
|
||||
Some("2026-09-09T03:10:00+00:00")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn team_two_windows_preserve_real_durations_and_absolute_reset_priority() {
|
||||
let reset = checked_at().timestamp() + 3600;
|
||||
let snapshot = parse(
|
||||
json!({
|
||||
"account_id":"team-a","plan_type":"team",
|
||||
"rate_limit":{"allowed":false,"limit_reached":true,
|
||||
"primary_window":{"limit_window_seconds":18000,"used_percent":100,"reset_at":reset,"reset_after_seconds":20},
|
||||
"secondary_window":{"limit_window_seconds":604800,"used_percent":23.25}}
|
||||
}),
|
||||
Some("team-a"),
|
||||
);
|
||||
let limit = &snapshot.limits[0];
|
||||
assert_eq!(limit.windows.len(), 2);
|
||||
assert_eq!(limit.limit_reached, Some(true));
|
||||
assert_eq!(limit.windows[0].window_seconds, Some(18000));
|
||||
assert_eq!(limit.windows[0].remaining_percent, Some(0.0));
|
||||
assert_eq!(
|
||||
limit.windows[0].resets_at.as_deref(),
|
||||
Some("2026-09-09T04:00:00+00:00")
|
||||
);
|
||||
assert_eq!(limit.windows[1].window_seconds, Some(604800));
|
||||
assert_eq!(limit.windows[1].remaining_percent, Some(76.75));
|
||||
assert!(limit.windows[1].resets_at.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_review_and_additional_features_remain_separate_limits() {
|
||||
let snapshot = parse(
|
||||
json!({
|
||||
"rate_limit":null,
|
||||
"code_review_rate_limit":{"allowed":true,"primary_window":{"used_percent":10,"limit_window_seconds":604800}},
|
||||
"additional_rate_limits":[null,
|
||||
{"limit_name":"Codex Spark","metered_feature":"codex_bengal","rate_limit":{"allowed":true,"primary_window":{"used_percent":40,"limit_window_seconds":18000}}},
|
||||
{"metered_feature":"future_feature","allowed":false,"limit_reached":true,"primary_window":{"used_percent":100,"limit_window_seconds":86400}}]
|
||||
}),
|
||||
None,
|
||||
);
|
||||
assert_eq!(snapshot.limits.len(), 3);
|
||||
assert_eq!(snapshot.limits[0].id, "code_review");
|
||||
assert_eq!(snapshot.limits[1].id, "additional-1");
|
||||
assert_eq!(snapshot.limits[1].name.as_deref(), Some("Codex Spark"));
|
||||
assert_eq!(snapshot.limits[2].name.as_deref(), Some("future_feature"));
|
||||
assert_eq!(snapshot.limits[2].allowed, Some(false));
|
||||
assert_eq!(snapshot.limits[2].windows[0].window_seconds, Some(86400));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_usage_is_unknown_instead_of_zero_or_full_remaining() {
|
||||
let snapshot = parse(
|
||||
json!({"rate_limit":{"primary_window":{"limit_window_seconds":18000}}}),
|
||||
None,
|
||||
);
|
||||
let window = &snapshot.limits[0].windows[0];
|
||||
assert!(window.used_percent.is_none());
|
||||
assert!(window.remaining_percent.is_none());
|
||||
assert!(snapshot.limits[0].allowed.is_none());
|
||||
assert!(snapshot.limits[0].limit_reached.is_none());
|
||||
let empty = parse(json!({}), None);
|
||||
assert!(empty.limits.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finite_percentages_are_clamped_and_nonfinite_values_stay_unknown() {
|
||||
for (used, expected) in [
|
||||
(-20.0, Some(0.0)),
|
||||
(130.0, Some(100.0)),
|
||||
(f64::NAN, None),
|
||||
(f64::INFINITY, None),
|
||||
] {
|
||||
let value = window(
|
||||
"primary",
|
||||
RawWindow {
|
||||
used_percent: Some(used),
|
||||
..Default::default()
|
||||
},
|
||||
checked_at(),
|
||||
);
|
||||
assert_eq!(value.used_percent, expected);
|
||||
assert_eq!(value.remaining_percent, expected.map(|used| 100.0 - used));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_reset_and_window_numbers_do_not_panic_or_invent_dates() {
|
||||
let value = window(
|
||||
"primary",
|
||||
RawWindow {
|
||||
limit_window_seconds: Some(-1),
|
||||
reset_at: Some(i64::MAX),
|
||||
reset_after_seconds: Some(i64::MAX),
|
||||
..Default::default()
|
||||
},
|
||||
checked_at(),
|
||||
);
|
||||
assert!(value.window_seconds.is_none());
|
||||
assert!(value.resets_at.is_none());
|
||||
let negative = window(
|
||||
"primary",
|
||||
RawWindow {
|
||||
reset_after_seconds: Some(-10),
|
||||
..Default::default()
|
||||
},
|
||||
checked_at(),
|
||||
);
|
||||
assert!(negative.resets_at.is_none());
|
||||
let now = window(
|
||||
"primary",
|
||||
RawWindow {
|
||||
reset_after_seconds: Some(0),
|
||||
..Default::default()
|
||||
},
|
||||
checked_at(),
|
||||
);
|
||||
assert_eq!(now.resets_at.as_deref(), Some("2026-09-09T03:00:00+00:00"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_nonempty_response_account_is_rejected_without_identifiers_in_error() {
|
||||
let error = parse_quota_response(
|
||||
br#"{"account_id":"other-private-account"}"#,
|
||||
"official-profile-a",
|
||||
&credentials(Some("selected-private-account")),
|
||||
checked_at(),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("不一致"));
|
||||
assert!(!error.contains("private-account"));
|
||||
assert!(!error.contains("synthetic-access-token"));
|
||||
assert!(
|
||||
parse(json!({"account_id":null}), Some("selected-private-account"))
|
||||
.limits
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn email_uses_response_first_then_safe_saved_display_metadata() {
|
||||
assert_eq!(
|
||||
parse(json!({"email":"response@example.test"}), None)
|
||||
.email
|
||||
.as_deref(),
|
||||
Some("response@example.test")
|
||||
);
|
||||
assert_eq!(
|
||||
parse(json!({"email":"bad\n@example.test"}), None)
|
||||
.email
|
||||
.as_deref(),
|
||||
Some("saved@example.test")
|
||||
);
|
||||
assert_eq!(
|
||||
parse(json!({}), None).email.as_deref(),
|
||||
Some("saved@example.test")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_has_only_fixed_https_endpoint_and_sensitive_auth_headers() {
|
||||
let request = quota_client()
|
||||
.unwrap()
|
||||
.get(QUOTA_URL)
|
||||
.headers(quota_headers(&credentials(Some("account-a"))).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
assert_eq!(request.method(), reqwest::Method::GET);
|
||||
assert_eq!(request.url().as_str(), QUOTA_URL);
|
||||
assert_eq!(request.url().host_str(), Some("chatgpt.com"));
|
||||
assert_eq!(request.url().scheme(), "https");
|
||||
assert!(request.headers()[AUTHORIZATION].is_sensitive());
|
||||
assert_eq!(
|
||||
request.headers()[AUTHORIZATION],
|
||||
"Bearer synthetic-access-token"
|
||||
);
|
||||
assert!(request.headers()["chatgpt-account-id"].is_sensitive());
|
||||
assert_eq!(request.headers()["chatgpt-account-id"], "account-a");
|
||||
assert_eq!(request.headers()[ACCEPT], "application/json");
|
||||
assert_eq!(request.headers()[USER_AGENT], "codex-cli");
|
||||
assert!(!format!("{request:?}").contains("synthetic-access-token"));
|
||||
assert!(!quota_headers(&credentials(None))
|
||||
.unwrap()
|
||||
.contains_key("chatgpt-account-id"));
|
||||
let credits_request = quota_client()
|
||||
.unwrap()
|
||||
.get(OfficialQuery::ResetCredits.url())
|
||||
.headers(quota_headers(&credentials(Some("account-a"))).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
assert_eq!(credits_request.method(), reqwest::Method::GET);
|
||||
assert_eq!(credits_request.url().as_str(), RESET_CREDITS_URL);
|
||||
assert_eq!(credits_request.url().scheme(), "https");
|
||||
assert_eq!(credits_request.url().host_str(), Some("chatgpt.com"));
|
||||
assert!(credits_request.headers()[AUTHORIZATION].is_sensitive());
|
||||
assert!(credits_request.headers()["chatgpt-account-id"].is_sensitive());
|
||||
assert!(!format!("{credits_request:?}").contains("synthetic-access-token"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_or_injected_credentials_fail_without_revealing_content() {
|
||||
let mut empty = credentials(None);
|
||||
empty.access_token = " ".to_owned();
|
||||
assert!(quota_headers(&empty)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("尚未登录"));
|
||||
let mut invalid = credentials(None);
|
||||
invalid.access_token = "private-secret\r\nInjected: true".to_owned();
|
||||
let error = quota_headers(&invalid).unwrap_err().to_string();
|
||||
assert!(!error.contains("private-secret"));
|
||||
assert!(!error.contains("Injected"));
|
||||
invalid = credentials(Some("private-account\r\nInjected: true"));
|
||||
let error = quota_headers(&invalid).unwrap_err().to_string();
|
||||
assert!(!error.contains("private-account"));
|
||||
assert!(error.contains("账号标识无效"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_statuses_have_safe_actionable_messages() {
|
||||
for query in [OfficialQuery::Quota, OfficialQuery::ResetCredits] {
|
||||
assert!(check_status(StatusCode::OK, query).is_ok());
|
||||
for (status, expected) in [
|
||||
(401, "重新登录"),
|
||||
(403, "检查网络"),
|
||||
(429, "过于频繁"),
|
||||
(302, "重定向"),
|
||||
(503, "HTTP 503"),
|
||||
] {
|
||||
let error = check_status(StatusCode::from_u16(status).unwrap(), query)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains(expected));
|
||||
assert!(error.contains(query.label()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn body_limit_applies_even_without_or_with_false_content_length() {
|
||||
assert_eq!(read_bounded_body(&b"{}"[..], Some(2)).unwrap(), b"{}");
|
||||
let large = vec![b'x'; MAX_RESPONSE_BYTES + 1];
|
||||
for content_length in [None, Some(1), Some(large.len() as u64)] {
|
||||
assert!(read_bounded_body(&large[..], content_length)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("响应过大"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_response_never_enters_error_text() {
|
||||
let error = parse_quota_response(
|
||||
b"server accidentally returned private-secret-token",
|
||||
"official-profile-a",
|
||||
&credentials(None),
|
||||
checked_at(),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("格式无法识别"));
|
||||
assert!(!error.contains("private-secret-token"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_change_rejects_stale_result_for_token_account_or_email() {
|
||||
let original = credentials(Some("account-a"));
|
||||
let fingerprint = credential_fingerprint(&original);
|
||||
assert!(ensure_same_credentials(fingerprint, &credentials(Some("account-a"))).is_ok());
|
||||
for field in ["token", "account", "email"] {
|
||||
let mut changed = credentials(Some("account-a"));
|
||||
match field {
|
||||
"token" => changed.access_token = "private-replacement-token".into(),
|
||||
"account" => changed.account_id = Some("account-b".into()),
|
||||
_ => changed.email = Some("changed@example.test".into()),
|
||||
}
|
||||
let error = ensure_same_credentials(fingerprint, &changed)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("登录信息已变化"));
|
||||
assert!(!error.contains("private-replacement-token"));
|
||||
assert!(!error.contains("account-b"));
|
||||
assert!(!error.contains("changed@example.test"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialized_snapshot_contains_only_display_fields_and_no_credentials() {
|
||||
let snapshot = parse(
|
||||
json!({"plan_type":"team","rate_limit":{"primary_window":{"used_percent":40,"limit_window_seconds":18000}}}),
|
||||
Some("account-a"),
|
||||
);
|
||||
let value = serde_json::to_value(&snapshot).unwrap();
|
||||
assert_eq!(value["profileId"], "official-profile-a");
|
||||
assert_eq!(value["planType"], "team");
|
||||
assert_eq!(value["limits"][0]["windows"][0]["remainingPercent"], 60.0);
|
||||
let serialized = value.to_string();
|
||||
assert!(!serialized.contains("access_token"));
|
||||
assert!(!serialized.contains("synthetic-access-token"));
|
||||
assert!(!serialized.contains("account-a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_credits_uses_available_count_and_returns_no_credit_details() {
|
||||
let raw = json!({
|
||||
"available_count": 3,
|
||||
"total_earned_count": 0,
|
||||
"credits": [{"id":"private-credit-id", "status":"available", "title":"private-credit-title"}],
|
||||
"immediate_reset_purchase_eligible": true
|
||||
});
|
||||
let snapshot = parse_reset_credits_response(
|
||||
&serde_json::to_vec(&raw).unwrap(),
|
||||
"official-profile-a",
|
||||
checked_at(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(snapshot).unwrap(),
|
||||
json!({
|
||||
"profileId":"official-profile-a",
|
||||
"availableCount":3,
|
||||
"checkedAt":"2026-09-09T03:00:00+00:00"
|
||||
})
|
||||
);
|
||||
let zero = parse_reset_credits_response(
|
||||
br#"{"available_count":0,"credits":[{"status":"available"}]}"#,
|
||||
"official-profile-a",
|
||||
checked_at(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(zero.available_count, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_credits_unknown_or_invalid_counts_are_not_reported_as_zero() {
|
||||
for raw in [
|
||||
"{}",
|
||||
"null",
|
||||
r#"{"available_count":null}"#,
|
||||
r#"{"available_count":-1}"#,
|
||||
r#"{"available_count":1.5}"#,
|
||||
r#"{"available_count":"3"}"#,
|
||||
r#"{"available_count":true}"#,
|
||||
r#"{"available_count":4294967296}"#,
|
||||
"private-malformed-response",
|
||||
] {
|
||||
let error =
|
||||
parse_reset_credits_response(raw.as_bytes(), "official-profile-a", checked_at())
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("重置次数响应格式无法识别"));
|
||||
assert!(!error.contains("private-malformed-response"));
|
||||
}
|
||||
}
|
||||
|
||||
fn query_fixture(label: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"codex-x-official-query-{label}-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
crate::file_io::write_text(
|
||||
&crate::config_path(&dir),
|
||||
"model_provider = \"openai\"\nmodel = \"synthetic-model\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
crate::file_io::write_json(
|
||||
&crate::auth_path(&dir),
|
||||
&json!({
|
||||
"auth_mode":"chatgpt", "tokens":{
|
||||
"access_token":"synthetic-query-token", "account_id":"synthetic-account"
|
||||
}
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_and_reset_queries_overlap_without_holding_the_live_config_lock() {
|
||||
use super::super::official_profiles::DEFAULT_OFFICIAL_PROFILE_ID;
|
||||
use std::sync::mpsc;
|
||||
|
||||
let _db_guard = crate::app_db::test_db_guard();
|
||||
let dir = query_fixture("parallel");
|
||||
// Initialize the test database before starting the two independent reads.
|
||||
read_query_credentials(&dir, DEFAULT_OFFICIAL_PROFILE_ID).unwrap();
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (quota_release_tx, quota_release_rx) = mpsc::channel();
|
||||
let (credits_release_tx, credits_release_rx) = mpsc::channel();
|
||||
std::thread::scope(|scope| {
|
||||
let quota_started = started_tx.clone();
|
||||
let quota_dir = &dir;
|
||||
let quota = scope.spawn(move || {
|
||||
read_official_snapshot(
|
||||
quota_dir,
|
||||
DEFAULT_OFFICIAL_PROFILE_ID,
|
||||
|_| {
|
||||
quota_started.send("quota").unwrap();
|
||||
quota_release_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.unwrap();
|
||||
Ok(b"{}".to_vec())
|
||||
},
|
||||
parse_quota_response,
|
||||
)
|
||||
});
|
||||
let credits_dir = &dir;
|
||||
let credits = scope.spawn(move || {
|
||||
read_official_snapshot(
|
||||
credits_dir,
|
||||
DEFAULT_OFFICIAL_PROFILE_ID,
|
||||
|_| {
|
||||
started_tx.send("credits").unwrap();
|
||||
credits_release_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.unwrap();
|
||||
Ok(br#"{"available_count":3}"#.to_vec())
|
||||
},
|
||||
|bytes, id, _, time| parse_reset_credits_response(bytes, id, time),
|
||||
)
|
||||
});
|
||||
// Both requests must start before either can finish. A lock held over
|
||||
// the simulated network wait would make this fail instead of hang.
|
||||
let first = started_rx.recv_timeout(Duration::from_secs(3)).unwrap();
|
||||
let second = started_rx.recv_timeout(Duration::from_secs(3)).unwrap();
|
||||
assert_ne!(first, second);
|
||||
drop(acquire_live_config_lock(&dir).unwrap());
|
||||
quota_release_tx.send(()).unwrap();
|
||||
credits_release_tx.send(()).unwrap();
|
||||
assert_eq!(
|
||||
quota.join().unwrap().unwrap().profile_id,
|
||||
DEFAULT_OFFICIAL_PROFILE_ID
|
||||
);
|
||||
assert_eq!(credits.join().unwrap().unwrap().available_count, 3);
|
||||
});
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_query_rejects_login_replaced_during_request() {
|
||||
use super::super::official_profiles::DEFAULT_OFFICIAL_PROFILE_ID;
|
||||
|
||||
let _db_guard = crate::app_db::test_db_guard();
|
||||
let dir = query_fixture("changed-login");
|
||||
let error = read_official_snapshot(
|
||||
&dir, DEFAULT_OFFICIAL_PROFILE_ID,
|
||||
|_| {
|
||||
let _guard = acquire_live_config_lock(&dir).unwrap();
|
||||
crate::file_io::write_json(&crate::auth_path(&dir), &json!({
|
||||
"auth_mode":"chatgpt", "tokens":{
|
||||
"access_token":"synthetic-replacement-token", "account_id":"synthetic-account"
|
||||
}
|
||||
})).unwrap();
|
||||
Ok(br#"{"available_count":3}"#.to_vec())
|
||||
},
|
||||
|bytes, id, _, time| parse_reset_credits_response(bytes, id, time),
|
||||
).unwrap_err().to_string();
|
||||
assert!(error.contains("登录信息已变化"));
|
||||
assert!(!error.contains("synthetic-replacement-token"));
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::now_rfc3339;
|
||||
use crate::paths::normalized_path_scope;
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
|
||||
pub(super) fn selected_provider_id_on_connection(
|
||||
conn: &Connection,
|
||||
codex_dir: &Path,
|
||||
) -> Result<Option<String>> {
|
||||
conn.query_row(
|
||||
"SELECT provider_id
|
||||
FROM active_provider_selections
|
||||
WHERE codex_dir = ?1",
|
||||
[normalized_path_scope(codex_dir)],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))
|
||||
}
|
||||
|
||||
pub(crate) fn remember_active_provider_on_connection(
|
||||
conn: &Connection,
|
||||
codex_dir: &Path,
|
||||
provider_id: &str,
|
||||
) -> Result<()> {
|
||||
let provider_id = provider_id.trim();
|
||||
if provider_id.is_empty() {
|
||||
return Err(CodexxError::Config("当前供应商 ID 不能为空".to_string()));
|
||||
}
|
||||
let exists = conn
|
||||
.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM providers WHERE id = ?1)",
|
||||
[provider_id],
|
||||
|row| row.get::<_, bool>(0),
|
||||
)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
if !exists {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"无法记录当前供应商,未找到 ID {provider_id}"
|
||||
)));
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT INTO active_provider_selections (codex_dir, provider_id, updated_at)
|
||||
VALUES (?1, ?2, ?3)
|
||||
ON CONFLICT(codex_dir) DO UPDATE SET
|
||||
provider_id = excluded.provider_id,
|
||||
updated_at = excluded.updated_at",
|
||||
params![normalized_path_scope(codex_dir), provider_id, now_rfc3339()],
|
||||
)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn clear_active_provider_on_connection(
|
||||
conn: &Connection,
|
||||
codex_dir: &Path,
|
||||
) -> Result<()> {
|
||||
conn.execute(
|
||||
"DELETE FROM active_provider_selections WHERE codex_dir = ?1",
|
||||
[normalized_path_scope(codex_dir)],
|
||||
)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn clear_provider_selections_on_connection(
|
||||
conn: &Connection,
|
||||
provider_id: &str,
|
||||
) -> Result<()> {
|
||||
conn.execute(
|
||||
"DELETE FROM active_provider_selections WHERE provider_id = ?1",
|
||||
[provider_id],
|
||||
)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn reconcile_active_provider_on_connection(
|
||||
conn: &Connection,
|
||||
codex_dir: &Path,
|
||||
candidate_ids: &[String],
|
||||
) -> Result<Option<String>> {
|
||||
let candidates = candidate_ids
|
||||
.iter()
|
||||
.map(|id| id.trim())
|
||||
.filter(|id| !id.is_empty())
|
||||
.collect::<HashSet<_>>();
|
||||
let selected = selected_provider_id_on_connection(conn, codex_dir)?;
|
||||
if let Some(selected) = selected.as_deref() {
|
||||
if candidates.contains(selected) {
|
||||
return Ok(Some(selected.to_string()));
|
||||
}
|
||||
clear_active_provider_on_connection(conn, codex_dir)?;
|
||||
}
|
||||
|
||||
if candidates.len() != 1 {
|
||||
return Ok(None);
|
||||
}
|
||||
let provider_id = candidates
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("one candidate must be present");
|
||||
remember_active_provider_on_connection(conn, codex_dir, provider_id)?;
|
||||
Ok(Some(provider_id.to_string()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn test_connection() -> Connection {
|
||||
let conn = Connection::open_in_memory().expect("open selection test database");
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE providers (id TEXT PRIMARY KEY);
|
||||
CREATE TABLE active_provider_selections (
|
||||
codex_dir TEXT PRIMARY KEY,
|
||||
provider_id TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
INSERT INTO providers (id) VALUES ('original'), ('copy'), ('other');",
|
||||
)
|
||||
.expect("create selection test schema");
|
||||
conn
|
||||
}
|
||||
|
||||
fn scope(name: &str) -> PathBuf {
|
||||
std::env::temp_dir().join(format!("codex-x-selection-{name}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_duplicate_does_not_replace_the_remembered_current_provider() {
|
||||
let conn = test_connection();
|
||||
let codex_dir = scope("duplicate");
|
||||
remember_active_provider_on_connection(&conn, &codex_dir, "original")
|
||||
.expect("remember original provider");
|
||||
|
||||
let active = reconcile_active_provider_on_connection(
|
||||
&conn,
|
||||
&codex_dir,
|
||||
&["original".to_string(), "copy".to_string()],
|
||||
)
|
||||
.expect("reconcile duplicate profiles");
|
||||
|
||||
assert_eq!(active.as_deref(), Some("original"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selections_are_independent_for_each_codex_directory() {
|
||||
let conn = test_connection();
|
||||
let first = scope("first");
|
||||
let second = scope("second");
|
||||
remember_active_provider_on_connection(&conn, &first, "original")
|
||||
.expect("remember first selection");
|
||||
remember_active_provider_on_connection(&conn, &second, "copy")
|
||||
.expect("remember second selection");
|
||||
let candidates = ["original".to_string(), "copy".to_string()];
|
||||
|
||||
assert_eq!(
|
||||
reconcile_active_provider_on_connection(&conn, &first, &candidates)
|
||||
.expect("reconcile first selection")
|
||||
.as_deref(),
|
||||
Some("original")
|
||||
);
|
||||
assert_eq!(
|
||||
reconcile_active_provider_on_connection(&conn, &second, &candidates)
|
||||
.expect("reconcile second selection")
|
||||
.as_deref(),
|
||||
Some("copy")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_selection_falls_back_only_when_the_live_match_is_unique() {
|
||||
let conn = test_connection();
|
||||
let codex_dir = scope("stale");
|
||||
remember_active_provider_on_connection(&conn, &codex_dir, "original")
|
||||
.expect("remember stale selection");
|
||||
|
||||
assert_eq!(
|
||||
reconcile_active_provider_on_connection(&conn, &codex_dir, &["other".to_string()])
|
||||
.expect("reconcile unique replacement")
|
||||
.as_deref(),
|
||||
Some("other")
|
||||
);
|
||||
assert_eq!(
|
||||
selected_provider_id_on_connection(&conn, &codex_dir)
|
||||
.expect("read repaired selection")
|
||||
.as_deref(),
|
||||
Some("other")
|
||||
);
|
||||
|
||||
assert!(
|
||||
reconcile_active_provider_on_connection(&conn, &codex_dir, &[])
|
||||
.expect("clear unmatched selection")
|
||||
.is_none()
|
||||
);
|
||||
assert!(selected_provider_id_on_connection(&conn, &codex_dir)
|
||||
.expect("read cleared selection")
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
use toml_edit::{value, Item, TableLike};
|
||||
|
||||
/// Match the official API exactly. A proxy that forwards DeepSeek may support
|
||||
/// WebSockets independently, so model names and partial host matches are unsafe.
|
||||
pub(crate) fn is_deepseek_http_endpoint(base_url: &str) -> bool {
|
||||
reqwest::Url::parse(base_url.trim()).is_ok_and(|url| {
|
||||
matches!(url.scheme(), "http" | "https") && url.host_str() == Some("api.deepseek.com")
|
||||
})
|
||||
}
|
||||
|
||||
/// A provider's WebSocket capability belongs to its endpoint, not the common
|
||||
/// Codex config inherited when creating a provider. Call before replacing URL.
|
||||
pub(super) fn configure_third_party_transport(
|
||||
table: &mut dyn TableLike,
|
||||
base_url: &str,
|
||||
own_template: bool,
|
||||
) {
|
||||
let same_endpoint = table
|
||||
.get("base_url")
|
||||
.and_then(Item::as_str)
|
||||
.is_some_and(|old| {
|
||||
super::store::canonical_provider_base_url(old)
|
||||
== super::store::canonical_provider_base_url(base_url)
|
||||
});
|
||||
let preserve_explicit = own_template
|
||||
&& same_endpoint
|
||||
&& !is_deepseek_http_endpoint(base_url)
|
||||
&& table
|
||||
.get("supports_websockets")
|
||||
.and_then(Item::as_bool)
|
||||
.is_some();
|
||||
if !preserve_explicit {
|
||||
// Explicit false also overrides Codex's built-in provider defaults if a
|
||||
// user-chosen provider ID happens to shadow a built-in provider.
|
||||
let decor = table
|
||||
.get("supports_websockets")
|
||||
.and_then(Item::as_value)
|
||||
.map(|value| value.decor().clone());
|
||||
let mut replacement = value(false);
|
||||
if let Some(decor) = decor {
|
||||
*replacement
|
||||
.as_value_mut()
|
||||
.expect("boolean value")
|
||||
.decor_mut() = decor;
|
||||
}
|
||||
table.insert("supports_websockets", replacement);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use toml_edit::Table;
|
||||
|
||||
#[test]
|
||||
fn deepseek_host_matching_does_not_disable_proxies() {
|
||||
assert!(is_deepseek_http_endpoint("https://api.deepseek.com/v1/"));
|
||||
assert!(is_deepseek_http_endpoint("HTTPS://API.DEEPSEEK.COM"));
|
||||
for endpoint in [
|
||||
"https://deepseek.proxy.example/v1",
|
||||
"https://api.deepseek.com.proxy.example/v1",
|
||||
"https://api.deepseek.com@proxy.example/v1",
|
||||
"https://proxy.example/api.deepseek.com",
|
||||
"invalid api.deepseek.com",
|
||||
] {
|
||||
assert!(!is_deepseek_http_endpoint(endpoint), "{endpoint}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoint_ownership_controls_websocket_inheritance() {
|
||||
for (source, destination, own, expected) in [
|
||||
(
|
||||
"https://proxy.example/v1",
|
||||
"https://proxy.example/v1/",
|
||||
true,
|
||||
true,
|
||||
),
|
||||
(
|
||||
"https://proxy.example/v1",
|
||||
"https://proxy.example/v1",
|
||||
false,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"https://old.example/v1",
|
||||
"https://new.example/v1",
|
||||
true,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"https://api.deepseek.com",
|
||||
"https://api.deepseek.com",
|
||||
true,
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let mut table = Table::new();
|
||||
table["base_url"] = value(source);
|
||||
table["supports_websockets"] = value(true);
|
||||
table["request_max_retries"] = value(9);
|
||||
configure_third_party_transport(&mut table, destination, own);
|
||||
assert_eq!(table["supports_websockets"].as_bool(), Some(expected));
|
||||
assert_eq!(table["request_max_retries"].as_integer(), Some(9));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -200,17 +200,6 @@ pub(super) fn create_provider_sync_backup(
|
||||
existed: path.exists(),
|
||||
});
|
||||
}
|
||||
for name in [
|
||||
"config.toml",
|
||||
".codex-global-state.json",
|
||||
".codex-global-state.json.bak",
|
||||
] {
|
||||
snapshots.push(copy_file_to_backup(
|
||||
codex_dir,
|
||||
&backup_dir,
|
||||
&codex_dir.join(name),
|
||||
)?);
|
||||
}
|
||||
for path in changed_rollouts {
|
||||
snapshots.push(copy_file_to_backup(codex_dir, &backup_dir, path)?);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
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))
|
||||
}
|
||||
|
||||
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}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the paths represented by this status only. The raw spelling remains
|
||||
/// the map key. Persistent home scope uses native identity only when birth time
|
||||
/// was verified; otherwise it conservatively follows the original home path.
|
||||
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(|| directory_identity(path));
|
||||
}
|
||||
(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,17 +1,3 @@
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::{atomic_write, io_err, json_err, write_text};
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct GlobalStateWrite {
|
||||
pub(super) path: std::path::PathBuf,
|
||||
pub(super) original_bytes: Option<Vec<u8>>,
|
||||
pub(super) written_bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
pub(super) fn normalize_workspace_path(value: &str) -> Option<String> {
|
||||
let trimmed = value.trim();
|
||||
if trimmed.is_empty() {
|
||||
@@ -26,313 +12,3 @@ pub(super) fn normalize_workspace_path(value: &str) -> Option<String> {
|
||||
}
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
|
||||
fn load_global_state(path: &Path) -> Result<Map<String, Value>> {
|
||||
if !path.exists() {
|
||||
return Ok(Map::new());
|
||||
}
|
||||
let text = fs::read_to_string(path).map_err(|error| io_err(path, error))?;
|
||||
let value = serde_json::from_str::<Value>(&text).map_err(|error| json_err(path, error))?;
|
||||
Ok(value.as_object().cloned().unwrap_or_default())
|
||||
}
|
||||
|
||||
pub(super) fn projectless_thread_ids(path: &Path) -> Result<HashSet<String>> {
|
||||
let state = load_global_state(path)?;
|
||||
Ok(state
|
||||
.get("projectless-thread-ids")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(ToString::to_string)
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn normalized_path_array(value: &Value) -> Vec<String> {
|
||||
if let Some(items) = value.as_array() {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.filter_map(normalize_workspace_path)
|
||||
.collect()
|
||||
} else {
|
||||
value
|
||||
.as_str()
|
||||
.and_then(normalize_workspace_path)
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn dedupe_workspace_paths(paths: Vec<String>) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
paths
|
||||
.into_iter()
|
||||
.filter(|path| {
|
||||
seen.insert(
|
||||
path.replace('/', r"\")
|
||||
.trim_end_matches('\\')
|
||||
.to_ascii_lowercase(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn normalized_global_state(state: &Map<String, Value>) -> Map<String, Value> {
|
||||
let mut next = Map::new();
|
||||
for key in ["electron-saved-workspace-roots", "project-order"] {
|
||||
if let Some(value) = state.get(key) {
|
||||
next.insert(
|
||||
key.to_string(),
|
||||
json!(dedupe_workspace_paths(normalized_path_array(value))),
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(value) = state.get("active-workspace-roots") {
|
||||
let normalized = dedupe_workspace_paths(normalized_path_array(value));
|
||||
let next_value = if value.is_array() {
|
||||
json!(normalized)
|
||||
} else if let Some(first) = normalized.first() {
|
||||
json!(first)
|
||||
} else {
|
||||
value.clone()
|
||||
};
|
||||
next.insert("active-workspace-roots".to_string(), next_value);
|
||||
}
|
||||
if let Some(labels) = state
|
||||
.get("electron-workspace-root-labels")
|
||||
.and_then(Value::as_object)
|
||||
{
|
||||
let mut normalized = Map::new();
|
||||
for (path, value) in labels {
|
||||
normalized.insert(
|
||||
normalize_workspace_path(path).unwrap_or_else(|| path.clone()),
|
||||
value.clone(),
|
||||
);
|
||||
}
|
||||
next.insert(
|
||||
"electron-workspace-root-labels".to_string(),
|
||||
Value::Object(normalized),
|
||||
);
|
||||
}
|
||||
if let Some(open_targets) = state
|
||||
.get("open-in-target-preferences")
|
||||
.and_then(Value::as_object)
|
||||
{
|
||||
let mut normalized = open_targets.clone();
|
||||
if let Some(per_path) = open_targets.get("perPath").and_then(Value::as_object) {
|
||||
let mut normalized_per_path = Map::new();
|
||||
for (path, value) in per_path {
|
||||
normalized_per_path.insert(
|
||||
normalize_workspace_path(path).unwrap_or_else(|| path.clone()),
|
||||
value.clone(),
|
||||
);
|
||||
}
|
||||
normalized.insert("perPath".to_string(), Value::Object(normalized_per_path));
|
||||
}
|
||||
next.insert(
|
||||
"open-in-target-preferences".to_string(),
|
||||
Value::Object(normalized),
|
||||
);
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
pub(super) fn count_global_state_updates(path: &Path) -> Result<usize> {
|
||||
let state = load_global_state(path)?;
|
||||
let next = normalized_global_state(&state);
|
||||
Ok(next
|
||||
.iter()
|
||||
.filter(|(key, value)| state.get(*key) != Some(*value))
|
||||
.count())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn apply_global_state_update(path: &Path) -> Result<usize> {
|
||||
apply_global_state_update_with_journal(path, &mut Vec::new(), &mut || Ok(()))
|
||||
}
|
||||
|
||||
fn read_optional_bytes(path: &Path) -> Result<Option<Vec<u8>>> {
|
||||
match fs::read(path) {
|
||||
Ok(bytes) => Ok(Some(bytes)),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(error) => Err(io_err(path, error)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn apply_global_state_update_with_journal<F>(
|
||||
path: &Path,
|
||||
writes: &mut Vec<GlobalStateWrite>,
|
||||
after_main_write: &mut F,
|
||||
) -> Result<usize>
|
||||
where
|
||||
F: FnMut() -> Result<()>,
|
||||
{
|
||||
let original_bytes = read_optional_bytes(path)?;
|
||||
let mut state = match &original_bytes {
|
||||
Some(bytes) => serde_json::from_slice::<Value>(bytes)
|
||||
.map_err(|error| json_err(path, error))?
|
||||
.as_object()
|
||||
.cloned()
|
||||
.unwrap_or_default(),
|
||||
None => Map::new(),
|
||||
};
|
||||
let next = normalized_global_state(&state);
|
||||
let updated = next
|
||||
.iter()
|
||||
.filter(|(key, value)| state.get(*key) != Some(*value))
|
||||
.count();
|
||||
if updated > 0 {
|
||||
for (key, value) in next {
|
||||
state.insert(key, value);
|
||||
}
|
||||
let text = serde_json::to_string_pretty(&Value::Object(state))
|
||||
.map_err(|error| json_err(path, error))?;
|
||||
let written_bytes = text.as_bytes().to_vec();
|
||||
if read_optional_bytes(path)? != original_bytes {
|
||||
return Err(CodexxError::Config(
|
||||
"全局状态已发生变化,请重试。".to_string(),
|
||||
));
|
||||
}
|
||||
write_text(path, &text)?;
|
||||
writes.push(GlobalStateWrite {
|
||||
path: path.to_path_buf(),
|
||||
original_bytes,
|
||||
written_bytes: written_bytes.clone(),
|
||||
});
|
||||
after_main_write()?;
|
||||
if let Some(parent) = path.parent() {
|
||||
let backup = parent.join(".codex-global-state.json.bak");
|
||||
let original_bytes = read_optional_bytes(&backup)?;
|
||||
if read_optional_bytes(&backup)? != original_bytes {
|
||||
return Err(CodexxError::Config(
|
||||
"全局状态已发生变化,请重试。".to_string(),
|
||||
));
|
||||
}
|
||||
write_text(&backup, &text)?;
|
||||
writes.push(GlobalStateWrite {
|
||||
path: backup,
|
||||
original_bytes,
|
||||
written_bytes,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
pub(super) fn restore_global_write(write: &GlobalStateWrite) -> Result<()> {
|
||||
match fs::read(&write.path) {
|
||||
Ok(current) if current == write.written_bytes => {}
|
||||
Ok(_) => {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"全局状态已发生变化,无法安全恢复: {}",
|
||||
write.path.display()
|
||||
)));
|
||||
}
|
||||
Err(error)
|
||||
if error.kind() == std::io::ErrorKind::NotFound && write.original_bytes.is_none() =>
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
Err(error) => return Err(io_err(&write.path, error)),
|
||||
}
|
||||
|
||||
if let Some(original) = &write.original_bytes {
|
||||
atomic_write(&write.path, original)
|
||||
} else {
|
||||
fs::remove_file(&write.path).map_err(|error| io_err(&write.path, error))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"codex-x-global-state-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create test directory");
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_state_update_keeps_unknown_fields_and_matches_backup() {
|
||||
let dir = temp_dir("update");
|
||||
let path = dir.join(".codex-global-state.json");
|
||||
fs::write(
|
||||
&path,
|
||||
r#"{
|
||||
"electron-saved-workspace-roots": "/tmp/project",
|
||||
"unrelated-setting": { "enabled": true }
|
||||
}"#,
|
||||
)
|
||||
.expect("write original global state");
|
||||
|
||||
assert_eq!(
|
||||
apply_global_state_update(&path).expect("update global state"),
|
||||
1
|
||||
);
|
||||
|
||||
let main_text = fs::read_to_string(&path).expect("read global state");
|
||||
let backup_path = dir.join(".codex-global-state.json.bak");
|
||||
let backup_text = fs::read_to_string(&backup_path).expect("read global state backup");
|
||||
assert_eq!(main_text, backup_text);
|
||||
let state: Value = serde_json::from_str(&main_text).expect("parse global state");
|
||||
assert_eq!(
|
||||
state.get("electron-saved-workspace-roots"),
|
||||
Some(&json!(["/tmp/project"]))
|
||||
);
|
||||
assert_eq!(
|
||||
state.get("unrelated-setting"),
|
||||
Some(&json!({ "enabled": true }))
|
||||
);
|
||||
|
||||
fs::remove_dir_all(dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restores_distinct_existing_global_main_and_backup() {
|
||||
let dir = temp_dir("distinct-snapshots");
|
||||
let main = dir.join(".codex-global-state.json");
|
||||
let backup = dir.join(".codex-global-state.json.bak");
|
||||
let original_main = br#"{"source":"main","value":1}"#;
|
||||
let original_backup = br#"{"source":"backup","value":2}"#;
|
||||
let written_text = r#"{"source":"mutated"}"#.to_string();
|
||||
fs::write(&main, original_main).expect("write original main");
|
||||
fs::write(&backup, original_backup).expect("write original backup");
|
||||
write_text(&main, &written_text).expect("mutate global main");
|
||||
write_text(&backup, &written_text).expect("mutate global backup");
|
||||
let writes = [
|
||||
GlobalStateWrite {
|
||||
path: main.clone(),
|
||||
original_bytes: Some(original_main.to_vec()),
|
||||
written_bytes: written_text.as_bytes().to_vec(),
|
||||
},
|
||||
GlobalStateWrite {
|
||||
path: backup.clone(),
|
||||
original_bytes: Some(original_backup.to_vec()),
|
||||
written_bytes: written_text.into_bytes(),
|
||||
},
|
||||
];
|
||||
|
||||
for write in writes.iter().rev() {
|
||||
restore_global_write(write).expect("restore global write");
|
||||
}
|
||||
assert_eq!(fs::read(&main).expect("read restored main"), original_main);
|
||||
assert_eq!(
|
||||
fs::read(&backup).expect("read restored backup"),
|
||||
original_backup
|
||||
);
|
||||
|
||||
fs::remove_dir_all(dir).expect("remove test directory");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
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;
|
||||
@@ -14,11 +18,16 @@ pub(crate) use backup::{
|
||||
#[cfg(test)]
|
||||
pub(crate) use delete::{active_session_ids_present, hard_delete_sessions_locally};
|
||||
pub(crate) use delete::{delete_codex_sessions_inner, SessionDeleteInput, SessionDeleteResult};
|
||||
pub(crate) use storage::sqlite_candidate_paths;
|
||||
pub(crate) use export::{export_codex_sessions_inner, SessionExportResult};
|
||||
#[cfg(test)]
|
||||
pub(crate) use storage::{
|
||||
apply_session_changes, list_session_previews, restore_session_changes, scan_rollouts,
|
||||
scan_sqlite, sqlite_session_db_paths,
|
||||
};
|
||||
pub(crate) use storage::{
|
||||
session_project_title, session_titles_by_id, source_kind_is_internal, sqlite_candidate_paths,
|
||||
sqlite_candidate_paths_with_timeout, thread_source_is_internal, usage_thread_identities,
|
||||
UsageThreadIdentity,
|
||||
};
|
||||
pub(crate) use sync::{session_sync_status_inner, sync_sessions_provider_inner};
|
||||
pub(crate) use types::{SessionSyncResult, SessionSyncStatus};
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
use super::global_state::{
|
||||
apply_global_state_update_with_journal, restore_global_write, GlobalStateWrite,
|
||||
use super::catalog::{
|
||||
apply_catalog_updates, catalog_columns, create_catalog_rollback_tables,
|
||||
restore_catalog_updates, CatalogRepairThread,
|
||||
};
|
||||
use super::storage::{
|
||||
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::storage::{apply_session_changes, restore_session_changes};
|
||||
use super::types::{RolloutScan, SessionFileChange};
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::io_err;
|
||||
use crate::sqlite_utils::{sqlite_has_table, table_column_set};
|
||||
use rusqlite::{Connection, OpenFlags};
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -15,24 +19,26 @@ use std::time::Duration;
|
||||
pub(super) struct SqliteUpdateCounts {
|
||||
provider_rows: usize,
|
||||
cwd_rows: usize,
|
||||
catalog_insert_rows: usize,
|
||||
}
|
||||
|
||||
impl SqliteUpdateCounts {
|
||||
pub(super) fn total(&self) -> usize {
|
||||
self.provider_rows + self.cwd_rows
|
||||
self.provider_rows + self.cwd_rows + self.catalog_insert_rows
|
||||
}
|
||||
|
||||
fn add(&mut self, other: Self) {
|
||||
self.provider_rows += other.provider_rows;
|
||||
self.cwd_rows += other.cwd_rows;
|
||||
self.catalog_insert_rows += other.catalog_insert_rows;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct MutationJournal {
|
||||
applied_rollouts: Vec<SessionFileChange>,
|
||||
expected_rollout_hashes: HashMap<PathBuf, [u8; 32]>,
|
||||
sqlite_restore_attempts: Vec<SqliteRestoreAttempt>,
|
||||
global_writes: Vec<GlobalStateWrite>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -45,7 +51,8 @@ pub(super) struct PendingSqliteUpdate {
|
||||
path: PathBuf,
|
||||
conn: Connection,
|
||||
observer: Connection,
|
||||
columns: HashSet<String>,
|
||||
thread_columns: HashSet<String>,
|
||||
catalog_columns: HashSet<String>,
|
||||
counts: SqliteUpdateCounts,
|
||||
transaction_open: bool,
|
||||
}
|
||||
@@ -80,7 +87,8 @@ fn create_sqlite_rollback_table(conn: &Connection) -> Result<()> {
|
||||
cwd_changed INTEGER NOT NULL DEFAULT 0
|
||||
);",
|
||||
)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
create_catalog_rollback_tables(conn)
|
||||
}
|
||||
|
||||
pub(super) fn prepare_sqlite_updates(sqlite_paths: &[PathBuf]) -> Result<Vec<PendingSqliteUpdate>> {
|
||||
@@ -107,11 +115,17 @@ pub(super) fn prepare_sqlite_updates(sqlite_paths: &[PathBuf]) -> Result<Vec<Pen
|
||||
})?;
|
||||
conn.busy_timeout(Duration::from_secs(5))
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
if !sqlite_has_table(&conn, "threads")? {
|
||||
continue;
|
||||
}
|
||||
let columns = table_column_set(&conn, "threads")?;
|
||||
if !columns.contains("id") || !columns.contains("model_provider") {
|
||||
let thread_columns = if sqlite_has_table(&conn, "threads")? {
|
||||
table_column_set(&conn, "threads")?
|
||||
} else {
|
||||
HashSet::new()
|
||||
};
|
||||
let catalog_columns = catalog_columns(&conn)?;
|
||||
let supports_thread_updates =
|
||||
thread_columns.contains("id") && thread_columns.contains("model_provider");
|
||||
let supports_catalog_updates =
|
||||
catalog_columns.contains("thread_id") && catalog_columns.contains("model_provider");
|
||||
if !supports_thread_updates && !supports_catalog_updates {
|
||||
continue;
|
||||
}
|
||||
conn.execute_batch("BEGIN IMMEDIATE")
|
||||
@@ -147,7 +161,8 @@ pub(super) fn prepare_sqlite_updates(sqlite_paths: &[PathBuf]) -> Result<Vec<Pen
|
||||
path: identity,
|
||||
conn,
|
||||
observer,
|
||||
columns,
|
||||
thread_columns,
|
||||
catalog_columns,
|
||||
counts: SqliteUpdateCounts::default(),
|
||||
transaction_open: true,
|
||||
});
|
||||
@@ -165,53 +180,98 @@ fn apply_sqlite_updates(
|
||||
pending: &mut [PendingSqliteUpdate],
|
||||
rollouts: &RolloutScan,
|
||||
target_provider: &str,
|
||||
catalog_sources: &HashMap<String, CatalogRepairThread>,
|
||||
syncable_thread_ids: &HashSet<String>,
|
||||
) -> Result<()> {
|
||||
let mut sorted_thread_ids = syncable_thread_ids.iter().collect::<Vec<_>>();
|
||||
sorted_thread_ids.sort();
|
||||
for update in pending.iter_mut() {
|
||||
update
|
||||
.conn
|
||||
.execute(
|
||||
let internal_ids = if update.thread_columns.contains("id") {
|
||||
sqlite_subagent_thread_ids(&update.conn, &update.thread_columns)?
|
||||
} else {
|
||||
HashSet::new()
|
||||
};
|
||||
if update.thread_columns.contains("id") && update.thread_columns.contains("model_provider")
|
||||
{
|
||||
let archived_filter = if update.thread_columns.contains("archived") {
|
||||
" AND COALESCE(archived, 0) = 0"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let snapshot_sql = format!(
|
||||
"INSERT INTO temp.codexx_session_rollback
|
||||
(id, model_provider, provider_changed)
|
||||
SELECT id, model_provider, 1 FROM threads
|
||||
WHERE COALESCE(model_provider, '') <> ?1
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
model_provider = excluded.model_provider,
|
||||
provider_changed = 1",
|
||||
[target_provider],
|
||||
)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
update.counts.provider_rows = update
|
||||
.conn
|
||||
.execute(
|
||||
"UPDATE threads SET model_provider = ?1 WHERE COALESCE(model_provider, '') <> ?1",
|
||||
[target_provider],
|
||||
)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
|
||||
if update.columns.contains("id") && update.columns.contains("cwd") {
|
||||
for (thread_id, cwd) in &rollouts.cwd_by_thread_id {
|
||||
(id, model_provider, provider_changed)
|
||||
SELECT id, model_provider, 1 FROM threads
|
||||
WHERE id = ?2 AND COALESCE(model_provider, '') <> ?1{archived_filter}
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
model_provider = excluded.model_provider,
|
||||
provider_changed = 1"
|
||||
);
|
||||
let update_sql = format!(
|
||||
"UPDATE threads SET model_provider = ?1 \
|
||||
WHERE id = ?2 AND COALESCE(model_provider, '') <> ?1{archived_filter}"
|
||||
);
|
||||
for thread_id in &sorted_thread_ids {
|
||||
if internal_ids.contains(*thread_id) {
|
||||
continue;
|
||||
}
|
||||
update
|
||||
.conn
|
||||
.execute(
|
||||
"INSERT INTO temp.codexx_session_rollback
|
||||
(id, cwd, cwd_changed)
|
||||
SELECT id, cwd, 1 FROM threads
|
||||
WHERE id = ?2 AND COALESCE(cwd, '') <> ?1
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
cwd = excluded.cwd,
|
||||
cwd_changed = 1",
|
||||
(cwd, thread_id),
|
||||
)
|
||||
.execute(&snapshot_sql, (target_provider, thread_id))
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
update.counts.cwd_rows += update
|
||||
update.counts.provider_rows += update
|
||||
.conn
|
||||
.execute(
|
||||
"UPDATE threads SET cwd = ?1 WHERE id = ?2 AND COALESCE(cwd, '') <> ?1",
|
||||
(cwd, thread_id),
|
||||
)
|
||||
.execute(&update_sql, (target_provider, thread_id))
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
}
|
||||
}
|
||||
|
||||
if update.thread_columns.contains("id") && update.thread_columns.contains("cwd") {
|
||||
let archived_filter = if update.thread_columns.contains("archived") {
|
||||
" AND COALESCE(archived, 0) = 0"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let snapshot_sql = format!(
|
||||
"INSERT INTO temp.codexx_session_rollback
|
||||
(id, cwd, cwd_changed)
|
||||
SELECT id, cwd, 1 FROM threads
|
||||
WHERE id = ?2 AND COALESCE(cwd, '') <> ?1{archived_filter}
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
cwd = excluded.cwd,
|
||||
cwd_changed = 1"
|
||||
);
|
||||
let update_sql = format!(
|
||||
"UPDATE threads SET cwd = ?1 \
|
||||
WHERE id = ?2 AND COALESCE(cwd, '') <> ?1{archived_filter}"
|
||||
);
|
||||
for (thread_id, cwd) in &rollouts.cwd_by_thread_id {
|
||||
if !syncable_thread_ids.contains(thread_id) || internal_ids.contains(thread_id) {
|
||||
continue;
|
||||
}
|
||||
update
|
||||
.conn
|
||||
.execute(&snapshot_sql, (cwd, thread_id))
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
update.counts.cwd_rows += update
|
||||
.conn
|
||||
.execute(&update_sql, (cwd, thread_id))
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
}
|
||||
}
|
||||
let local_syncable_ids = syncable_thread_ids
|
||||
.difference(&internal_ids)
|
||||
.cloned()
|
||||
.collect();
|
||||
let catalog_counts = apply_catalog_updates(
|
||||
&update.conn,
|
||||
&update.catalog_columns,
|
||||
target_provider,
|
||||
catalog_sources,
|
||||
&local_syncable_ids,
|
||||
)?;
|
||||
update.counts.provider_rows += catalog_counts.provider_rows;
|
||||
update.counts.catalog_insert_rows += catalog_counts.inserted_rows;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -226,6 +286,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(),
|
||||
@@ -252,6 +313,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)
|
||||
}
|
||||
|
||||
@@ -273,18 +337,23 @@ fn restore_sqlite_update(
|
||||
)));
|
||||
}
|
||||
|
||||
let mut statements = vec![
|
||||
"UPDATE threads
|
||||
SET model_provider = (
|
||||
SELECT rollback.model_provider
|
||||
FROM temp.codexx_session_rollback AS rollback
|
||||
WHERE rollback.id = threads.id
|
||||
)
|
||||
WHERE id IN (
|
||||
SELECT id FROM temp.codexx_session_rollback WHERE provider_changed = 1
|
||||
)",
|
||||
];
|
||||
if update.columns.contains("cwd") {
|
||||
restore_catalog_updates(&update.conn, &update.catalog_columns)?;
|
||||
let mut statements = Vec::new();
|
||||
if update.thread_columns.contains("id") && update.thread_columns.contains("model_provider")
|
||||
{
|
||||
statements.push(
|
||||
"UPDATE threads
|
||||
SET model_provider = (
|
||||
SELECT rollback.model_provider
|
||||
FROM temp.codexx_session_rollback AS rollback
|
||||
WHERE rollback.id = threads.id
|
||||
)
|
||||
WHERE id IN (
|
||||
SELECT id FROM temp.codexx_session_rollback WHERE provider_changed = 1
|
||||
)",
|
||||
);
|
||||
}
|
||||
if update.thread_columns.contains("id") && update.thread_columns.contains("cwd") {
|
||||
statements.push(
|
||||
"UPDATE threads
|
||||
SET cwd = (
|
||||
@@ -321,11 +390,6 @@ pub(super) fn rollback_mutation(
|
||||
pending_sqlite: &mut [PendingSqliteUpdate],
|
||||
) -> Vec<String> {
|
||||
let mut errors = Vec::new();
|
||||
for write in journal.global_writes.iter().rev() {
|
||||
if let Err(error) = restore_global_write(write) {
|
||||
errors.push(error.to_string());
|
||||
}
|
||||
}
|
||||
for attempt in journal.sqlite_restore_attempts.iter().rev() {
|
||||
let Some(update) = pending_sqlite
|
||||
.iter_mut()
|
||||
@@ -357,21 +421,93 @@ pub(super) fn mutation_error(original: CodexxError, recovery_errors: Vec<String>
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum MutationPoint {
|
||||
BeforeSqliteLock,
|
||||
BeforeRolloutMutation,
|
||||
BeforeEachRolloutMutation(usize),
|
||||
AfterRolloutMutation,
|
||||
AfterSqliteCommit(usize),
|
||||
AfterGlobalMainWrite,
|
||||
}
|
||||
|
||||
pub(super) struct MutationResult {
|
||||
pub(super) applied_rollouts: usize,
|
||||
pub(super) skipped_rollouts: Vec<PathBuf>,
|
||||
pub(super) sqlite_updates: SqliteUpdateCounts,
|
||||
}
|
||||
|
||||
// A file may be reclassified after scanning. In particular, the general file
|
||||
// writer skips concurrently changed rollouts; that must not leave their old IDs
|
||||
// eligible for a catalog insert or a provider update in this transaction.
|
||||
fn validate_rollout_classification(rollouts: &RolloutScan) -> Result<()> {
|
||||
let mut paths = rollouts.provider_candidate_paths.clone();
|
||||
for change in &rollouts.changes {
|
||||
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(),
|
||||
));
|
||||
}
|
||||
paths.insert(change.path.clone());
|
||||
}
|
||||
for path in paths {
|
||||
if !rollout_path_has_syncable_identity(&path)? {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"会话类型已变化,已停止同步;请重新检查会话:{}",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
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 {
|
||||
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],
|
||||
target_provider: &str,
|
||||
global_state_path: &Path,
|
||||
catalog_sources: &HashMap<String, CatalogRepairThread>,
|
||||
syncable_thread_ids: &HashSet<String>,
|
||||
journal: &mut MutationJournal,
|
||||
hook: &mut F,
|
||||
) -> Result<MutationResult>
|
||||
@@ -379,18 +515,45 @@ where
|
||||
F: FnMut(MutationPoint) -> Result<()>,
|
||||
{
|
||||
let result = (|| -> Result<MutationResult> {
|
||||
let (applied_rollouts, skipped_rollouts) = apply_session_changes(&rollouts.changes)?;
|
||||
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)?;
|
||||
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;
|
||||
apply_sqlite_updates(pending_sqlite, rollouts, target_provider)?;
|
||||
apply_global_state_update_with_journal(
|
||||
global_state_path,
|
||||
&mut journal.global_writes,
|
||||
&mut || hook(MutationPoint::AfterGlobalMainWrite),
|
||||
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,
|
||||
target_provider,
|
||||
catalog_sources,
|
||||
syncable_thread_ids,
|
||||
)?;
|
||||
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!(
|
||||
@@ -18,6 +21,8 @@ fn temp_dir(name: &str) -> PathBuf {
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create test directory");
|
||||
fs::write(path.join("config.toml"), "model_provider = \"custom\"\n")
|
||||
.expect("write shared provider config");
|
||||
path
|
||||
}
|
||||
|
||||
@@ -71,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");
|
||||
@@ -176,7 +808,8 @@ fn failed_sqlite_commit_rolls_back_without_snapshot_restore() {
|
||||
path: database.clone(),
|
||||
conn,
|
||||
observer,
|
||||
columns: HashSet::new(),
|
||||
thread_columns: HashSet::new(),
|
||||
catalog_columns: HashSet::new(),
|
||||
counts: SqliteUpdateCounts::default(),
|
||||
transaction_open: true,
|
||||
}];
|
||||
@@ -332,53 +965,7 @@ fn sqlite_prepare_deduplicates_symlink_aliases() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_main_failpoint_restores_prior_mutations_without_touching_backup() {
|
||||
let codex_dir = temp_dir("global-main-failpoint");
|
||||
let id = "019f6000-0000-7000-8000-000000000408";
|
||||
let rollout = codex_dir.join(format!("sessions/rollout-test-{id}.jsonl"));
|
||||
let original_rollout = write_rollout(&rollout, id);
|
||||
let database = codex_dir.join("state_10.sqlite");
|
||||
create_thread_database(&database, id, &rollout);
|
||||
let global = codex_dir.join(".codex-global-state.json");
|
||||
let global_backup = codex_dir.join(".codex-global-state.json.bak");
|
||||
let original_global = br#"{"electron-saved-workspace-roots":"/tmp/project"}"#;
|
||||
fs::write(&global, original_global).expect("write original global state");
|
||||
assert!(!global_backup.exists());
|
||||
|
||||
let error = sync_sessions_provider_with_hook(
|
||||
Some(codex_dir.display().to_string()),
|
||||
Some("custom".to_string()),
|
||||
|point| match point {
|
||||
MutationPoint::AfterGlobalMainWrite => {
|
||||
assert_eq!(thread_provider(&database, id), "openai");
|
||||
assert!(fs::read_to_string(&rollout)
|
||||
.expect("read mutated rollout")
|
||||
.contains("\"model_provider\":\"custom\""));
|
||||
assert!(!global_backup.exists());
|
||||
Err(CodexxError::Config("主状态写入后注入失败".to_string()))
|
||||
}
|
||||
_ => Ok(()),
|
||||
},
|
||||
)
|
||||
.expect_err("fail after global main write");
|
||||
|
||||
assert_eq!(error.to_string(), "配置错误: 主状态写入后注入失败");
|
||||
assert_eq!(thread_provider(&database, id), "openai");
|
||||
assert_eq!(
|
||||
fs::read(&rollout).expect("read restored rollout"),
|
||||
original_rollout
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(&global).expect("read restored global"),
|
||||
original_global
|
||||
);
|
||||
assert!(!global_backup.exists());
|
||||
|
||||
fs::remove_dir_all(codex_dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn injected_failure_restores_sqlite_jsonl_and_global_state() {
|
||||
fn injected_failure_restores_sqlite_and_jsonl_without_touching_global_state() {
|
||||
let codex_dir = temp_dir("full-mutation-rollback");
|
||||
let id = "019f6000-0000-7000-8000-000000000411";
|
||||
let rollout = codex_dir.join(format!("sessions/rollout-test-{id}.jsonl"));
|
||||
@@ -440,10 +1027,11 @@ fn injected_failure_restores_sqlite_jsonl_and_global_state() {
|
||||
assert!(fs::read_to_string(&rollout)
|
||||
.expect("read mutated rollout")
|
||||
.contains("\"model_provider\":\"custom\""));
|
||||
let main = fs::read_to_string(&global).expect("read mutated global state");
|
||||
let backup =
|
||||
fs::read_to_string(&global_backup).expect("read mutated global backup");
|
||||
assert_eq!(main, backup);
|
||||
assert_eq!(
|
||||
fs::read(&global).expect("read untouched global state"),
|
||||
original_global
|
||||
);
|
||||
assert!(!global_backup.exists());
|
||||
Err(CodexxError::Config("测试注入失败".to_string()))
|
||||
}
|
||||
_ => Ok(()),
|
||||
@@ -478,11 +1066,105 @@ fn injected_failure_restores_sqlite_jsonl_and_global_state() {
|
||||
original_global
|
||||
);
|
||||
assert!(!global_backup.exists());
|
||||
assert!(fs::read_dir(provider_sync_backup_root(&codex_dir))
|
||||
let retained_backup = fs::read_dir(provider_sync_backup_root(&codex_dir))
|
||||
.expect("read retained provider sync backup")
|
||||
.next()
|
||||
.is_some());
|
||||
.expect("retained provider sync backup")
|
||||
.expect("read retained provider sync backup entry")
|
||||
.path();
|
||||
let metadata = fs::read_to_string(retained_backup.join("metadata.json"))
|
||||
.expect("read retained provider sync metadata");
|
||||
assert!(!metadata.contains("config.toml"));
|
||||
assert!(!metadata.contains(".codex-global-state.json"));
|
||||
assert!(!retained_backup.join("config.toml").exists());
|
||||
assert!(!retained_backup.join(".codex-global-state.json").exists());
|
||||
|
||||
drop(wal_guard);
|
||||
fs::remove_dir_all(codex_dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_reclassification_before_mutation_aborts_without_registering_or_rewriting() {
|
||||
for existing_provider in ["openai", "custom"] {
|
||||
let codex_dir = temp_dir("internal-before-mutation");
|
||||
let id = "019f6000-0000-7000-8000-000000000980";
|
||||
let rollout = codex_dir.join(format!("sessions/rollout-test-{id}.jsonl"));
|
||||
let existing = String::from_utf8(write_rollout(&rollout, id))
|
||||
.expect("UTF-8 fixture")
|
||||
.replace("openai", existing_provider);
|
||||
fs::write(&rollout, existing).expect("set current rollout provider");
|
||||
let database = codex_dir.join("state_10.sqlite");
|
||||
create_thread_database(&database, id, &rollout);
|
||||
let internal = format!(
|
||||
"{}\n",
|
||||
serde_json::json!({"type":"session_meta", "payload":{
|
||||
"id":id, "model_provider":existing_provider, "source":{"internal":"guardian"}
|
||||
}})
|
||||
);
|
||||
let error = sync_sessions_provider_with_hook(
|
||||
Some(codex_dir.display().to_string()),
|
||||
None,
|
||||
|point| {
|
||||
if point == MutationPoint::BeforeRolloutMutation {
|
||||
fs::write(&rollout, &internal).expect("reclassify rollout during sync");
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.expect_err("reclassification must abort sync");
|
||||
assert!(error.to_string().contains("会话类型已变化"), "{error}");
|
||||
assert_eq!(thread_provider(&database, id), "openai");
|
||||
assert_eq!(
|
||||
fs::read_to_string(&rollout).expect("read internal rollout"),
|
||||
internal
|
||||
);
|
||||
fs::remove_dir_all(codex_dir).expect("remove race fixture");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_reclassification_after_file_writes_rolls_back_other_files_and_all_databases() {
|
||||
let codex_dir = temp_dir("internal-after-rollout-mutation");
|
||||
let parent = "019f6000-0000-7000-8000-000000000981";
|
||||
let child = "019f6000-0000-7000-8000-000000000982";
|
||||
let parent_rollout = codex_dir.join(format!("sessions/rollout-test-{parent}.jsonl"));
|
||||
let child_rollout = codex_dir.join(format!("sessions/rollout-test-{child}.jsonl"));
|
||||
let original_parent = write_rollout(&parent_rollout, parent);
|
||||
write_rollout(&child_rollout, child);
|
||||
let database = codex_dir.join("state_10.sqlite");
|
||||
create_thread_database(&database, parent, &parent_rollout);
|
||||
Connection::open(&database)
|
||||
.expect("open fixture index")
|
||||
.execute(
|
||||
"INSERT INTO threads (id, model_provider, rollout_path) VALUES (?1, 'openai', ?2)",
|
||||
(child, child_rollout.display().to_string()),
|
||||
)
|
||||
.expect("insert second thread");
|
||||
let internal = format!(
|
||||
"{}\n",
|
||||
serde_json::json!({"type":"session_meta", "payload":{
|
||||
"id":child, "model_provider":"openai", "source":{"internal":"guardian"}
|
||||
}})
|
||||
);
|
||||
let error =
|
||||
sync_sessions_provider_with_hook(Some(codex_dir.display().to_string()), None, |point| {
|
||||
if point == MutationPoint::AfterRolloutMutation {
|
||||
fs::write(&child_rollout, &internal)
|
||||
.expect("publish internal metadata during sync");
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("reclassification must prevent database commits");
|
||||
assert!(error.to_string().contains("会话类型已变化"), "{error}");
|
||||
assert_eq!(thread_provider(&database, parent), "openai");
|
||||
assert_eq!(thread_provider(&database, child), "openai");
|
||||
assert_eq!(
|
||||
fs::read(&parent_rollout).expect("read restored parent"),
|
||||
original_parent
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(&child_rollout).expect("preserve newer internal source"),
|
||||
internal
|
||||
);
|
||||
fs::remove_dir_all(codex_dir).expect("remove rollback fixture");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
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,
|
||||
@@ -33,7 +39,10 @@ pub(crate) struct SessionSyncStatus {
|
||||
pub(crate) top_level_threads: usize,
|
||||
pub(crate) subagent_threads: usize,
|
||||
pub(crate) mismatched_threads: usize,
|
||||
pub(crate) mismatched_sessions: usize,
|
||||
pub(crate) needs_sync: bool,
|
||||
pub(crate) scan_complete: bool,
|
||||
pub(crate) scan_failures: Vec<String>,
|
||||
pub(crate) backup_dir: Option<String>,
|
||||
pub(crate) warnings: Vec<String>,
|
||||
pub(crate) sessions: Vec<SessionPreview>,
|
||||
@@ -50,13 +59,27 @@ pub(crate) struct SessionSyncResult {
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct RolloutScan {
|
||||
pub(crate) discovered_rollout_files: usize,
|
||||
pub(crate) rollout_files: usize,
|
||||
pub(crate) session_meta_count: usize,
|
||||
pub(crate) mismatched_rollouts: usize,
|
||||
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
|
||||
/// even when the rollout is excluded from provider synchronization.
|
||||
pub(crate) internal_thread_ids: HashSet<String>,
|
||||
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)]
|
||||
@@ -65,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)]
|
||||
@@ -74,5 +115,12 @@ pub(crate) struct SqliteScan {
|
||||
pub(crate) top_level_threads: usize,
|
||||
pub(crate) subagent_threads: usize,
|
||||
pub(crate) mismatched_threads: usize,
|
||||
pub(crate) thread_ids: HashSet<String>,
|
||||
pub(crate) syncable_thread_ids: HashSet<String>,
|
||||
pub(crate) archived_thread_ids: HashSet<String>,
|
||||
pub(crate) subagent_thread_ids: HashSet<String>,
|
||||
pub(crate) rollout_paths_by_thread_id: HashMap<String, String>,
|
||||
pub(crate) mismatched_thread_ids: HashSet<String>,
|
||||
pub(crate) warnings: Vec<String>,
|
||||
pub(crate) scan_failures: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,993 @@
|
||||
use super::build_skills_mcp_state_inner;
|
||||
use super::mcp::{
|
||||
commit_mcp_transaction_with_config, document_bytes, is_valid_mcp_config, json_to_toml_item,
|
||||
mcp_configs_equal, save_managed_mcp_on_connection,
|
||||
};
|
||||
use super::skills::{
|
||||
codex_skills_dir, copy_dir_recursive, disabled_skills_dir, read_skill_metadata,
|
||||
sanitize_dir_name,
|
||||
};
|
||||
use super::types::{SkillsMcpActionResult, SkillsMcpExportResult};
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::{ensure_directory, io_err, parse_toml_document};
|
||||
use crate::live_config::{acquire_live_config_lock, read_file_snapshot, text_from_snapshot};
|
||||
use crate::paths::{app_home, normalized_path_scope};
|
||||
use crate::toml_utils::ensure_table;
|
||||
use crate::{config_path, now_rfc3339, open_db, resolve_codex_dir};
|
||||
use rusqlite::{params, TransactionBehavior};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{Read, Seek};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use zip::write::SimpleFileOptions;
|
||||
|
||||
const MANIFEST: &str = "codex-x-archive.json";
|
||||
const FORMAT: &str = "codex-x-skills-mcp";
|
||||
static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct Manifest {
|
||||
format: String,
|
||||
version: u32,
|
||||
#[serde(default)]
|
||||
skills: Vec<SkillEntry>,
|
||||
#[serde(default)]
|
||||
mcp_servers: Vec<McpEntry>,
|
||||
}
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct SkillEntry {
|
||||
directory: String,
|
||||
path: String,
|
||||
enabled: bool,
|
||||
note: Option<String>,
|
||||
}
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct McpEntry {
|
||||
id: String,
|
||||
name: String,
|
||||
config: Value,
|
||||
enabled: bool,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> CodexxError {
|
||||
CodexxError::Config(message.into())
|
||||
}
|
||||
fn zip_error(error: impl std::fmt::Display) -> CodexxError {
|
||||
invalid(format!("无法读取或写入 ZIP:{error}"))
|
||||
}
|
||||
fn unique_name(prefix: &str) -> String {
|
||||
format!(
|
||||
".{prefix}-{}-{}-{}",
|
||||
std::process::id(),
|
||||
chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default(),
|
||||
NEXT_TEMP.fetch_add(1, Ordering::Relaxed)
|
||||
)
|
||||
}
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
fn new(parent: &Path) -> Result<Self> {
|
||||
ensure_directory(parent)?;
|
||||
let path = parent.join(unique_name("codex-x-archive"));
|
||||
fs::create_dir(&path).map_err(|error| io_err(&path, error))?;
|
||||
Ok(Self(path))
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
// Reject Windows traversal/drive names on every OS too, so exported bundles can
|
||||
// safely move between machines. Links and special files are never extracted.
|
||||
fn safe_relative(name: &str) -> Result<PathBuf> {
|
||||
if name.is_empty() || name.contains('\\') || name.contains(':') || name.contains('\0') {
|
||||
return Err(invalid("ZIP 中含有不安全的文件路径"));
|
||||
}
|
||||
let path = Path::new(name);
|
||||
if path
|
||||
.components()
|
||||
.any(|part| !matches!(part, Component::Normal(_)))
|
||||
{
|
||||
return Err(invalid("ZIP 中含有不安全的文件路径"));
|
||||
}
|
||||
for part in name.trim_end_matches('/').split('/') {
|
||||
let stem = part.split('.').next().unwrap_or("").to_ascii_uppercase();
|
||||
if part.is_empty()
|
||||
|| part.ends_with([' ', '.'])
|
||||
|| matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|
||||
|| (stem.len() == 4
|
||||
&& (stem.starts_with("COM") || stem.starts_with("LPT"))
|
||||
&& stem.as_bytes()[3].is_ascii_digit())
|
||||
{
|
||||
return Err(invalid("ZIP 中含有无法跨平台安全使用的文件路径"));
|
||||
}
|
||||
}
|
||||
Ok(path.to_path_buf())
|
||||
}
|
||||
fn safe_directory(name: &str) -> Result<()> {
|
||||
let path = safe_relative(name)?;
|
||||
if path.components().count() != 1 || name.starts_with('.') {
|
||||
return Err(invalid("归档中的 Skill 目录名无效"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract<R: Read + Seek>(reader: R, destination: &Path) -> Result<()> {
|
||||
let mut archive = zip::ZipArchive::new(reader).map_err(zip_error)?;
|
||||
let mut seen = HashSet::new();
|
||||
for index in 0..archive.len() {
|
||||
let mut entry = archive.by_index(index).map_err(zip_error)?;
|
||||
let name = entry.name().trim_end_matches('/');
|
||||
let relative = safe_relative(name)?;
|
||||
let mode = entry.unix_mode().unwrap_or(0) & 0o170000;
|
||||
if mode != 0 && mode != 0o100000 && mode != 0o040000 {
|
||||
return Err(invalid("ZIP 不支持符号链接或特殊文件"));
|
||||
}
|
||||
if !seen.insert(name.to_ascii_lowercase()) {
|
||||
return Err(invalid("ZIP 中含有重复文件路径"));
|
||||
}
|
||||
let output = destination.join(relative);
|
||||
if entry.is_dir() {
|
||||
ensure_directory(&output)?;
|
||||
} else {
|
||||
ensure_directory(output.parent().ok_or_else(|| invalid("ZIP 路径无效"))?)?;
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&output)
|
||||
.map_err(|error| io_err(&output, error))?;
|
||||
std::io::copy(&mut entry, &mut file).map_err(|error| io_err(&output, error))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if let Some(mode) = entry.unix_mode() {
|
||||
fs::set_permissions(&output, fs::Permissions::from_mode(mode & 0o777))
|
||||
.map_err(|error| io_err(&output, error))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn collect_entries(root: &Path, current: &Path, output: &mut Vec<PathBuf>) -> Result<()> {
|
||||
let metadata = fs::symlink_metadata(current).map_err(|error| io_err(current, error))?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
return Err(invalid("Skill 包含符号链接,请先替换为实际文件再导出"));
|
||||
}
|
||||
if metadata.is_file() {
|
||||
output.push(
|
||||
current
|
||||
.strip_prefix(root)
|
||||
.map_err(|_| invalid("Skill 文件路径无效"))?
|
||||
.to_path_buf(),
|
||||
);
|
||||
} else if metadata.is_dir() {
|
||||
if current != root {
|
||||
output.push(
|
||||
current
|
||||
.strip_prefix(root)
|
||||
.map_err(|_| invalid("Skill 目录路径无效"))?
|
||||
.to_path_buf(),
|
||||
);
|
||||
}
|
||||
for entry in fs::read_dir(current).map_err(|error| io_err(current, error))? {
|
||||
collect_entries(
|
||||
root,
|
||||
&entry.map_err(|error| io_err(current, error))?.path(),
|
||||
output,
|
||||
)?;
|
||||
}
|
||||
} else {
|
||||
return Err(invalid("Skill 包含不支持的特殊文件"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn directory_digest(path: &Path) -> Result<Vec<u8>> {
|
||||
let mut files = Vec::new();
|
||||
collect_entries(path, path, &mut files)?;
|
||||
files.sort();
|
||||
let mut digest = Sha256::new();
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
for relative in files {
|
||||
let name = relative.to_string_lossy().replace('\\', "/");
|
||||
digest.update((name.len() as u64).to_le_bytes());
|
||||
digest.update(name.as_bytes());
|
||||
let file_path = path.join(relative);
|
||||
if file_path.is_dir() {
|
||||
digest.update(b"directory");
|
||||
continue;
|
||||
}
|
||||
digest.update(b"file");
|
||||
let mut file = File::open(&file_path).map_err(|error| io_err(&file_path, error))?;
|
||||
digest.update(
|
||||
file.metadata()
|
||||
.map_err(|error| io_err(&file_path, error))?
|
||||
.len()
|
||||
.to_le_bytes(),
|
||||
);
|
||||
loop {
|
||||
let count = file
|
||||
.read(&mut buffer)
|
||||
.map_err(|error| io_err(&file_path, error))?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
digest.update(&buffer[..count]);
|
||||
}
|
||||
}
|
||||
Ok(digest.finalize().to_vec())
|
||||
}
|
||||
fn write_archive(path: &Path, manifest: &Manifest, sources: &[PathBuf]) -> Result<()> {
|
||||
let file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
.map_err(|error| io_err(path, error))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
file.set_permissions(fs::Permissions::from_mode(0o600))
|
||||
.map_err(|error| io_err(path, error))?;
|
||||
}
|
||||
let mut writer = zip::ZipWriter::new(file);
|
||||
let options = SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated)
|
||||
.large_file(true);
|
||||
writer.start_file(MANIFEST, options).map_err(zip_error)?;
|
||||
serde_json::to_writer_pretty(&mut writer, manifest).map_err(|_| invalid("无法写入归档清单"))?;
|
||||
for (entry, source) in manifest.skills.iter().zip(sources) {
|
||||
let mut files = Vec::new();
|
||||
collect_entries(source, source, &mut files)?;
|
||||
files.sort();
|
||||
for relative in files {
|
||||
let relative_name = relative.to_string_lossy().replace('\\', "/");
|
||||
safe_relative(&relative_name)?;
|
||||
let source_file = source.join(&relative);
|
||||
let mut options = options;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
options = options.unix_permissions(
|
||||
fs::metadata(&source_file)
|
||||
.map_err(|error| io_err(&source_file, error))?
|
||||
.permissions()
|
||||
.mode()
|
||||
& 0o777,
|
||||
);
|
||||
}
|
||||
if source_file.is_dir() {
|
||||
writer
|
||||
.add_directory(format!("{}/{}/", entry.path, relative_name), options)
|
||||
.map_err(zip_error)?;
|
||||
continue;
|
||||
}
|
||||
writer
|
||||
.start_file(format!("{}/{}", entry.path, relative_name), options)
|
||||
.map_err(zip_error)?;
|
||||
let mut input =
|
||||
File::open(&source_file).map_err(|error| io_err(&source_file, error))?;
|
||||
std::io::copy(&mut input, &mut writer).map_err(|error| io_err(path, error))?;
|
||||
}
|
||||
}
|
||||
writer
|
||||
.finish()
|
||||
.map_err(zip_error)?
|
||||
.sync_all()
|
||||
.map_err(|error| io_err(path, error))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn destination_snapshot(path: &Path) -> Result<Option<Vec<u8>>> {
|
||||
let metadata = match fs::symlink_metadata(path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(io_err(path, error)),
|
||||
};
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() {
|
||||
return Err(invalid("请选择普通 ZIP 文件路径,不能覆盖符号链接或目录"));
|
||||
}
|
||||
let mut file = File::open(path).map_err(|error| io_err(path, error))?;
|
||||
let mut digest = Sha256::new();
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
loop {
|
||||
let count = file
|
||||
.read(&mut buffer)
|
||||
.map_err(|error| io_err(path, error))?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
digest.update(&buffer[..count]);
|
||||
}
|
||||
Ok(Some(digest.finalize().to_vec()))
|
||||
}
|
||||
|
||||
fn write_archive_atomic<BeforeReplace: FnOnce() -> Result<()>>(
|
||||
output: &Path,
|
||||
manifest: &Manifest,
|
||||
sources: &[PathBuf],
|
||||
before_replace: BeforeReplace,
|
||||
) -> Result<()> {
|
||||
let initial = destination_snapshot(output)?;
|
||||
let parent = output
|
||||
.parent()
|
||||
.ok_or_else(|| invalid("请选择有效的保存目录"))?;
|
||||
let temporary = parent.join(unique_name("codex-x-export"));
|
||||
let result = (|| {
|
||||
write_archive(&temporary, manifest, sources)?;
|
||||
before_replace()?;
|
||||
if destination_snapshot(output)? != initial {
|
||||
return Err(invalid(
|
||||
"保存位置的文件已被其他程序修改,请重新选择位置再导出",
|
||||
));
|
||||
}
|
||||
fs::rename(&temporary, output).map_err(|error| io_err(output, error))
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&temporary);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn validate_export_destination(output: &Path, codex_dir: &Path) -> Result<PathBuf> {
|
||||
if !output
|
||||
.extension()
|
||||
.and_then(|extension| extension.to_str())
|
||||
.is_some_and(|extension| extension.eq_ignore_ascii_case("zip"))
|
||||
{
|
||||
return Err(invalid("请将导出文件保存为 .zip 格式"));
|
||||
}
|
||||
let parent = output
|
||||
.parent()
|
||||
.filter(|parent| parent.is_dir())
|
||||
.ok_or_else(|| invalid("请选择有效的保存目录"))?;
|
||||
let canonical_parent = fs::canonicalize(parent).map_err(|error| io_err(parent, error))?;
|
||||
for protected in [codex_dir.to_path_buf(), app_home()?] {
|
||||
let canonical = fs::canonicalize(&protected).unwrap_or(protected);
|
||||
if canonical_parent.starts_with(canonical) {
|
||||
return Err(invalid(
|
||||
"请将 ZIP 保存到下载、桌面等目录,不要放入 Codex 配置或应用数据目录",
|
||||
));
|
||||
}
|
||||
}
|
||||
destination_snapshot(output)?;
|
||||
Ok(canonical_parent)
|
||||
}
|
||||
|
||||
pub(crate) fn export_skills_mcp_archive_inner(
|
||||
config_dir: Option<String>,
|
||||
kind: String,
|
||||
destination: String,
|
||||
) -> Result<SkillsMcpExportResult> {
|
||||
if !matches!(kind.as_str(), "skills" | "mcp") {
|
||||
return Err(invalid("请选择导出 Skills 或 MCP"));
|
||||
}
|
||||
let state = build_skills_mcp_state_inner(config_dir)?;
|
||||
let mut manifest = Manifest {
|
||||
format: FORMAT.to_owned(),
|
||||
version: 1,
|
||||
skills: vec![],
|
||||
mcp_servers: vec![],
|
||||
};
|
||||
let mut sources = Vec::new();
|
||||
if kind == "skills" {
|
||||
for skill in state.skills {
|
||||
safe_directory(&skill.directory)?;
|
||||
manifest.skills.push(SkillEntry {
|
||||
path: format!("skills/{}", skill.directory),
|
||||
directory: skill.directory,
|
||||
enabled: skill.enabled,
|
||||
note: skill.note,
|
||||
});
|
||||
sources.push(PathBuf::from(skill.path));
|
||||
}
|
||||
} else {
|
||||
for mcp in state.mcp_servers {
|
||||
manifest.mcp_servers.push(McpEntry {
|
||||
id: mcp.id,
|
||||
name: mcp.name,
|
||||
config: mcp.config_json,
|
||||
enabled: mcp.enabled,
|
||||
note: mcp.note,
|
||||
});
|
||||
}
|
||||
}
|
||||
if manifest.skills.is_empty() && manifest.mcp_servers.is_empty() {
|
||||
return Err(invalid("当前没有可导出的内容"));
|
||||
}
|
||||
let output = PathBuf::from(destination);
|
||||
let canonical_parent = validate_export_destination(&output, Path::new(&state.codex_dir))?;
|
||||
for source in &sources {
|
||||
let canonical_source = fs::canonicalize(source).map_err(|error| io_err(source, error))?;
|
||||
if canonical_parent.starts_with(canonical_source) {
|
||||
return Err(invalid("请将 ZIP 保存在 Skill 目录之外"));
|
||||
}
|
||||
}
|
||||
write_archive_atomic(&output, &manifest, &sources, || Ok(()))?;
|
||||
Ok(SkillsMcpExportResult {
|
||||
path: output.display().to_string(),
|
||||
exported_skills: manifest.skills.len(),
|
||||
exported_mcp: manifest.mcp_servers.len(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn install_skill_archive_path_inner(
|
||||
config_dir: Option<String>,
|
||||
path: String,
|
||||
) -> Result<SkillsMcpActionResult> {
|
||||
let path = Path::new(&path);
|
||||
let file = File::open(path).map_err(|error| io_err(path, error))?;
|
||||
install_archive_reader(
|
||||
config_dir,
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("skills.zip")
|
||||
.to_owned(),
|
||||
file,
|
||||
)
|
||||
}
|
||||
|
||||
fn find_skill_roots(path: &Path, output: &mut Vec<PathBuf>) -> Result<()> {
|
||||
if path.join("SKILL.md").is_file() {
|
||||
output.push(path.to_path_buf());
|
||||
return Ok(());
|
||||
}
|
||||
for entry in fs::read_dir(path).map_err(|error| io_err(path, error))? {
|
||||
let entry = entry.map_err(|error| io_err(path, error))?;
|
||||
if entry
|
||||
.file_type()
|
||||
.map_err(|error| io_err(path, error))?
|
||||
.is_dir()
|
||||
{
|
||||
find_skill_roots(&entry.path(), output)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn manifest_from_extracted(path: &Path, file_name: &str) -> Result<Manifest> {
|
||||
let manifest_path = path.join(MANIFEST);
|
||||
if manifest_path.exists() {
|
||||
let file = File::open(&manifest_path).map_err(|error| io_err(&manifest_path, error))?;
|
||||
// This limits only metadata, not ZIP contents or Skill file sizes.
|
||||
let manifest: Manifest = serde_json::from_reader(file.take(8 * 1024 * 1024))
|
||||
.map_err(|_| invalid("Codex-X 归档清单无效或过大"))?;
|
||||
if manifest.format != FORMAT || manifest.version != 1 {
|
||||
return Err(invalid("暂不支持此归档版本,请更新 Codex-X"));
|
||||
}
|
||||
return Ok(manifest);
|
||||
}
|
||||
let mut roots = Vec::new();
|
||||
find_skill_roots(path, &mut roots)?;
|
||||
let mut manifest = Manifest {
|
||||
format: FORMAT.to_owned(),
|
||||
version: 1,
|
||||
skills: vec![],
|
||||
mcp_servers: vec![],
|
||||
};
|
||||
for root in roots {
|
||||
let fallback = if root == path {
|
||||
file_name.trim_end_matches(".zip")
|
||||
} else {
|
||||
root.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or(file_name.trim_end_matches(".zip"))
|
||||
};
|
||||
let (name, _) = read_skill_metadata(&root, fallback);
|
||||
let relative = root
|
||||
.strip_prefix(path)
|
||||
.map_err(|_| invalid("Skill 路径无效"))?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
manifest.skills.push(SkillEntry {
|
||||
directory: sanitize_dir_name(&name, "skill"),
|
||||
path: relative,
|
||||
enabled: true,
|
||||
note: None,
|
||||
});
|
||||
}
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
pub(super) fn install_archive_reader<R: Read + Seek>(
|
||||
config_dir: Option<String>,
|
||||
file_name: String,
|
||||
reader: R,
|
||||
) -> Result<SkillsMcpActionResult> {
|
||||
let temporary = TempDir::new(&app_home()?.join("tmp"))?;
|
||||
extract(reader, &temporary.0)?;
|
||||
let manifest = manifest_from_extracted(&temporary.0, &file_name)?;
|
||||
let (imported_skills, imported_mcp, skipped) =
|
||||
import_manifest(config_dir.clone(), &temporary.0, manifest)?;
|
||||
Ok(SkillsMcpActionResult {
|
||||
imported_skills,
|
||||
imported_mcp,
|
||||
message: format!(
|
||||
"已导入 {imported_skills} 个 Skills、{imported_mcp} 个 MCP{}",
|
||||
if skipped > 0 {
|
||||
format!(",跳过 {skipped} 个已存在的项目")
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
),
|
||||
state: build_skills_mcp_state_inner(config_dir)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn import_manifest(
|
||||
config_dir: Option<String>,
|
||||
root: &Path,
|
||||
manifest: Manifest,
|
||||
) -> Result<(usize, usize, usize)> {
|
||||
if manifest.skills.is_empty() && manifest.mcp_servers.is_empty() {
|
||||
return Err(invalid("ZIP 中没有可导入的 Skills 或 MCP"));
|
||||
}
|
||||
let codex_dir = resolve_codex_dir(config_dir.clone())?;
|
||||
ensure_directory(&codex_dir)?;
|
||||
let _lock = acquire_live_config_lock(&codex_dir)?;
|
||||
let current = build_skills_mcp_state_inner(config_dir)?;
|
||||
let cfg = config_path(&codex_dir);
|
||||
let before = read_file_snapshot(&cfg)?;
|
||||
let mut document = parse_toml_document(&cfg, &text_from_snapshot(&cfg, before.as_deref())?)?;
|
||||
let mut skill_ids = HashSet::new();
|
||||
let mut mcp_ids = HashSet::new();
|
||||
let existing_skills: HashMap<_, _> = current
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| (skill.directory.as_str(), skill))
|
||||
.collect();
|
||||
let existing_mcp: HashMap<_, _> = current
|
||||
.mcp_servers
|
||||
.iter()
|
||||
.map(|mcp| (mcp.id.as_str(), mcp))
|
||||
.collect();
|
||||
let mut skill_plan = Vec::new();
|
||||
let mut mcp_plan = Vec::new();
|
||||
let mut skipped = 0;
|
||||
for skill in manifest.skills {
|
||||
safe_directory(&skill.directory)?;
|
||||
if !skill_ids.insert(sanitize_dir_name(&skill.directory, "skill")) {
|
||||
return Err(invalid("归档中存在同名 Skill"));
|
||||
}
|
||||
let relative = if skill.path.is_empty() {
|
||||
PathBuf::new()
|
||||
} else {
|
||||
safe_relative(&skill.path)?
|
||||
};
|
||||
let source = root.join(relative);
|
||||
if !source.join("SKILL.md").is_file() {
|
||||
return Err(invalid(format!("Skill {} 缺少 SKILL.md", skill.directory)));
|
||||
}
|
||||
if let Some(existing) = existing_skills.get(skill.directory.as_str()) {
|
||||
if directory_digest(&source)? == directory_digest(Path::new(&existing.path))? {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
return Err(invalid(format!(
|
||||
"Skill「{}」已存在且内容不同。请先重命名或移除已有项目,导入不会覆盖它。",
|
||||
skill.directory
|
||||
)));
|
||||
}
|
||||
let parent = if skill.enabled {
|
||||
codex_skills_dir(&codex_dir)
|
||||
} else {
|
||||
disabled_skills_dir()?
|
||||
};
|
||||
let destination = parent.join(&skill.directory);
|
||||
if destination.exists() {
|
||||
return Err(invalid(format!(
|
||||
"Skill 目录「{}」已存在,未覆盖",
|
||||
skill.directory
|
||||
)));
|
||||
}
|
||||
skill_plan.push((skill, source, destination));
|
||||
}
|
||||
for mcp in manifest.mcp_servers {
|
||||
if mcp.id.trim().is_empty()
|
||||
|| !mcp_ids.insert(mcp.id.clone())
|
||||
|| !is_valid_mcp_config(&mcp.config)
|
||||
{
|
||||
return Err(invalid("归档中存在无效或重复的 MCP 配置"));
|
||||
}
|
||||
if let Some(existing) = existing_mcp.get(mcp.id.as_str()) {
|
||||
if mcp_configs_equal(&existing.config_json, &mcp.config) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
return Err(invalid(format!(
|
||||
"MCP「{}」已存在且配置不同。请先重命名或移除已有项目,导入不会覆盖它。",
|
||||
mcp.name
|
||||
)));
|
||||
}
|
||||
// A malformed live entry is still user data; do not overwrite it.
|
||||
if document
|
||||
.get("mcp_servers")
|
||||
.and_then(|item| item.as_table())
|
||||
.is_some_and(|table| table.contains_key(&mcp.id))
|
||||
{
|
||||
return Err(invalid(format!("MCP「{}」已存在,未覆盖", mcp.name)));
|
||||
}
|
||||
mcp_plan.push(mcp);
|
||||
}
|
||||
let mut connection = open_db()?;
|
||||
let transaction = connection
|
||||
.transaction_with_behavior(TransactionBehavior::Immediate)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
let scope = normalized_path_scope(&codex_dir);
|
||||
let save_note = |kind: &str, id: &str, note: &Option<String>| -> Result<()> {
|
||||
if let Some(note) = note.as_deref().filter(|note| !note.trim().is_empty()) {
|
||||
if note.chars().count() > super::SKILLS_MCP_NOTE_MAX_CHARS {
|
||||
return Err(invalid("归档中的备注过长"));
|
||||
}
|
||||
transaction.execute("INSERT INTO skills_mcp_notes (codex_dir,item_kind,item_id,note,updated_at) VALUES (?1,?2,?3,?4,?5) ON CONFLICT(codex_dir,item_kind,item_id) DO NOTHING", params![scope, kind, id, note, now_rfc3339()]).map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
for mcp in &mcp_plan {
|
||||
save_managed_mcp_on_connection(&transaction, &mcp.id, &mcp.name, &mcp.config, mcp.enabled)?;
|
||||
if mcp.enabled {
|
||||
ensure_table(document.as_table_mut(), "mcp_servers")?
|
||||
.insert(&mcp.id, json_to_toml_item(&mcp.config));
|
||||
}
|
||||
save_note("mcp", &mcp.id, &mcp.note)?;
|
||||
}
|
||||
for (skill, _, _) in &skill_plan {
|
||||
save_note(
|
||||
"skill",
|
||||
&sanitize_dir_name(&skill.directory, "skill"),
|
||||
&skill.note,
|
||||
)?;
|
||||
}
|
||||
let mut created = Vec::new();
|
||||
let apply = (|| -> Result<()> {
|
||||
for (_, source, destination) in &skill_plan {
|
||||
let staging = TempDir::new(
|
||||
destination
|
||||
.parent()
|
||||
.ok_or_else(|| invalid("Skill 目标目录无效"))?,
|
||||
)?;
|
||||
copy_dir_recursive(source, &staging.0)?;
|
||||
if destination.exists() {
|
||||
return Err(invalid("导入期间出现同名 Skill,已停止且未覆盖"));
|
||||
}
|
||||
fs::rename(&staging.0, destination).map_err(|error| io_err(destination, error))?;
|
||||
created.push(destination.clone());
|
||||
}
|
||||
let after = document_bytes(before.as_deref(), &document);
|
||||
commit_mcp_transaction_with_config(
|
||||
transaction,
|
||||
&codex_dir,
|
||||
before,
|
||||
after,
|
||||
"import-skills-mcp-zip",
|
||||
|_| Ok(()),
|
||||
|_| Ok(()),
|
||||
)
|
||||
})();
|
||||
if apply.is_err() {
|
||||
for path in created {
|
||||
let _ = fs::remove_dir_all(path);
|
||||
}
|
||||
}
|
||||
apply?;
|
||||
Ok((skill_plan.len(), mcp_plan.len(), skipped))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use std::io::{Cursor, Write};
|
||||
|
||||
fn manifest() -> Manifest {
|
||||
Manifest {
|
||||
format: FORMAT.into(),
|
||||
version: 1,
|
||||
skills: vec![],
|
||||
mcp_servers: vec![],
|
||||
}
|
||||
}
|
||||
fn test_dir() -> TempDir {
|
||||
TempDir::new(&std::env::temp_dir().join("codex-x-archive-tests")).unwrap()
|
||||
}
|
||||
fn codex(dir: &Path) -> Option<String> {
|
||||
fs::create_dir_all(dir).unwrap();
|
||||
Some(dir.display().to_string())
|
||||
}
|
||||
fn skill(root: &Path, directory: &str, enabled: bool) -> SkillEntry {
|
||||
let path = root.join("skills").join(directory);
|
||||
fs::create_dir_all(&path).unwrap();
|
||||
fs::write(
|
||||
path.join("SKILL.md"),
|
||||
format!("---\nname: {directory}\ndescription: Example\n---\n# Readme"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(path.join(".extra"), b"hidden file").unwrap();
|
||||
fs::create_dir_all(path.join("empty-resources")).unwrap();
|
||||
SkillEntry {
|
||||
directory: directory.into(),
|
||||
path: format!("skills/{directory}"),
|
||||
enabled,
|
||||
note: Some("My skill note".into()),
|
||||
}
|
||||
}
|
||||
fn zip_entries(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
for (name, data) in entries {
|
||||
writer
|
||||
.start_file(
|
||||
*name,
|
||||
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored),
|
||||
)
|
||||
.unwrap();
|
||||
writer.write_all(data).unwrap();
|
||||
}
|
||||
writer.finish().unwrap().into_inner()
|
||||
}
|
||||
fn clean_mcp(id: &str) {
|
||||
let db = open_db().unwrap();
|
||||
db.execute("DELETE FROM managed_mcp_servers WHERE id=?1", [id])
|
||||
.unwrap();
|
||||
db.execute("DELETE FROM skills_mcp_notes WHERE item_id=?1", [id])
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip_bundle_round_trip_preserves_files_notes_disabled_skills_and_mcp_settings() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let temporary = test_dir();
|
||||
let source = temporary.0.join("source");
|
||||
let destination = temporary.0.join("codex");
|
||||
let directory = format!("archive-roundtrip-{}", std::process::id());
|
||||
let id = format!("archive-roundtrip-mcp-{}", std::process::id());
|
||||
clean_mcp(&id);
|
||||
let disabled = disabled_skills_dir().unwrap().join(&directory);
|
||||
let _ = fs::remove_dir_all(&disabled);
|
||||
let mut bundle = manifest();
|
||||
bundle.skills.push(skill(&source, &directory, false));
|
||||
bundle.mcp_servers.push(McpEntry { id: id.clone(), name: "Portable MCP".into(), config: json!({"command":"example-server", "args":["--safe"], "env":{"TOKEN":"synthetic-test-token"}}), enabled: true, note: Some("MCP note".into()) });
|
||||
let output = temporary.0.join("bundle.zip");
|
||||
write_archive(&output, &bundle, &[source.join("skills").join(&directory)]).unwrap();
|
||||
fs::create_dir_all(&destination).unwrap();
|
||||
fs::write(
|
||||
destination.join("config.toml"),
|
||||
"# Keep this\nmodel = \"gpt-test\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let imported =
|
||||
install_skill_archive_path_inner(codex(&destination), output.display().to_string())
|
||||
.unwrap();
|
||||
assert_eq!((imported.imported_skills, imported.imported_mcp), (1, 1));
|
||||
let skill = imported
|
||||
.state
|
||||
.skills
|
||||
.iter()
|
||||
.find(|skill| skill.id == directory)
|
||||
.unwrap();
|
||||
assert!(!skill.enabled);
|
||||
assert_eq!(skill.note.as_deref(), Some("My skill note"));
|
||||
assert_eq!(fs::read(disabled.join(".extra")).unwrap(), b"hidden file");
|
||||
assert!(disabled.join("empty-resources").is_dir());
|
||||
let mcp = imported
|
||||
.state
|
||||
.mcp_servers
|
||||
.iter()
|
||||
.find(|mcp| mcp.id == id)
|
||||
.unwrap();
|
||||
assert_eq!(mcp.note.as_deref(), Some("MCP note"));
|
||||
assert!(mcp.enabled);
|
||||
assert!(fs::read_to_string(destination.join("config.toml"))
|
||||
.unwrap()
|
||||
.starts_with("# Keep this"));
|
||||
let second =
|
||||
install_skill_archive_path_inner(codex(&destination), output.display().to_string())
|
||||
.unwrap();
|
||||
assert_eq!((second.imported_skills, second.imported_mcp), (0, 0));
|
||||
fs::remove_dir_all(disabled).unwrap();
|
||||
clean_mcp(&id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regular_skill_zip_larger_than_twenty_megabytes_installs_without_size_limit() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let temporary = test_dir();
|
||||
let payload = vec![b'x'; 21 * 1024 * 1024];
|
||||
let bytes = zip_entries(&[
|
||||
(
|
||||
"package/SKILL.md",
|
||||
b"---\nname: large-archive-fixture\n---\n",
|
||||
),
|
||||
("package/data.bin", &payload),
|
||||
]);
|
||||
assert!(bytes.len() > 20 * 1024 * 1024);
|
||||
let result = install_archive_reader(
|
||||
codex(&temporary.0.join("codex")),
|
||||
"large.zip".into(),
|
||||
Cursor::new(bytes),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.imported_skills, 1);
|
||||
assert_eq!(
|
||||
fs::metadata(
|
||||
temporary
|
||||
.0
|
||||
.join("codex/skills/large-archive-fixture/data.bin")
|
||||
)
|
||||
.unwrap()
|
||||
.len(),
|
||||
payload.len() as u64
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_bundle_is_rejected_before_any_skill_or_mcp_is_written() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let temporary = test_dir();
|
||||
let source = temporary.0.join("source");
|
||||
let destination = temporary.0.join("codex");
|
||||
let mut bundle = manifest();
|
||||
bundle
|
||||
.skills
|
||||
.push(skill(&source, "archive-new-first", true));
|
||||
bundle
|
||||
.skills
|
||||
.push(skill(&source, "archive-existing-second", true));
|
||||
let existing = destination.join("skills/archive-existing-second");
|
||||
fs::create_dir_all(&existing).unwrap();
|
||||
fs::write(existing.join("SKILL.md"), "original").unwrap();
|
||||
assert!(import_manifest(codex(&destination), &source, bundle).is_err());
|
||||
assert!(!destination.join("skills/archive-new-first").exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(existing.join("SKILL.md")).unwrap(),
|
||||
"original"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsafe_duplicate_and_link_zip_entries_are_rejected() {
|
||||
let temporary = test_dir();
|
||||
for name in [
|
||||
"../escape",
|
||||
"/absolute",
|
||||
"C:/drive",
|
||||
"folder\\escape",
|
||||
"CON.txt",
|
||||
] {
|
||||
let target = TempDir::new(&temporary.0).unwrap();
|
||||
assert!(
|
||||
extract(Cursor::new(zip_entries(&[(name, b"unsafe")])), &target.0).is_err(),
|
||||
"accepted {name}"
|
||||
);
|
||||
}
|
||||
let target = TempDir::new(&temporary.0).unwrap();
|
||||
assert!(extract(
|
||||
Cursor::new(zip_entries(&[("a", b"1"), ("A", b"2")])),
|
||||
&target.0
|
||||
)
|
||||
.is_err());
|
||||
let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
writer
|
||||
.add_symlink("link", "../outside", SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
assert!(extract(
|
||||
Cursor::new(writer.finish().unwrap().into_inner()),
|
||||
&TempDir::new(&temporary.0).unwrap().0
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_unknown_version_archives_are_rejected() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let temporary = test_dir();
|
||||
assert!(install_archive_reader(
|
||||
codex(&temporary.0.join("codex")),
|
||||
"empty.zip".into(),
|
||||
Cursor::new(zip_entries(&[("readme.txt", b"No skills")]))
|
||||
)
|
||||
.is_err());
|
||||
let mut unknown = manifest();
|
||||
unknown.version = 99;
|
||||
let bytes = serde_json::to_vec(&unknown).unwrap();
|
||||
assert!(install_archive_reader(
|
||||
codex(&temporary.0.join("codex")),
|
||||
"future.zip".into(),
|
||||
Cursor::new(zip_entries(&[(MANIFEST, &bytes)]))
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exported_skill_archive_can_be_imported_with_original_state() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let temporary = test_dir();
|
||||
let source = temporary.0.join("source");
|
||||
let destination = temporary.0.join("destination");
|
||||
let directory = format!("archive-export-{}", std::process::id());
|
||||
skill(&source, &directory, true);
|
||||
let archive = temporary.0.join("export.zip");
|
||||
let result = export_skills_mcp_archive_inner(
|
||||
codex(&source),
|
||||
"skills".into(),
|
||||
archive.display().to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.exported_skills >= 1);
|
||||
assert_eq!(result.exported_mcp, 0);
|
||||
let imported =
|
||||
install_skill_archive_path_inner(codex(&destination), archive.display().to_string())
|
||||
.unwrap();
|
||||
assert!(imported
|
||||
.state
|
||||
.skills
|
||||
.iter()
|
||||
.any(|skill| skill.directory == directory && skill.enabled));
|
||||
assert_eq!(
|
||||
directory_digest(&source.join("skills").join(&directory)).unwrap(),
|
||||
directory_digest(&destination.join("skills").join(&directory)).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_mcp_id_with_different_configuration_does_not_overwrite_live_config() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let temporary = test_dir();
|
||||
let destination = temporary.0.join("codex");
|
||||
codex(&destination);
|
||||
let original = "[mcp_servers.archive_conflict]\ncommand = \"existing\"\n";
|
||||
fs::write(destination.join("config.toml"), original).unwrap();
|
||||
let mut bundle = manifest();
|
||||
bundle.mcp_servers.push(McpEntry {
|
||||
id: "archive_conflict".into(),
|
||||
name: "Conflict".into(),
|
||||
config: json!({"command":"different"}),
|
||||
enabled: true,
|
||||
note: None,
|
||||
});
|
||||
assert!(import_manifest(codex(&destination), &temporary.0, bundle).is_err());
|
||||
assert_eq!(
|
||||
fs::read_to_string(destination.join("config.toml")).unwrap(),
|
||||
original
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn export_refuses_changed_destinations_and_cleans_temporary_output() {
|
||||
let temporary = test_dir();
|
||||
let output = temporary.0.join("export.zip");
|
||||
fs::write(&output, b"before").unwrap();
|
||||
let result = write_archive_atomic(&output, &manifest(), &[], || {
|
||||
fs::write(&output, b"external-update").unwrap();
|
||||
Ok(())
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(fs::read(&output).unwrap(), b"external-update");
|
||||
assert_eq!(fs::read_dir(&temporary.0).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_rejects_codex_data_and_non_zip_destinations() {
|
||||
let temporary = test_dir();
|
||||
let codex = temporary.0.join("codex");
|
||||
fs::create_dir_all(&codex).unwrap();
|
||||
assert!(validate_export_destination(&codex.join("backup.zip"), &codex).is_err());
|
||||
assert!(validate_export_destination(&temporary.0.join("auth.json"), &codex).is_err());
|
||||
assert!(validate_export_destination(&temporary.0.join("backup.zip"), &codex).is_ok());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let file = temporary.0.join("original.zip");
|
||||
fs::write(&file, "original").unwrap();
|
||||
let link = temporary.0.join("symlink.zip");
|
||||
std::os::unix::fs::symlink(&file, &link).unwrap();
|
||||
assert!(validate_export_destination(&link, &codex).is_err());
|
||||
assert_eq!(fs::read_to_string(file).unwrap(), "original");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,25 @@
|
||||
use super::build_skills_mcp_state_inner;
|
||||
use super::types::{ManagedMcpServer, SkillsMcpState};
|
||||
use crate::backups::create_backup;
|
||||
use crate::ccswitch::default_ccswitch_db_path;
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::{ensure_directory, parse_toml_document, read_to_string_if_exists, write_text};
|
||||
use crate::file_io::{ensure_directory, parse_toml_document, read_to_string_if_exists};
|
||||
use crate::live_config::{
|
||||
acquire_live_config_lock, apply_file_change, fail_with_file_rollback, read_file_snapshot,
|
||||
text_from_snapshot,
|
||||
};
|
||||
use crate::toml_utils::ensure_table;
|
||||
use crate::{config_path, now_rfc3339, open_db, resolve_codex_dir};
|
||||
use rusqlite::{params, Connection, OpenFlags};
|
||||
use rusqlite::{
|
||||
params, Connection, OpenFlags, OptionalExtension, Transaction, TransactionBehavior,
|
||||
};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use toml_edit::{value, Item, Table};
|
||||
|
||||
type CcSwitchMcpCandidate = (String, String, Value, bool);
|
||||
|
||||
fn toml_value_to_json(value: &toml_edit::Value) -> Value {
|
||||
if let Some(s) = value.as_str() {
|
||||
return json!(s);
|
||||
@@ -24,6 +33,14 @@ fn toml_value_to_json(value: &toml_edit::Value) -> Value {
|
||||
if let Some(b) = value.as_bool() {
|
||||
return json!(b);
|
||||
}
|
||||
if let Some(table) = value.as_inline_table() {
|
||||
return Value::Object(
|
||||
table
|
||||
.iter()
|
||||
.map(|(key, value)| (key.to_owned(), toml_value_to_json(value)))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
if let Some(arr) = value.as_array() {
|
||||
return Value::Array(arr.iter().map(toml_value_to_json).collect());
|
||||
}
|
||||
@@ -44,7 +61,7 @@ fn toml_item_to_json(item: &Item) -> Value {
|
||||
Value::Null
|
||||
}
|
||||
|
||||
fn json_to_toml_item(value_json: &Value) -> Item {
|
||||
pub(super) fn json_to_toml_item(value_json: &Value) -> Item {
|
||||
match value_json {
|
||||
Value::String(s) => value(s.clone()),
|
||||
Value::Bool(b) => value(*b),
|
||||
@@ -134,8 +151,13 @@ pub(super) fn mcp_summary(config: &Value) -> (String, Option<String>, Option<Str
|
||||
(transport, command, url, summary)
|
||||
}
|
||||
|
||||
pub(super) fn save_managed_mcp(id: &str, name: &str, config: &Value, enabled: bool) -> Result<()> {
|
||||
let conn = open_db()?;
|
||||
pub(super) fn save_managed_mcp_on_connection(
|
||||
conn: &Connection,
|
||||
id: &str,
|
||||
name: &str,
|
||||
config: &Value,
|
||||
enabled: bool,
|
||||
) -> Result<()> {
|
||||
conn.execute(
|
||||
"INSERT INTO managed_mcp_servers (id, name, server_config, enabled, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)
|
||||
@@ -156,6 +178,86 @@ pub(super) fn save_managed_mcp(id: &str, name: &str, config: &Value, enabled: bo
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn save_managed_mcp(id: &str, name: &str, config: &Value, enabled: bool) -> Result<()> {
|
||||
let conn = open_db()?;
|
||||
save_managed_mcp_on_connection(&conn, id, name, config, enabled)
|
||||
}
|
||||
|
||||
fn managed_mcp_on_connection(conn: &Connection, id: &str) -> Result<Option<(String, Value, bool)>> {
|
||||
conn.query_row(
|
||||
"SELECT name, server_config, enabled FROM managed_mcp_servers WHERE id = ?1 LIMIT 1",
|
||||
[id],
|
||||
|row| {
|
||||
let config_text: String = row.get(1)?;
|
||||
Ok((
|
||||
row.get(0)?,
|
||||
serde_json::from_str(&config_text).unwrap_or(Value::Object(Default::default())),
|
||||
row.get(2)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))
|
||||
}
|
||||
|
||||
fn document_mcp_ids(doc: &toml_edit::DocumentMut) -> HashSet<String> {
|
||||
doc.get("mcp_servers")
|
||||
.and_then(|item| item.as_table())
|
||||
.map(|table| {
|
||||
table
|
||||
.iter()
|
||||
.filter(|(_, item)| item.as_table_like().is_some())
|
||||
.map(|(id, _)| id.to_string())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) fn document_bytes(
|
||||
snapshot: Option<&[u8]>,
|
||||
doc: &toml_edit::DocumentMut,
|
||||
) -> Option<Vec<u8>> {
|
||||
let bytes = doc.to_string().into_bytes();
|
||||
if snapshot.is_none() && bytes.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn commit_mcp_transaction_with_config<BeforeApply, BeforeCommit>(
|
||||
transaction: Transaction<'_>,
|
||||
codex_dir: &Path,
|
||||
before: Option<Vec<u8>>,
|
||||
after: Option<Vec<u8>>,
|
||||
backup_action: &str,
|
||||
before_apply: BeforeApply,
|
||||
before_commit: BeforeCommit,
|
||||
) -> Result<()>
|
||||
where
|
||||
BeforeApply: FnOnce(&Path) -> Result<()>,
|
||||
BeforeCommit: FnOnce(&Transaction<'_>) -> Result<()>,
|
||||
{
|
||||
let cfg = config_path(codex_dir);
|
||||
let mut changes = Vec::new();
|
||||
if before != after {
|
||||
create_backup(codex_dir, backup_action)?;
|
||||
before_apply(&cfg)?;
|
||||
changes.push(apply_file_change(&cfg, before, after)?);
|
||||
}
|
||||
|
||||
if let Err(error) = before_commit(&transaction) {
|
||||
return fail_with_file_rollback(error, &changes);
|
||||
}
|
||||
if let Err(error) = transaction
|
||||
.commit()
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))
|
||||
{
|
||||
return fail_with_file_rollback(error, &changes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn db_managed_mcp() -> Result<Vec<(String, String, Value, bool)>> {
|
||||
let conn = open_db()?;
|
||||
let mut stmt = conn.prepare("SELECT id, name, server_config, enabled FROM managed_mcp_servers ORDER BY name ASC, id ASC")
|
||||
@@ -194,18 +296,25 @@ pub(super) fn list_mcp_from_config(codex_dir: &Path) -> Result<Vec<ManagedMcpSer
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (id, item) in mcp_tbl.iter() {
|
||||
if !item.is_table() {
|
||||
if item.as_table_like().is_none() {
|
||||
continue;
|
||||
}
|
||||
let config = toml_item_to_json(item);
|
||||
if !is_valid_mcp_config(&config) {
|
||||
continue;
|
||||
}
|
||||
let (transport, command, url, summary) = mcp_summary(&config);
|
||||
out.push(ManagedMcpServer {
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
transport,
|
||||
enabled: true,
|
||||
enabled: config
|
||||
.get("enabled")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(true),
|
||||
source: "config.toml".to_string(),
|
||||
summary,
|
||||
note: None,
|
||||
command,
|
||||
url,
|
||||
config_json: config,
|
||||
@@ -227,79 +336,153 @@ pub(super) fn import_ccswitch_mcp_servers_for_codex(
|
||||
codex_dir: &Path,
|
||||
imported_ids: &mut HashSet<String>,
|
||||
) -> Result<usize> {
|
||||
let db = default_ccswitch_db_path()?;
|
||||
if !db.exists() {
|
||||
let candidates = new_ccswitch_mcp_candidates(codex_dir, imported_ids)?;
|
||||
|
||||
import_ccswitch_mcp_candidates_with_hooks(
|
||||
codex_dir,
|
||||
imported_ids,
|
||||
candidates,
|
||||
|_| Ok(()),
|
||||
|_| Ok(()),
|
||||
)
|
||||
}
|
||||
|
||||
fn import_ccswitch_mcp_candidates_with_hooks<BeforeApply, BeforeCommit>(
|
||||
codex_dir: &Path,
|
||||
imported_ids: &mut HashSet<String>,
|
||||
candidates: Vec<CcSwitchMcpCandidate>,
|
||||
before_apply: BeforeApply,
|
||||
before_commit: BeforeCommit,
|
||||
) -> Result<usize>
|
||||
where
|
||||
BeforeApply: FnOnce(&Path) -> Result<()>,
|
||||
BeforeCommit: FnOnce(&Transaction<'_>) -> Result<()>,
|
||||
{
|
||||
let mut staged_ids = HashSet::new();
|
||||
let candidates = candidates
|
||||
.into_iter()
|
||||
.filter(|(id, _, config, _)| {
|
||||
is_valid_mcp_config(config)
|
||||
&& !imported_ids.contains(id)
|
||||
&& staged_ids.insert(id.clone())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if candidates.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let conn = Connection::open_with_flags(
|
||||
&db,
|
||||
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)
|
||||
.map_err(|e| {
|
||||
CodexxError::Database(format!(
|
||||
"打开 cc-switch MCP 数据库失败 {}: {e}",
|
||||
db.display()
|
||||
))
|
||||
})?;
|
||||
let mut stmt = match conn
|
||||
.prepare("SELECT id, name, server_config, enabled_codex FROM mcp_servers ORDER BY name ASC, id ASC")
|
||||
.or_else(|_| {
|
||||
conn.prepare("SELECT id, name, server_config, 0 AS enabled_codex FROM mcp_servers ORDER BY name ASC, id ASC")
|
||||
}) {
|
||||
Ok(stmt) => stmt,
|
||||
Err(rusqlite::Error::SqliteFailure(_, Some(message)))
|
||||
if message.to_lowercase().contains("no such table") =>
|
||||
{
|
||||
return Ok(0);
|
||||
}
|
||||
Err(e) => return Err(CodexxError::Database(e.to_string())),
|
||||
};
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, String>(2)?,
|
||||
row.get::<_, bool>(3)?,
|
||||
))
|
||||
})
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
|
||||
ensure_directory(codex_dir)?;
|
||||
let _live_lock = acquire_live_config_lock(codex_dir)?;
|
||||
let cfg = config_path(codex_dir);
|
||||
let text = read_to_string_if_exists(&cfg)?;
|
||||
let before = read_file_snapshot(&cfg)?;
|
||||
let text = text_from_snapshot(&cfg, before.as_deref())?;
|
||||
let mut doc = parse_toml_document(&cfg, &text)?;
|
||||
let live_enabled = list_mcp_from_config(codex_dir)?
|
||||
.into_iter()
|
||||
.map(|server| server.id)
|
||||
.collect::<HashSet<_>>();
|
||||
let mut imported = 0usize;
|
||||
let mut changed_config = false;
|
||||
for row in rows {
|
||||
let (id, name, config_text, enabled_codex) =
|
||||
row.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
let config: Value =
|
||||
serde_json::from_str(&config_text).unwrap_or(Value::Object(Default::default()));
|
||||
if !imported_ids.insert(id.clone()) {
|
||||
continue;
|
||||
let live_enabled = document_mcp_ids(&doc);
|
||||
|
||||
let mut app_conn = open_db()?;
|
||||
let transaction = app_conn
|
||||
.transaction_with_behavior(TransactionBehavior::Immediate)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
for (id, name, config, enabled_codex) in &candidates {
|
||||
let enabled = *enabled_codex || live_enabled.contains(id);
|
||||
save_managed_mcp_on_connection(&transaction, id, name, config, enabled)?;
|
||||
if *enabled_codex && !live_enabled.contains(id) {
|
||||
ensure_table(doc.as_table_mut(), "mcp_servers")?.insert(id, json_to_toml_item(config));
|
||||
}
|
||||
let enabled = enabled_codex || live_enabled.contains(&id);
|
||||
save_managed_mcp(&id, &name, &config, enabled)?;
|
||||
if enabled_codex && !live_enabled.contains(&id) {
|
||||
ensure_table(doc.as_table_mut(), "mcp_servers")?
|
||||
.insert(&id, json_to_toml_item(&config));
|
||||
changed_config = true;
|
||||
}
|
||||
imported += 1;
|
||||
}
|
||||
if changed_config {
|
||||
write_text(&cfg, &doc.to_string())?;
|
||||
}
|
||||
let after = document_bytes(before.as_deref(), &doc);
|
||||
commit_mcp_transaction_with_config(
|
||||
transaction,
|
||||
codex_dir,
|
||||
before,
|
||||
after,
|
||||
"import-ccswitch-mcp",
|
||||
before_apply,
|
||||
before_commit,
|
||||
)?;
|
||||
|
||||
let imported = candidates.len();
|
||||
imported_ids.extend(staged_ids);
|
||||
Ok(imported)
|
||||
}
|
||||
|
||||
pub(super) fn preview_ccswitch_mcp_servers_for_codex(
|
||||
codex_dir: &Path,
|
||||
) -> Result<Vec<ManagedMcpServer>> {
|
||||
// Both preview and import use the same validated records. Malformed JSON is never
|
||||
// converted to an empty stdio server.
|
||||
pub(super) fn is_valid_mcp_config(config: &Value) -> bool {
|
||||
let Some(object) = config.as_object() else {
|
||||
return false;
|
||||
};
|
||||
let nonempty = |key| {
|
||||
object
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|value| !value.trim().is_empty())
|
||||
};
|
||||
let command = nonempty("command");
|
||||
let url = nonempty("url");
|
||||
if command == url {
|
||||
return false;
|
||||
}
|
||||
if command
|
||||
&& object.get("args").is_some_and(|args| {
|
||||
!args
|
||||
.as_array()
|
||||
.is_some_and(|values| values.iter().all(Value::is_string))
|
||||
})
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if object.get("env").is_some_and(|env| {
|
||||
!env.as_object()
|
||||
.is_some_and(|values| values.values().all(Value::is_string))
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn mcp_configs_equal(left: &Value, right: &Value) -> bool {
|
||||
let normalize = |value: &Value| {
|
||||
let mut config = value.clone();
|
||||
if let Some(object) = config.as_object_mut() {
|
||||
// Transport is inferred from command/url by Codex; enabled is stored
|
||||
// separately from the connection settings in managed records.
|
||||
object.remove("type");
|
||||
object.remove("enabled");
|
||||
for key in ["args", "env", "http_headers", "env_http_headers"] {
|
||||
if object.get(key).is_some_and(|value| {
|
||||
value.as_array().is_some_and(Vec::is_empty)
|
||||
|| value.as_object().is_some_and(serde_json::Map::is_empty)
|
||||
}) {
|
||||
object.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
config
|
||||
};
|
||||
normalize(left) == normalize(right)
|
||||
}
|
||||
|
||||
fn normalized_ccswitch_config(config: Value, id: &str) -> Option<Value> {
|
||||
if is_valid_mcp_config(&config) {
|
||||
return Some(config);
|
||||
}
|
||||
for key in ["mcpServers", "mcp_servers"] {
|
||||
if let Some(servers) = config.get(key).and_then(Value::as_object) {
|
||||
let server = servers.get(id).or_else(|| {
|
||||
(servers.len() == 1)
|
||||
.then(|| servers.values().next())
|
||||
.flatten()
|
||||
})?;
|
||||
if is_valid_mcp_config(server) {
|
||||
return Some(server.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn read_ccswitch_mcp_candidates() -> Result<Vec<CcSwitchMcpCandidate>> {
|
||||
let db = default_ccswitch_db_path()?;
|
||||
if !db.exists() {
|
||||
return Ok(vec![]);
|
||||
@@ -308,29 +491,20 @@ pub(super) fn preview_ccswitch_mcp_servers_for_codex(
|
||||
&db,
|
||||
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)
|
||||
.map_err(|e| {
|
||||
CodexxError::Database(format!(
|
||||
"打开 cc-switch MCP 数据库失败 {}: {e}",
|
||||
db.display()
|
||||
))
|
||||
})?;
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
read_ccswitch_mcp_candidates_from_connection(&conn)
|
||||
}
|
||||
|
||||
fn read_ccswitch_mcp_candidates_from_connection(
|
||||
conn: &Connection,
|
||||
) -> Result<Vec<CcSwitchMcpCandidate>> {
|
||||
let mut stmt = match conn
|
||||
.prepare("SELECT id, name, server_config, enabled_codex FROM mcp_servers ORDER BY name ASC, id ASC")
|
||||
.or_else(|_| {
|
||||
conn.prepare("SELECT id, name, server_config, 0 AS enabled_codex FROM mcp_servers ORDER BY name ASC, id ASC")
|
||||
}) {
|
||||
.or_else(|_| conn.prepare("SELECT id, name, server_config, 0 FROM mcp_servers ORDER BY name ASC, id ASC")) {
|
||||
Ok(stmt) => stmt,
|
||||
Err(rusqlite::Error::SqliteFailure(_, Some(message)))
|
||||
if message.to_lowercase().contains("no such table") =>
|
||||
{
|
||||
return Ok(vec![]);
|
||||
}
|
||||
Err(e) => return Err(CodexxError::Database(e.to_string())),
|
||||
Err(rusqlite::Error::SqliteFailure(_, Some(message))) if message.to_lowercase().contains("no such table") => return Ok(vec![]),
|
||||
Err(error) => return Err(CodexxError::Database(error.to_string())),
|
||||
};
|
||||
let live_enabled = list_mcp_from_config(codex_dir)?
|
||||
.into_iter()
|
||||
.map(|server| server.id)
|
||||
.collect::<HashSet<_>>();
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
Ok((
|
||||
@@ -340,59 +514,456 @@ pub(super) fn preview_ccswitch_mcp_servers_for_codex(
|
||||
row.get::<_, bool>(3)?,
|
||||
))
|
||||
})
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let (id, name, config_text, enabled_codex) =
|
||||
row.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
let config: Value =
|
||||
serde_json::from_str(&config_text).unwrap_or(Value::Object(Default::default()));
|
||||
let (transport, command, url, summary) = mcp_summary(&config);
|
||||
out.push(ManagedMcpServer {
|
||||
id: id.clone(),
|
||||
name,
|
||||
transport,
|
||||
enabled: enabled_codex || live_enabled.contains(&id),
|
||||
source: "cc-switch".to_string(),
|
||||
summary,
|
||||
command,
|
||||
url,
|
||||
config_json: config,
|
||||
});
|
||||
let (id, name, text, enabled) =
|
||||
row.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
if id.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(config) = serde_json::from_str(&text)
|
||||
.ok()
|
||||
.and_then(|config| normalized_ccswitch_config(config, &id))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let name = if name.trim().is_empty() {
|
||||
id.clone()
|
||||
} else {
|
||||
name
|
||||
};
|
||||
out.push((id, name, config, enabled));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn new_ccswitch_mcp_candidates(
|
||||
codex_dir: &Path,
|
||||
already_seen: &HashSet<String>,
|
||||
) -> Result<Vec<CcSwitchMcpCandidate>> {
|
||||
let current = list_mcp_from_config(codex_dir)?;
|
||||
let managed = db_managed_mcp()?;
|
||||
let mut ids = already_seen.clone();
|
||||
let mut configs = Vec::new();
|
||||
for server in current {
|
||||
ids.insert(server.id);
|
||||
configs.push(server.config_json);
|
||||
}
|
||||
for (id, _, config, _) in managed {
|
||||
ids.insert(id);
|
||||
if is_valid_mcp_config(&config) {
|
||||
configs.push(config);
|
||||
}
|
||||
}
|
||||
let mut output = Vec::new();
|
||||
for candidate in read_ccswitch_mcp_candidates()? {
|
||||
if !ids.insert(candidate.0.clone())
|
||||
|| configs
|
||||
.iter()
|
||||
.any(|config| mcp_configs_equal(config, &candidate.2))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
configs.push(candidate.2.clone());
|
||||
output.push(candidate);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub(super) fn preview_ccswitch_mcp_servers_for_codex(
|
||||
codex_dir: &Path,
|
||||
) -> Result<Vec<ManagedMcpServer>> {
|
||||
let live_enabled = list_mcp_from_config(codex_dir)?
|
||||
.into_iter()
|
||||
.map(|server| server.id)
|
||||
.collect::<HashSet<_>>();
|
||||
Ok(new_ccswitch_mcp_candidates(codex_dir, &HashSet::new())?
|
||||
.into_iter()
|
||||
.map(|(id, name, config, enabled)| {
|
||||
let (transport, command, url, summary) = mcp_summary(&config);
|
||||
ManagedMcpServer {
|
||||
enabled: enabled || live_enabled.contains(&id),
|
||||
id,
|
||||
name,
|
||||
transport,
|
||||
source: "cc-switch".to_string(),
|
||||
summary,
|
||||
note: None,
|
||||
command,
|
||||
url,
|
||||
config_json: config,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(crate) fn toggle_codex_mcp_inner(
|
||||
config_dir: Option<String>,
|
||||
id: String,
|
||||
enabled: bool,
|
||||
) -> Result<SkillsMcpState> {
|
||||
toggle_codex_mcp_with_hooks(config_dir, id, enabled, |_| Ok(()), |_| Ok(()))
|
||||
}
|
||||
|
||||
fn toggle_codex_mcp_with_hooks<BeforeApply, BeforeCommit>(
|
||||
config_dir: Option<String>,
|
||||
id: String,
|
||||
enabled: bool,
|
||||
before_apply: BeforeApply,
|
||||
before_commit: BeforeCommit,
|
||||
) -> Result<SkillsMcpState>
|
||||
where
|
||||
BeforeApply: FnOnce(&Path) -> Result<()>,
|
||||
BeforeCommit: FnOnce(&Transaction<'_>) -> Result<()>,
|
||||
{
|
||||
let codex_dir = resolve_codex_dir(config_dir.clone())?;
|
||||
ensure_directory(&codex_dir)?;
|
||||
let _live_lock = acquire_live_config_lock(&codex_dir)?;
|
||||
let cfg = config_path(&codex_dir);
|
||||
let text = read_to_string_if_exists(&cfg)?;
|
||||
let before = read_file_snapshot(&cfg)?;
|
||||
let text = text_from_snapshot(&cfg, before.as_deref())?;
|
||||
let mut doc = parse_toml_document(&cfg, &text)?;
|
||||
|
||||
let mut conn = open_db()?;
|
||||
let transaction = conn
|
||||
.transaction_with_behavior(TransactionBehavior::Immediate)
|
||||
.map_err(|error| CodexxError::Database(error.to_string()))?;
|
||||
let stored = managed_mcp_on_connection(&transaction, &id)?;
|
||||
if enabled {
|
||||
let db = db_managed_mcp()?
|
||||
.into_iter()
|
||||
.find(|(sid, _, _, _)| sid == &id)
|
||||
let (name, mut config, _) = stored
|
||||
.or_else(|| {
|
||||
doc.get("mcp_servers")
|
||||
.and_then(Item::as_table)
|
||||
.and_then(|table| table.get(&id))
|
||||
.map(|item| (id.clone(), toml_item_to_json(item), false))
|
||||
})
|
||||
.ok_or_else(|| CodexxError::Config(format!("未找到 MCP: {id}")))?;
|
||||
ensure_table(doc.as_table_mut(), "mcp_servers")?.insert(&id, json_to_toml_item(&db.2));
|
||||
save_managed_mcp(&id, &db.1, &db.2, true)?;
|
||||
if let Some(object) = config.as_object_mut() {
|
||||
if object.contains_key("enabled") {
|
||||
object.insert("enabled".to_owned(), Value::Bool(true));
|
||||
}
|
||||
}
|
||||
ensure_table(doc.as_table_mut(), "mcp_servers")?.insert(&id, json_to_toml_item(&config));
|
||||
save_managed_mcp_on_connection(&transaction, &id, &name, &config, true)?;
|
||||
} else {
|
||||
if let Some(item) = doc
|
||||
let live_config = doc
|
||||
.get("mcp_servers")
|
||||
.and_then(|m| m.as_table())
|
||||
.and_then(|tbl| tbl.get(&id))
|
||||
{
|
||||
let config = toml_item_to_json(item);
|
||||
save_managed_mcp(&id, &id, &config, false)?;
|
||||
.map(toml_item_to_json);
|
||||
if let Some(config) = live_config {
|
||||
let name = stored
|
||||
.as_ref()
|
||||
.map(|(name, _, _)| name.as_str())
|
||||
.unwrap_or(&id);
|
||||
save_managed_mcp_on_connection(&transaction, &id, name, &config, false)?;
|
||||
} else if let Some((name, config, _)) = stored {
|
||||
save_managed_mcp_on_connection(&transaction, &id, &name, &config, false)?;
|
||||
}
|
||||
if let Some(tbl) = doc.get_mut("mcp_servers").and_then(|m| m.as_table_mut()) {
|
||||
tbl.remove(&id);
|
||||
}
|
||||
}
|
||||
write_text(&cfg, &doc.to_string())?;
|
||||
|
||||
let after = document_bytes(before.as_deref(), &doc);
|
||||
commit_mcp_transaction_with_config(
|
||||
transaction,
|
||||
&codex_dir,
|
||||
before,
|
||||
after,
|
||||
"toggle-mcp",
|
||||
before_apply,
|
||||
before_commit,
|
||||
)?;
|
||||
build_skills_mcp_state_inner(config_dir)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
fn test_case(name: &str) -> (PathBuf, String) {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let suffix = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"codex-x-mcp-{name}-{}-{suffix}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("create MCP test directory");
|
||||
(dir, format!("test-mcp-{name}-{suffix}"))
|
||||
}
|
||||
|
||||
fn database_error(error: rusqlite::Error) -> CodexxError {
|
||||
CodexxError::Database(error.to_string())
|
||||
}
|
||||
|
||||
fn remove_test_mcp(id: &str) {
|
||||
open_db()
|
||||
.expect("open test database")
|
||||
.execute("DELETE FROM managed_mcp_servers WHERE id = ?1", [id])
|
||||
.expect("remove test MCP");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_existing_unmanaged_disabled_mcp_updates_enabled_flag() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let (directory, id) = test_case("disabled-unmanaged");
|
||||
let config = format!("[mcp_servers.\"{id}\"]\ncommand = \"fixture\"\nenabled = false\n");
|
||||
std::fs::write(directory.join("config.toml"), config).unwrap();
|
||||
let initial = list_mcp_from_config(&directory).unwrap();
|
||||
assert!(!initial[0].enabled);
|
||||
let result =
|
||||
toggle_codex_mcp_inner(Some(directory.display().to_string()), id.clone(), true)
|
||||
.unwrap();
|
||||
assert!(
|
||||
result
|
||||
.mcp_servers
|
||||
.iter()
|
||||
.find(|server| server.id == id)
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
remove_test_mcp(&id);
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ccswitch_candidates_skip_empty_invalid_and_transport_only_records() {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE mcp_servers(id TEXT,name TEXT,server_config TEXT,enabled_codex BOOLEAN)",
|
||||
)
|
||||
.unwrap();
|
||||
for (id, data) in [
|
||||
("broken", "invalid"),
|
||||
("empty", "{}"),
|
||||
("transport", r#"{"type":"stdio"}"#),
|
||||
("valid", r#"{"command":"npx","args":["server"]}"#),
|
||||
(
|
||||
"wrapped",
|
||||
r#"{"mcpServers":{"wrapped":{"url":"https://example.test/mcp"}}}"#,
|
||||
),
|
||||
] {
|
||||
conn.execute(
|
||||
"INSERT INTO mcp_servers VALUES(?1,?1,?2,0)",
|
||||
params![id, data],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let candidates = read_ccswitch_mcp_candidates_from_connection(&conn).unwrap();
|
||||
assert_eq!(
|
||||
candidates
|
||||
.iter()
|
||||
.map(|entry| entry.0.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["valid", "wrapped"]
|
||||
);
|
||||
assert_eq!(candidates[1].2["url"], "https://example.test/mcp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_environment_round_trip_retains_mcp_credentials() {
|
||||
let document: toml_edit::DocumentMut =
|
||||
"[mcp_servers.example]\ncommand = \"example\"\nenv = { TOKEN = \"synthetic\" }\n"
|
||||
.parse()
|
||||
.unwrap();
|
||||
let value = toml_item_to_json(&document["mcp_servers"]["example"]);
|
||||
assert!(is_valid_mcp_config(&value));
|
||||
assert_eq!(value["env"]["TOKEN"], "synthetic");
|
||||
assert_eq!(toml_item_to_json(&json_to_toml_item(&value)), value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_updates_only_the_target_mcp_and_keeps_database_in_sync() {
|
||||
let _db_guard = crate::app_db::test_db_guard();
|
||||
let (codex_dir, id) = test_case("success");
|
||||
let cfg = config_path(&codex_dir);
|
||||
let original = b"# keep this comment\nmodel = \"gpt-5.5\"\n\n[features]\njs_repl = false\n\n[mcp_servers.existing]\ncommand = \"existing\"\n";
|
||||
fs::write(&cfg, original).expect("seed original config");
|
||||
save_managed_mcp(&id, "Managed", &json!({ "command": "managed" }), false)
|
||||
.expect("seed managed MCP");
|
||||
|
||||
let enabled_state =
|
||||
toggle_codex_mcp_inner(Some(codex_dir.display().to_string()), id.clone(), true)
|
||||
.expect("enable managed MCP");
|
||||
assert!(enabled_state
|
||||
.mcp_servers
|
||||
.iter()
|
||||
.any(|server| server.id == id && server.enabled));
|
||||
let enabled_text = fs::read_to_string(&cfg).expect("read enabled config");
|
||||
let enabled_doc = enabled_text
|
||||
.parse::<toml_edit::DocumentMut>()
|
||||
.expect("parse enabled config");
|
||||
assert!(enabled_text.contains("# keep this comment"));
|
||||
assert_eq!(enabled_doc["features"]["js_repl"].as_bool(), Some(false));
|
||||
assert_eq!(
|
||||
enabled_doc["mcp_servers"]["existing"]["command"].as_str(),
|
||||
Some("existing")
|
||||
);
|
||||
assert_eq!(
|
||||
enabled_doc["mcp_servers"][&id]["command"].as_str(),
|
||||
Some("managed")
|
||||
);
|
||||
let conn = open_db().expect("open test database");
|
||||
assert!(
|
||||
managed_mcp_on_connection(&conn, &id)
|
||||
.expect("read enabled MCP")
|
||||
.expect("enabled MCP exists")
|
||||
.2
|
||||
);
|
||||
drop(conn);
|
||||
|
||||
toggle_codex_mcp_inner(Some(codex_dir.display().to_string()), id.clone(), false)
|
||||
.expect("disable managed MCP");
|
||||
let disabled_text = fs::read_to_string(&cfg).expect("read disabled config");
|
||||
let disabled_doc = disabled_text
|
||||
.parse::<toml_edit::DocumentMut>()
|
||||
.expect("parse disabled config");
|
||||
assert!(disabled_text.contains("# keep this comment"));
|
||||
assert!(disabled_doc["mcp_servers"].get(&id).is_none());
|
||||
assert_eq!(
|
||||
disabled_doc["mcp_servers"]["existing"]["command"].as_str(),
|
||||
Some("existing")
|
||||
);
|
||||
let conn = open_db().expect("open test database");
|
||||
let (name, config, enabled) = managed_mcp_on_connection(&conn, &id)
|
||||
.expect("read disabled MCP")
|
||||
.expect("disabled MCP exists");
|
||||
assert_eq!(name, "Managed");
|
||||
assert_eq!(config["command"].as_str(), Some("managed"));
|
||||
assert!(!enabled);
|
||||
drop(conn);
|
||||
assert!(codex_dir.join(".codexx-test-backups").is_dir());
|
||||
|
||||
remove_test_mcp(&id);
|
||||
fs::remove_dir_all(codex_dir).expect("remove MCP test directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_rejects_a_stale_snapshot_without_changing_database_or_external_config() {
|
||||
let _db_guard = crate::app_db::test_db_guard();
|
||||
let (codex_dir, id) = test_case("stale");
|
||||
let cfg = config_path(&codex_dir);
|
||||
let original = b"# original\nmodel = \"gpt-5.5\"\n";
|
||||
let external = b"# external update\nmodel = \"gpt-5.5\"\n\n[mcp_servers.external]\ncommand = \"external\"\n";
|
||||
fs::write(&cfg, original).expect("seed original config");
|
||||
save_managed_mcp(&id, "Managed", &json!({ "command": "managed" }), false)
|
||||
.expect("seed managed MCP");
|
||||
|
||||
let error = toggle_codex_mcp_with_hooks(
|
||||
Some(codex_dir.display().to_string()),
|
||||
id.clone(),
|
||||
true,
|
||||
|path| {
|
||||
fs::write(path, external).map_err(|error| CodexxError::Config(error.to_string()))
|
||||
},
|
||||
|_| Ok(()),
|
||||
)
|
||||
.expect_err("stale MCP toggle must fail");
|
||||
|
||||
assert!(error.to_string().contains("已被其他程序修改"));
|
||||
assert_eq!(fs::read(&cfg).expect("read external config"), external);
|
||||
let conn = open_db().expect("open test database");
|
||||
let (_, config, enabled) = managed_mcp_on_connection(&conn, &id)
|
||||
.expect("read managed MCP")
|
||||
.expect("managed MCP still exists");
|
||||
assert_eq!(config["command"].as_str(), Some("managed"));
|
||||
assert!(!enabled);
|
||||
drop(conn);
|
||||
|
||||
remove_test_mcp(&id);
|
||||
fs::remove_dir_all(codex_dir).expect("remove MCP test directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_rolls_back_config_when_database_commit_fails() {
|
||||
let _db_guard = crate::app_db::test_db_guard();
|
||||
let (codex_dir, id) = test_case("commit");
|
||||
let cfg = config_path(&codex_dir);
|
||||
let original = b"# keep exact bytes\nmodel = \"gpt-5.5\"\n\n[features]\njs_repl = false\n";
|
||||
fs::write(&cfg, original).expect("seed original config");
|
||||
save_managed_mcp(&id, "Managed", &json!({ "command": "managed" }), false)
|
||||
.expect("seed managed MCP");
|
||||
|
||||
toggle_codex_mcp_with_hooks(
|
||||
Some(codex_dir.display().to_string()),
|
||||
id.clone(),
|
||||
true,
|
||||
|_| Ok(()),
|
||||
|transaction| {
|
||||
transaction
|
||||
.execute_batch("ROLLBACK")
|
||||
.map_err(database_error)
|
||||
},
|
||||
)
|
||||
.expect_err("database commit failure must fail the toggle");
|
||||
|
||||
assert_eq!(fs::read(&cfg).expect("read rolled-back config"), original);
|
||||
let conn = open_db().expect("open test database");
|
||||
let (_, _, enabled) = managed_mcp_on_connection(&conn, &id)
|
||||
.expect("read managed MCP")
|
||||
.expect("managed MCP still exists");
|
||||
assert!(!enabled);
|
||||
drop(conn);
|
||||
assert!(codex_dir.join(".codexx-test-backups").is_dir());
|
||||
|
||||
remove_test_mcp(&id);
|
||||
fs::remove_dir_all(codex_dir).expect("remove MCP test directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ccswitch_import_rolls_back_file_database_and_ids_when_commit_fails() {
|
||||
let _db_guard = crate::app_db::test_db_guard();
|
||||
let (codex_dir, id) = test_case("import-commit");
|
||||
let second_id = format!("{id}-second");
|
||||
let cfg = config_path(&codex_dir);
|
||||
let original = b"# import baseline\nmodel = \"gpt-5.5\"\n";
|
||||
fs::write(&cfg, original).expect("seed original config");
|
||||
let mut imported_ids = HashSet::new();
|
||||
|
||||
import_ccswitch_mcp_candidates_with_hooks(
|
||||
&codex_dir,
|
||||
&mut imported_ids,
|
||||
vec![
|
||||
(
|
||||
id.clone(),
|
||||
"Imported".to_string(),
|
||||
json!({ "command": "imported" }),
|
||||
true,
|
||||
),
|
||||
(
|
||||
second_id.clone(),
|
||||
"Imported second".to_string(),
|
||||
json!({ "command": "imported-second" }),
|
||||
true,
|
||||
),
|
||||
],
|
||||
|_| Ok(()),
|
||||
|transaction| {
|
||||
transaction
|
||||
.execute_batch("ROLLBACK")
|
||||
.map_err(database_error)
|
||||
},
|
||||
)
|
||||
.expect_err("database commit failure must fail the import");
|
||||
|
||||
assert_eq!(fs::read(&cfg).expect("read rolled-back config"), original);
|
||||
assert!(imported_ids.is_empty());
|
||||
let conn = open_db().expect("open test database");
|
||||
assert!(managed_mcp_on_connection(&conn, &id)
|
||||
.expect("read imported MCP")
|
||||
.is_none());
|
||||
assert!(managed_mcp_on_connection(&conn, &second_id)
|
||||
.expect("read second imported MCP")
|
||||
.is_none());
|
||||
drop(conn);
|
||||
assert!(codex_dir.join(".codexx-test-backups").is_dir());
|
||||
|
||||
fs::remove_dir_all(codex_dir).expect("remove MCP test directory");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
mod archive;
|
||||
mod mcp;
|
||||
pub(crate) use archive::{export_skills_mcp_archive_inner, install_skill_archive_path_inner};
|
||||
mod skills;
|
||||
mod types;
|
||||
|
||||
@@ -8,7 +10,8 @@ pub(crate) use skills::{
|
||||
sort_managed_skills, toggle_codex_skill_inner,
|
||||
};
|
||||
pub(crate) use types::{
|
||||
ManagedMcpServer, SkillsMcpActionResult, SkillsMcpImportPreview, SkillsMcpState,
|
||||
ManagedMcpServer, SkillsMcpActionResult, SkillsMcpExportResult, SkillsMcpImportPreview,
|
||||
SkillsMcpState,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -17,18 +20,74 @@ pub(crate) use skills::read_skill_metadata;
|
||||
pub(crate) use types::ManagedSkill;
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::file_io::{ensure_directory, io_err};
|
||||
use crate::paths::home_dir;
|
||||
use crate::file_io::ensure_directory;
|
||||
use crate::paths::{home_dir, normalized_path_scope};
|
||||
use crate::resolve_codex_dir;
|
||||
use crate::{now_rfc3339, open_db};
|
||||
use mcp::{
|
||||
db_managed_mcp, import_ccswitch_mcp_servers_for_codex, list_mcp_from_config, mcp_summary,
|
||||
preview_ccswitch_mcp_servers_for_codex, save_managed_mcp,
|
||||
};
|
||||
use skills::{
|
||||
codex_skills_dir, copy_dir_recursive, disabled_skills_dir, sanitize_dir_name, scan_skill_dir,
|
||||
};
|
||||
use std::collections::HashSet;
|
||||
use rusqlite::params;
|
||||
use skills::{codex_skills_dir, copy_dir_recursive, disabled_skills_dir, scan_skill_dir};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
#[cfg(test)]
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
const SKILLS_MCP_NOTE_MAX_CHARS: usize = 1000;
|
||||
|
||||
fn normalized_note_item_kind(item_kind: &str) -> Result<&'static str> {
|
||||
match item_kind.trim().to_ascii_lowercase().as_str() {
|
||||
"skill" => Ok("skill"),
|
||||
"mcp" => Ok("mcp"),
|
||||
_ => Err(crate::error::CodexxError::Config(
|
||||
"备注类型必须是 skill 或 mcp".to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn skills_mcp_notes(codex_dir: &Path) -> Result<HashMap<(String, String), String>> {
|
||||
let conn = open_db()?;
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT item_kind, item_id, note
|
||||
FROM skills_mcp_notes
|
||||
WHERE codex_dir = ?1
|
||||
ORDER BY item_kind ASC, item_id ASC",
|
||||
)
|
||||
.map_err(|error| crate::error::CodexxError::Database(error.to_string()))?;
|
||||
let rows = stmt
|
||||
.query_map([normalized_path_scope(codex_dir)], |row| {
|
||||
Ok((
|
||||
(row.get::<_, String>(0)?, row.get::<_, String>(1)?),
|
||||
row.get::<_, String>(2)?,
|
||||
))
|
||||
})
|
||||
.map_err(|error| crate::error::CodexxError::Database(error.to_string()))?;
|
||||
let mut notes = HashMap::new();
|
||||
for row in rows {
|
||||
let (key, note) =
|
||||
row.map_err(|error| crate::error::CodexxError::Database(error.to_string()))?;
|
||||
notes.insert(key, note);
|
||||
}
|
||||
Ok(notes)
|
||||
}
|
||||
|
||||
fn attach_skills_mcp_notes(
|
||||
codex_dir: &Path,
|
||||
skills: &mut [types::ManagedSkill],
|
||||
mcp_servers: &mut [ManagedMcpServer],
|
||||
) -> Result<()> {
|
||||
let notes = skills_mcp_notes(codex_dir)?;
|
||||
for skill in skills {
|
||||
skill.note = notes.get(&("skill".to_string(), skill.id.clone())).cloned();
|
||||
}
|
||||
for server in mcp_servers {
|
||||
server.note = notes.get(&("mcp".to_string(), server.id.clone())).cloned();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extend_unmanaged_mcp_candidates(
|
||||
output: &mut Vec<ManagedMcpServer>,
|
||||
@@ -71,7 +130,7 @@ pub(crate) fn build_skills_mcp_state_inner(config_dir: Option<String>) -> Result
|
||||
let mut mcp_servers = list_mcp_from_config(&codex_dir)?;
|
||||
let enabled_ids: HashSet<String> = mcp_servers.iter().map(|s| s.id.clone()).collect();
|
||||
for (id, name, config, enabled) in db_managed_mcp()? {
|
||||
if enabled_ids.contains(&id) {
|
||||
if enabled_ids.contains(&id) || !mcp::is_valid_mcp_config(&config) {
|
||||
continue;
|
||||
}
|
||||
let (transport, command, url, summary) = mcp_summary(&config);
|
||||
@@ -82,11 +141,13 @@ pub(crate) fn build_skills_mcp_state_inner(config_dir: Option<String>) -> Result
|
||||
enabled,
|
||||
source: "Codex-X".to_string(),
|
||||
summary,
|
||||
note: None,
|
||||
command,
|
||||
url,
|
||||
config_json: config,
|
||||
});
|
||||
}
|
||||
attach_skills_mcp_notes(&codex_dir, &mut skills, &mut mcp_servers)?;
|
||||
sort_managed_mcp_servers(&mut mcp_servers);
|
||||
sort_managed_skills(&mut skills);
|
||||
Ok(SkillsMcpState {
|
||||
@@ -99,37 +160,79 @@ pub(crate) fn build_skills_mcp_state_inner(config_dir: Option<String>) -> Result
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn save_skills_mcp_note_inner(
|
||||
config_dir: Option<String>,
|
||||
item_kind: String,
|
||||
id: String,
|
||||
note: String,
|
||||
) -> Result<SkillsMcpState> {
|
||||
let item_kind = normalized_note_item_kind(&item_kind)?;
|
||||
if id.trim().is_empty() {
|
||||
return Err(crate::error::CodexxError::Config(
|
||||
"备注对象 ID 不能为空".to_string(),
|
||||
));
|
||||
}
|
||||
let id = id.as_str();
|
||||
let note = note.trim();
|
||||
if note.chars().count() > SKILLS_MCP_NOTE_MAX_CHARS {
|
||||
return Err(crate::error::CodexxError::Config(format!(
|
||||
"备注不能超过 {SKILLS_MCP_NOTE_MAX_CHARS} 个字符"
|
||||
)));
|
||||
}
|
||||
|
||||
let codex_dir = resolve_codex_dir(config_dir.clone())?;
|
||||
let codex_dir_scope = normalized_path_scope(&codex_dir);
|
||||
let current = build_skills_mcp_state_inner(config_dir.clone())?;
|
||||
let exists = match item_kind {
|
||||
"skill" => current.skills.iter().any(|skill| skill.id == id),
|
||||
"mcp" => current.mcp_servers.iter().any(|server| server.id == id),
|
||||
_ => false,
|
||||
};
|
||||
if !exists {
|
||||
return Err(crate::error::CodexxError::Config(format!(
|
||||
"未找到要备注的 {item_kind}: {id}"
|
||||
)));
|
||||
}
|
||||
|
||||
let conn = open_db()?;
|
||||
if note.is_empty() {
|
||||
conn.execute(
|
||||
"DELETE FROM skills_mcp_notes
|
||||
WHERE codex_dir = ?1 AND item_kind = ?2 AND item_id = ?3",
|
||||
params![codex_dir_scope, item_kind, id],
|
||||
)
|
||||
.map_err(|error| crate::error::CodexxError::Database(error.to_string()))?;
|
||||
} else {
|
||||
conn.execute(
|
||||
"INSERT INTO skills_mcp_notes
|
||||
(codex_dir, item_kind, item_id, note, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)
|
||||
ON CONFLICT(codex_dir, item_kind, item_id) DO UPDATE SET
|
||||
note = excluded.note,
|
||||
updated_at = excluded.updated_at",
|
||||
params![codex_dir_scope, item_kind, id, note, now_rfc3339()],
|
||||
)
|
||||
.map_err(|error| crate::error::CodexxError::Database(error.to_string()))?;
|
||||
}
|
||||
build_skills_mcp_state_inner(config_dir)
|
||||
}
|
||||
|
||||
pub(crate) fn import_existing_skills_mcp_inner(
|
||||
config_dir: Option<String>,
|
||||
) -> Result<SkillsMcpActionResult> {
|
||||
let codex_dir = resolve_codex_dir(config_dir.clone())?;
|
||||
let skills_dir = codex_skills_dir(&codex_dir);
|
||||
ensure_directory(&skills_dir)?;
|
||||
let preview = preview_existing_skills_mcp_inner(config_dir.clone())?;
|
||||
let mut imported_skills = 0usize;
|
||||
let candidates = vec![
|
||||
home_dir()?.join(".agents").join("skills"),
|
||||
home_dir()?.join(".cc-switch").join("skills"),
|
||||
];
|
||||
for base in candidates {
|
||||
if !base.exists() {
|
||||
continue;
|
||||
}
|
||||
for entry in fs::read_dir(&base).map_err(|e| io_err(&base, e))? {
|
||||
let entry = entry.map_err(|e| io_err(&base, e))?;
|
||||
let src = entry.path();
|
||||
if !src.is_dir() || !src.join("SKILL.md").is_file() {
|
||||
continue;
|
||||
}
|
||||
let directory = sanitize_dir_name(&entry.file_name().to_string_lossy(), "skill");
|
||||
let dst = skills_dir.join(&directory);
|
||||
if !dst.exists() {
|
||||
copy_dir_recursive(&src, &dst)?;
|
||||
imported_skills += 1;
|
||||
}
|
||||
for skill in preview.skills {
|
||||
let destination = skills_dir.join(&skill.directory);
|
||||
if !destination.exists() {
|
||||
copy_dir_recursive(Path::new(&skill.path), &destination)?;
|
||||
imported_skills += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let mut imported_mcp = 0usize;
|
||||
let mut imported_mcp_ids = db_managed_mcp()?
|
||||
.into_iter()
|
||||
.map(|(id, _, _, _)| id)
|
||||
@@ -138,10 +241,11 @@ pub(crate) fn import_existing_skills_mcp_inner(
|
||||
if !imported_mcp_ids.insert(server.id.clone()) {
|
||||
continue;
|
||||
}
|
||||
// Already visible in the list: record it for deduplication without
|
||||
// presenting it as a newly imported server.
|
||||
save_managed_mcp(&server.id, &server.name, &server.config_json, true)?;
|
||||
imported_mcp += 1;
|
||||
}
|
||||
imported_mcp += import_ccswitch_mcp_servers_for_codex(&codex_dir, &mut imported_mcp_ids)?;
|
||||
let imported_mcp = import_ccswitch_mcp_servers_for_codex(&codex_dir, &mut imported_mcp_ids)?;
|
||||
let state = build_skills_mcp_state_inner(config_dir)?;
|
||||
Ok(SkillsMcpActionResult {
|
||||
imported_skills,
|
||||
@@ -156,6 +260,7 @@ pub(crate) fn preview_existing_skills_mcp_inner(
|
||||
) -> Result<SkillsMcpImportPreview> {
|
||||
let codex_dir = resolve_codex_dir(config_dir)?;
|
||||
let skills_dir = codex_skills_dir(&codex_dir);
|
||||
let disabled_dir = disabled_skills_dir()?;
|
||||
let mut warnings = Vec::new();
|
||||
let mut skills = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
@@ -177,14 +282,20 @@ pub(crate) fn preview_existing_skills_mcp_inner(
|
||||
warnings.push(e.to_string());
|
||||
}
|
||||
for skill in &mut skills[before..] {
|
||||
if skills_dir.join(&skill.directory).exists() {
|
||||
if skills_dir.join(&skill.directory).exists()
|
||||
|| disabled_dir.join(&skill.directory).exists()
|
||||
{
|
||||
skill.update_status = "已存在,将跳过".to_string();
|
||||
} else {
|
||||
skill.update_status = "可导入".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
skills.retain(|skill| skill.update_status != "已存在,将跳过");
|
||||
let mut candidate_ids = HashSet::new();
|
||||
skills.retain(|skill| {
|
||||
skill.update_status != "已存在,将跳过"
|
||||
&& candidate_ids.insert(skill.directory.to_ascii_lowercase())
|
||||
});
|
||||
|
||||
let mut config_mcp_servers = list_mcp_from_config(&codex_dir)?;
|
||||
for server in &mut config_mcp_servers {
|
||||
@@ -195,7 +306,7 @@ pub(crate) fn preview_existing_skills_mcp_inner(
|
||||
.map(|(id, _, _, _)| id)
|
||||
.collect::<HashSet<_>>();
|
||||
let mut mcp_servers = Vec::new();
|
||||
extend_unmanaged_mcp_candidates(&mut mcp_servers, &mut seen_mcp, config_mcp_servers);
|
||||
seen_mcp.extend(config_mcp_servers.into_iter().map(|server| server.id));
|
||||
extend_unmanaged_mcp_candidates(
|
||||
&mut mcp_servers,
|
||||
&mut seen_mcp,
|
||||
@@ -223,6 +334,7 @@ mod tests {
|
||||
enabled: true,
|
||||
source: source.to_string(),
|
||||
summary: id.to_string(),
|
||||
note: None,
|
||||
command: Some(id.to_string()),
|
||||
url: None,
|
||||
config_json: json!({ "command": id }),
|
||||
@@ -271,4 +383,161 @@ mod tests {
|
||||
);
|
||||
assert!(second_preview.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_notes_are_isolated_by_kind_and_codex_home_and_empty_text_clears_them() {
|
||||
let _db_guard = crate::app_db::test_db_guard();
|
||||
let item_id = format!("shared-note-item-{}", std::process::id());
|
||||
let spaced_id = " spaced-mcp ";
|
||||
let codex_dir =
|
||||
std::env::temp_dir().join(format!("codex-x-note-state-{}", std::process::id()));
|
||||
let other_codex_dir =
|
||||
std::env::temp_dir().join(format!("codex-x-note-state-other-{}", std::process::id()));
|
||||
let prepare_codex_dir = |dir: &Path| {
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
let skill_dir = dir.join("skills").join(&item_id);
|
||||
fs::create_dir_all(&skill_dir).expect("create test skill directory");
|
||||
fs::write(
|
||||
skill_dir.join("SKILL.md"),
|
||||
format!("---\nname: {item_id}\ndescription: test\n---\n"),
|
||||
)
|
||||
.expect("write test skill");
|
||||
fs::write(
|
||||
dir.join("config.toml"),
|
||||
format!(
|
||||
"[mcp_servers.{item_id}]\ncommand = \"test-server\"\n\
|
||||
[mcp_servers.\"{spaced_id}\"]\ncommand = \"spaced-server\"\n"
|
||||
),
|
||||
)
|
||||
.expect("write test MCP config");
|
||||
};
|
||||
prepare_codex_dir(&codex_dir);
|
||||
prepare_codex_dir(&other_codex_dir);
|
||||
|
||||
let conn = open_db().expect("open app database");
|
||||
conn.execute(
|
||||
"DELETE FROM skills_mcp_notes WHERE item_id IN (?1, ?2)",
|
||||
params![&item_id, spaced_id],
|
||||
)
|
||||
.expect("clear stale test notes");
|
||||
drop(conn);
|
||||
let config_dir = Some(codex_dir.display().to_string());
|
||||
|
||||
save_skills_mcp_note_inner(
|
||||
config_dir.clone(),
|
||||
"skill".to_string(),
|
||||
item_id.clone(),
|
||||
" 我的 Skill 备注 ".to_string(),
|
||||
)
|
||||
.expect("save skill note");
|
||||
let state = save_skills_mcp_note_inner(
|
||||
config_dir.clone(),
|
||||
"mcp".to_string(),
|
||||
item_id.clone(),
|
||||
"MCP note".to_string(),
|
||||
)
|
||||
.expect("save MCP note");
|
||||
assert_eq!(
|
||||
state
|
||||
.skills
|
||||
.iter()
|
||||
.find(|skill| skill.id == item_id)
|
||||
.and_then(|skill| skill.note.as_deref()),
|
||||
Some("我的 Skill 备注")
|
||||
);
|
||||
assert_eq!(
|
||||
state
|
||||
.mcp_servers
|
||||
.iter()
|
||||
.find(|server| server.id == item_id)
|
||||
.and_then(|server| server.note.as_deref()),
|
||||
Some("MCP note")
|
||||
);
|
||||
let state = save_skills_mcp_note_inner(
|
||||
config_dir.clone(),
|
||||
"mcp".to_string(),
|
||||
spaced_id.to_string(),
|
||||
"Spaced ID note".to_string(),
|
||||
)
|
||||
.expect("save note without normalizing the MCP ID");
|
||||
assert_eq!(
|
||||
state
|
||||
.mcp_servers
|
||||
.iter()
|
||||
.find(|server| server.id == spaced_id)
|
||||
.and_then(|server| server.note.as_deref()),
|
||||
Some("Spaced ID note")
|
||||
);
|
||||
|
||||
let other_config_dir = Some(other_codex_dir.display().to_string());
|
||||
let other_state = build_skills_mcp_state_inner(other_config_dir.clone())
|
||||
.expect("load other CODEX_HOME state");
|
||||
assert!(other_state
|
||||
.mcp_servers
|
||||
.iter()
|
||||
.find(|server| server.id == item_id)
|
||||
.is_some_and(|server| server.note.is_none()));
|
||||
save_skills_mcp_note_inner(
|
||||
other_config_dir,
|
||||
"mcp".to_string(),
|
||||
item_id.clone(),
|
||||
"Other MCP note".to_string(),
|
||||
)
|
||||
.expect("save note for other CODEX_HOME");
|
||||
let original_state = build_skills_mcp_state_inner(config_dir.clone())
|
||||
.expect("reload original CODEX_HOME state");
|
||||
assert_eq!(
|
||||
original_state
|
||||
.mcp_servers
|
||||
.iter()
|
||||
.find(|server| server.id == item_id)
|
||||
.and_then(|server| server.note.as_deref()),
|
||||
Some("MCP note")
|
||||
);
|
||||
|
||||
let state = save_skills_mcp_note_inner(
|
||||
config_dir.clone(),
|
||||
"skill".to_string(),
|
||||
item_id.clone(),
|
||||
" ".to_string(),
|
||||
)
|
||||
.expect("clear skill note");
|
||||
assert!(state
|
||||
.skills
|
||||
.iter()
|
||||
.find(|skill| skill.id == item_id)
|
||||
.is_some_and(|skill| skill.note.is_none()));
|
||||
assert_eq!(
|
||||
state
|
||||
.mcp_servers
|
||||
.iter()
|
||||
.find(|server| server.id == item_id)
|
||||
.and_then(|server| server.note.as_deref()),
|
||||
Some("MCP note")
|
||||
);
|
||||
assert!(save_skills_mcp_note_inner(
|
||||
config_dir.clone(),
|
||||
"unknown".to_string(),
|
||||
item_id.clone(),
|
||||
"note".to_string(),
|
||||
)
|
||||
.is_err());
|
||||
assert!(save_skills_mcp_note_inner(
|
||||
config_dir,
|
||||
"mcp".to_string(),
|
||||
item_id.clone(),
|
||||
"x".repeat(SKILLS_MCP_NOTE_MAX_CHARS + 1),
|
||||
)
|
||||
.is_err());
|
||||
|
||||
let conn = open_db().expect("reopen app database");
|
||||
conn.execute(
|
||||
"DELETE FROM skills_mcp_notes WHERE item_id IN (?1, ?2)",
|
||||
params![&item_id, spaced_id],
|
||||
)
|
||||
.expect("remove test notes");
|
||||
drop(conn);
|
||||
fs::remove_dir_all(&codex_dir).expect("remove test Codex directory");
|
||||
fs::remove_dir_all(&other_codex_dir).expect("remove other test Codex directory");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
use super::build_skills_mcp_state_inner;
|
||||
use super::types::{CcSwitchSkillMeta, ManagedSkill, SkillsMcpActionResult, SkillsMcpState};
|
||||
use crate::ccswitch::default_ccswitch_db_path;
|
||||
use crate::constants::MAX_SKILL_ZIP_BYTES;
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::{ensure_directory, io_err, read_to_string_if_exists};
|
||||
use crate::paths::app_home;
|
||||
use crate::{now_rfc3339, open_db, resolve_codex_dir};
|
||||
use chrono::Local;
|
||||
use rusqlite::{params, Connection, OpenFlags};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
@@ -101,8 +99,15 @@ fn compute_dir_hash(dir: &Path) -> Result<String> {
|
||||
.replace('\\', "/");
|
||||
hasher.update(rel.as_bytes());
|
||||
hasher.update(b"\0");
|
||||
let bytes = fs::read(&path).map_err(|e| io_err(&path, e))?;
|
||||
hasher.update(&bytes);
|
||||
let mut file = fs::File::open(&path).map_err(|e| io_err(&path, e))?;
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
loop {
|
||||
let size = file.read(&mut buffer).map_err(|e| io_err(&path, e))?;
|
||||
if size == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..size]);
|
||||
}
|
||||
hasher.update(b"\0");
|
||||
}
|
||||
Ok(format!("{:x}", hasher.finalize()))
|
||||
@@ -258,6 +263,7 @@ pub(super) fn scan_skill_dir(
|
||||
id: id.clone(),
|
||||
name,
|
||||
description,
|
||||
note: None,
|
||||
directory,
|
||||
enabled,
|
||||
source: source.to_string(),
|
||||
@@ -337,83 +343,7 @@ pub(crate) fn install_skill_zip_inner(
|
||||
file_name: String,
|
||||
bytes: Vec<u8>,
|
||||
) -> Result<SkillsMcpActionResult> {
|
||||
let codex_dir = resolve_codex_dir(config_dir.clone())?;
|
||||
let skills_dir = codex_skills_dir(&codex_dir);
|
||||
ensure_directory(&skills_dir)?;
|
||||
let mut archive = zip::ZipArchive::new(Cursor::new(bytes))
|
||||
.map_err(|e| CodexxError::Config(format!("读取 ZIP 失败: {e}")))?;
|
||||
let tmp = app_home()?
|
||||
.join("tmp")
|
||||
.join(format!("skill-zip-{}", Local::now().timestamp_millis()));
|
||||
ensure_directory(&tmp)?;
|
||||
let install_result = (|| -> Result<usize> {
|
||||
let mut total_size = 0u64;
|
||||
for i in 0..archive.len() {
|
||||
let mut file = archive
|
||||
.by_index(i)
|
||||
.map_err(|e| CodexxError::Config(format!("读取 ZIP 条目失败: {e}")))?;
|
||||
let Some(path) = file.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
continue;
|
||||
};
|
||||
total_size += file.size();
|
||||
if total_size > MAX_SKILL_ZIP_BYTES {
|
||||
return Err(CodexxError::Config("ZIP 解压后超过 20MB".to_string()));
|
||||
}
|
||||
let out = tmp.join(path);
|
||||
if file.name().ends_with('/') {
|
||||
ensure_directory(&out)?;
|
||||
} else {
|
||||
if let Some(parent) = out.parent() {
|
||||
ensure_directory(parent)?;
|
||||
}
|
||||
let mut outfile = fs::File::create(&out).map_err(|e| io_err(&out, e))?;
|
||||
std::io::copy(&mut file, &mut outfile).map_err(|e| io_err(&out, e))?;
|
||||
}
|
||||
}
|
||||
|
||||
let mut skill_dirs = Vec::new();
|
||||
fn find_skill_dirs(current: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
|
||||
if current.join("SKILL.md").is_file() {
|
||||
out.push(current.to_path_buf());
|
||||
return Ok(());
|
||||
}
|
||||
for entry in fs::read_dir(current).map_err(|e| io_err(current, e))? {
|
||||
let entry = entry.map_err(|e| io_err(current, e))?;
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
find_skill_dirs(&path, out)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
find_skill_dirs(&tmp, &mut skill_dirs)?;
|
||||
if skill_dirs.is_empty() {
|
||||
return Err(CodexxError::Config("ZIP 中没有找到 SKILL.md".to_string()));
|
||||
}
|
||||
let mut imported_skills = 0usize;
|
||||
for src in skill_dirs {
|
||||
let fallback = file_name.trim_end_matches(".zip");
|
||||
let dir_name = src.file_name().and_then(|v| v.to_str()).unwrap_or(fallback);
|
||||
let (skill_name, _) = read_skill_metadata(&src, dir_name);
|
||||
let dst_name = sanitize_dir_name(&skill_name, "skill");
|
||||
let dst = skills_dir.join(dst_name);
|
||||
if dst.exists() {
|
||||
fs::remove_dir_all(&dst).map_err(|e| io_err(&dst, e))?;
|
||||
}
|
||||
copy_dir_recursive(&src, &dst)?;
|
||||
imported_skills += 1;
|
||||
}
|
||||
Ok(imported_skills)
|
||||
})();
|
||||
let _ = fs::remove_dir_all(&tmp);
|
||||
let imported_skills = install_result?;
|
||||
let state = build_skills_mcp_state_inner(config_dir)?;
|
||||
Ok(SkillsMcpActionResult {
|
||||
imported_skills,
|
||||
imported_mcp: 0,
|
||||
message: format!("已从 ZIP 安装 {imported_skills} 个 Skill"),
|
||||
state,
|
||||
})
|
||||
super::archive::install_archive_reader(config_dir, file_name, Cursor::new(bytes))
|
||||
}
|
||||
|
||||
fn ccswitch_skill_meta_by_directory() -> Result<HashMap<String, CcSwitchSkillMeta>> {
|
||||
|
||||
@@ -10,6 +10,7 @@ pub(crate) struct ManagedMcpServer {
|
||||
pub(crate) enabled: bool,
|
||||
pub(crate) source: String,
|
||||
pub(crate) summary: String,
|
||||
pub(crate) note: Option<String>,
|
||||
pub(crate) command: Option<String>,
|
||||
pub(crate) url: Option<String>,
|
||||
pub(crate) config_json: Value,
|
||||
@@ -21,6 +22,7 @@ pub(crate) struct ManagedSkill {
|
||||
pub(crate) id: String,
|
||||
pub(crate) name: String,
|
||||
pub(crate) description: Option<String>,
|
||||
pub(crate) note: Option<String>,
|
||||
pub(crate) directory: String,
|
||||
pub(crate) enabled: bool,
|
||||
pub(crate) source: String,
|
||||
@@ -64,3 +66,11 @@ pub(super) struct CcSwitchSkillMeta {
|
||||
pub(super) repo_branch: String,
|
||||
pub(super) content_hash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct SkillsMcpExportResult {
|
||||
pub(crate) path: String,
|
||||
pub(crate) exported_skills: usize,
|
||||
pub(crate) exported_mcp: usize,
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
pub(crate) struct BuiltinSkinAsset {
|
||||
pub(crate) id: &'static str,
|
||||
pub(crate) manifest: &'static str,
|
||||
pub(crate) image: &'static [u8],
|
||||
}
|
||||
|
||||
pub(crate) const BUILTIN_SKIN_ID: &str = "shiina-mashiro-blossom";
|
||||
|
||||
pub(crate) fn retired_builtin_skin_ids() -> &'static [&'static str] {
|
||||
&[
|
||||
"preset-midnight-aurora",
|
||||
"preset-sakura-dawn",
|
||||
"preset-amber-dusk",
|
||||
"preset-forest-mist",
|
||||
"preset-cyber-neon",
|
||||
]
|
||||
}
|
||||
|
||||
pub(crate) fn builtin_skin_assets() -> &'static [BuiltinSkinAsset] {
|
||||
&[BuiltinSkinAsset {
|
||||
id: BUILTIN_SKIN_ID,
|
||||
manifest: include_str!("../resources/skin-presets/shiina-mashiro-blossom/theme.json"),
|
||||
image: include_bytes!("../resources/skin-presets/shiina-mashiro-blossom/background.png"),
|
||||
}]
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::{atomic_write, ensure_directory};
|
||||
use crate::skins::skins_root;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(super) const RUNTIME_VERSION: &str = "1.2.2-codexx.3";
|
||||
pub(super) const UPSTREAM_COMMIT: &str = "5fd8af532efbaa87d2d0092297fd2d45cd56574e";
|
||||
|
||||
struct EmbeddedRuntimeAsset {
|
||||
relative_path: &'static str,
|
||||
bytes: &'static [u8],
|
||||
}
|
||||
|
||||
fn embedded_assets() -> &'static [EmbeddedRuntimeAsset] {
|
||||
&[
|
||||
EmbeddedRuntimeAsset {
|
||||
relative_path: "scripts/injector.mjs",
|
||||
bytes: include_bytes!("../../resources/skin-runtime/scripts/injector.mjs"),
|
||||
},
|
||||
EmbeddedRuntimeAsset {
|
||||
relative_path: "scripts/image-metadata.mjs",
|
||||
bytes: include_bytes!("../../resources/skin-runtime/scripts/image-metadata.mjs"),
|
||||
},
|
||||
EmbeddedRuntimeAsset {
|
||||
relative_path: "scripts/stage-theme.mjs",
|
||||
bytes: include_bytes!("../../resources/skin-runtime/scripts/stage-theme.mjs"),
|
||||
},
|
||||
EmbeddedRuntimeAsset {
|
||||
relative_path: "assets/dream-skin.css",
|
||||
bytes: include_bytes!("../../resources/skin-runtime/assets/dream-skin.css"),
|
||||
},
|
||||
EmbeddedRuntimeAsset {
|
||||
relative_path: "assets/renderer-inject.js",
|
||||
bytes: include_bytes!("../../resources/skin-runtime/assets/renderer-inject.js"),
|
||||
},
|
||||
EmbeddedRuntimeAsset {
|
||||
relative_path: "windows/codexx-windows.ps1",
|
||||
bytes: include_bytes!("../../resources/skin-runtime/windows/codexx-windows.ps1"),
|
||||
},
|
||||
EmbeddedRuntimeAsset {
|
||||
relative_path: "windows/common-windows.ps1",
|
||||
bytes: include_bytes!("../../resources/skin-runtime/windows/common-windows.ps1"),
|
||||
},
|
||||
EmbeddedRuntimeAsset {
|
||||
relative_path: "windows/config-utf8.ps1",
|
||||
bytes: include_bytes!("../../resources/skin-runtime/windows/config-utf8.ps1"),
|
||||
},
|
||||
EmbeddedRuntimeAsset {
|
||||
relative_path: "LICENSE",
|
||||
bytes: include_bytes!("../../resources/skin-runtime/LICENSE"),
|
||||
},
|
||||
EmbeddedRuntimeAsset {
|
||||
relative_path: "NOTICE.md",
|
||||
bytes: include_bytes!("../../resources/skin-runtime/NOTICE.md"),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn bytes_match(path: &Path, expected: &[u8]) -> bool {
|
||||
if !fs::symlink_metadata(path)
|
||||
.is_ok_and(|metadata| metadata.is_file() && !metadata.file_type().is_symlink())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Ok(actual) = fs::read(path) else {
|
||||
return false;
|
||||
};
|
||||
Sha256::digest(actual) == Sha256::digest(expected)
|
||||
}
|
||||
|
||||
pub(super) fn ensure_runtime_directory(path: &Path) -> Result<()> {
|
||||
ensure_directory(path)?;
|
||||
let metadata =
|
||||
fs::symlink_metadata(path).map_err(|source| crate::file_io::io_err(path, source))?;
|
||||
if metadata.file_type().is_symlink() || !metadata.is_dir() {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"皮肤运行时目录不能是符号链接或普通文件: {}",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
set_private_permissions(path, true)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn set_private_permissions(path: &Path, directory: bool) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let mode = if directory { 0o700 } else { 0o600 };
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(mode))
|
||||
.map_err(|source| crate::file_io::io_err(path, source))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn set_private_permissions(_path: &Path, _directory: bool) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) struct RuntimeAssets {
|
||||
pub(super) injector: PathBuf,
|
||||
pub(super) stage_theme: PathBuf,
|
||||
#[cfg(any(target_os = "windows", feature = "windows-runtime-check"))]
|
||||
#[cfg_attr(feature = "windows-runtime-check", allow(dead_code))]
|
||||
pub(super) windows_adapter: PathBuf,
|
||||
}
|
||||
|
||||
pub(super) fn ensure_runtime_assets() -> Result<RuntimeAssets> {
|
||||
let base = skins_root()?.join("runtime");
|
||||
ensure_runtime_directory(&base)?;
|
||||
let root = base.join(RUNTIME_VERSION);
|
||||
ensure_runtime_directory(&root)?;
|
||||
for asset in embedded_assets() {
|
||||
let path = root.join(asset.relative_path);
|
||||
let parent = path.parent().ok_or_else(|| {
|
||||
CodexxError::Config(format!("内置皮肤资源路径无效: {}", path.display()))
|
||||
})?;
|
||||
ensure_runtime_directory(parent)?;
|
||||
if !bytes_match(&path, asset.bytes) {
|
||||
atomic_write(&path, asset.bytes)?;
|
||||
}
|
||||
set_private_permissions(&path, false)?;
|
||||
}
|
||||
Ok(RuntimeAssets {
|
||||
injector: root.join("scripts/injector.mjs"),
|
||||
stage_theme: root.join("scripts/stage-theme.mjs"),
|
||||
#[cfg(any(target_os = "windows", feature = "windows-runtime-check"))]
|
||||
windows_adapter: root.join("windows/codexx-windows.ps1"),
|
||||
})
|
||||
}
|
||||
@@ -1,786 +0,0 @@
|
||||
use super::assets::{
|
||||
ensure_runtime_assets, ensure_runtime_directory, RuntimeAssets, RUNTIME_VERSION,
|
||||
UPSTREAM_COMMIT,
|
||||
};
|
||||
use super::macos_injector::{
|
||||
launch_watcher, remove_live_skin, run_injector_once, stage_theme_snapshot,
|
||||
};
|
||||
use super::macos_system::{discover_codex_runtime, CodexRuntime};
|
||||
use super::{SkinRuntimeAction, SkinRuntimeStatus};
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::{atomic_write, io_err};
|
||||
use crate::now_rfc3339;
|
||||
use crate::skins::skins_root;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const DEFAULT_CDP_PORT: u16 = 9341;
|
||||
const MAX_CDP_PORT_OFFSET: u16 = 100;
|
||||
const RUNTIME_STATE_SCHEMA: u32 = 1;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RuntimeStateFile {
|
||||
schema_version: u32,
|
||||
runtime_version: String,
|
||||
upstream_commit: String,
|
||||
session: String,
|
||||
port: u16,
|
||||
injector_pid: u32,
|
||||
injector_started_at: String,
|
||||
injector_path: String,
|
||||
node_path: String,
|
||||
node_version: String,
|
||||
codex_bundle: String,
|
||||
codex_executable: String,
|
||||
codex_version: String,
|
||||
codex_team_id: String,
|
||||
theme_id: String,
|
||||
theme_dir: String,
|
||||
created_at: String,
|
||||
updated_at: String,
|
||||
}
|
||||
|
||||
fn runtime_root() -> Result<PathBuf> {
|
||||
Ok(skins_root()?.join("runtime"))
|
||||
}
|
||||
|
||||
fn state_path() -> Result<PathBuf> {
|
||||
Ok(runtime_root()?.join("state.json"))
|
||||
}
|
||||
|
||||
pub(super) fn snapshots_root() -> Result<PathBuf> {
|
||||
Ok(runtime_root()?.join("themes"))
|
||||
}
|
||||
|
||||
fn logs_root() -> Result<PathBuf> {
|
||||
Ok(runtime_root()?.join("logs"))
|
||||
}
|
||||
|
||||
fn read_runtime_state() -> Result<Option<RuntimeStateFile>> {
|
||||
let path = state_path()?;
|
||||
let metadata = match fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(io_err(&path, error)),
|
||||
};
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() || metadata.len() > 256 * 1024 {
|
||||
return Err(CodexxError::Config(
|
||||
"皮肤运行状态文件不是安全的普通文件,已停止自动处理".to_string(),
|
||||
));
|
||||
}
|
||||
let bytes = fs::read(&path).map_err(|source| io_err(&path, source))?;
|
||||
let state: RuntimeStateFile = serde_json::from_slice(&bytes)
|
||||
.map_err(|error| CodexxError::Config(format!("解析皮肤运行状态失败: {error}")))?;
|
||||
if state.schema_version != RUNTIME_STATE_SCHEMA || !(1024..=65535).contains(&state.port) {
|
||||
return Err(CodexxError::Config(
|
||||
"皮肤运行状态版本或端口无效,已停止自动处理".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(Some(state))
|
||||
}
|
||||
|
||||
fn write_runtime_state(state: &RuntimeStateFile) -> Result<()> {
|
||||
let path = state_path()?;
|
||||
let text = serde_json::to_string_pretty(state)
|
||||
.map_err(|error| CodexxError::Config(format!("序列化皮肤运行状态失败: {error}")))?;
|
||||
atomic_write(&path, format!("{text}\n").as_bytes())?;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))
|
||||
.map_err(|source| io_err(&path, source))
|
||||
}
|
||||
|
||||
fn remove_runtime_state() -> Result<()> {
|
||||
let path = state_path()?;
|
||||
match fs::remove_file(&path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(io_err(&path, error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn process_table() -> Vec<(u32, String)> {
|
||||
let Ok(output) = Command::new("/bin/ps")
|
||||
.args(["-axo", "pid=,command="])
|
||||
.output()
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let trimmed = line.trim_start();
|
||||
let split = trimmed.find(char::is_whitespace)?;
|
||||
let pid = trimmed[..split].parse::<u32>().ok()?;
|
||||
Some((pid, trimmed[split..].trim_start().to_string()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn process_command(pid: u32) -> Option<String> {
|
||||
let output = Command::new("/bin/ps")
|
||||
.args(["-p", &pid.to_string(), "-o", "command="])
|
||||
.output()
|
||||
.ok()?;
|
||||
let command = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
(!command.is_empty()).then_some(command)
|
||||
}
|
||||
|
||||
pub(super) fn process_started_at(pid: u32) -> Option<String> {
|
||||
let output = Command::new("/bin/ps")
|
||||
.args(["-p", &pid.to_string(), "-o", "lstart="])
|
||||
.output()
|
||||
.ok()?;
|
||||
let value = String::from_utf8_lossy(&output.stdout)
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
(!value.is_empty()).then_some(value)
|
||||
}
|
||||
|
||||
pub(super) fn process_alive(pid: u32) -> bool {
|
||||
pid > 0
|
||||
&& Command::new("/bin/kill")
|
||||
.args(["-0", &pid.to_string()])
|
||||
.status()
|
||||
.is_ok_and(|status| status.success())
|
||||
}
|
||||
|
||||
fn codex_main_pids(runtime: &CodexRuntime) -> Vec<u32> {
|
||||
let prefix = runtime.executable.to_string_lossy();
|
||||
process_table()
|
||||
.into_iter()
|
||||
.filter_map(|(pid, command)| command.starts_with(prefix.as_ref()).then_some(pid))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn codex_is_running(runtime: &CodexRuntime) -> bool {
|
||||
!codex_main_pids(runtime).is_empty()
|
||||
}
|
||||
|
||||
fn debug_port_from_command(command: &str) -> Option<u16> {
|
||||
command.split_whitespace().find_map(|argument| {
|
||||
argument
|
||||
.strip_prefix("--remote-debugging-port=")?
|
||||
.parse::<u16>()
|
||||
.ok()
|
||||
.filter(|port| *port >= 1024)
|
||||
})
|
||||
}
|
||||
|
||||
fn process_parent(pid: u32) -> Option<u32> {
|
||||
let output = Command::new("/bin/ps")
|
||||
.args(["-p", &pid.to_string(), "-o", "ppid="])
|
||||
.output()
|
||||
.ok()?;
|
||||
String::from_utf8_lossy(&output.stdout).trim().parse().ok()
|
||||
}
|
||||
|
||||
fn pid_is_codex_descendant(runtime: &CodexRuntime, mut pid: u32) -> bool {
|
||||
let executable = runtime.executable.to_string_lossy();
|
||||
for _ in 0..32 {
|
||||
if process_command(pid).is_some_and(|command| command.starts_with(executable.as_ref())) {
|
||||
return true;
|
||||
}
|
||||
let Some(parent) = process_parent(pid) else {
|
||||
return false;
|
||||
};
|
||||
if parent <= 1 || parent == pid {
|
||||
return false;
|
||||
}
|
||||
pid = parent;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn listener_pids(port: u16) -> Vec<u32> {
|
||||
let Ok(output) = Command::new("/usr/sbin/lsof")
|
||||
.args(["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN", "-t"])
|
||||
.output()
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.lines()
|
||||
.filter_map(|line| line.trim().parse().ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn port_belongs_to_codex(runtime: &CodexRuntime, port: u16) -> bool {
|
||||
let pids = listener_pids(port);
|
||||
!pids.is_empty()
|
||||
&& pids
|
||||
.into_iter()
|
||||
.all(|pid| pid_is_codex_descendant(runtime, pid))
|
||||
}
|
||||
|
||||
fn cdp_http_ready(port: u16) -> bool {
|
||||
let Ok(client) = reqwest::blocking::Client::builder()
|
||||
.no_proxy()
|
||||
.timeout(Duration::from_secs(2))
|
||||
.build()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
client
|
||||
.get(format!("http://127.0.0.1:{port}/json/version"))
|
||||
.send()
|
||||
.is_ok_and(|response| response.status().is_success())
|
||||
}
|
||||
|
||||
fn verified_cdp_endpoint(runtime: &CodexRuntime, port: u16) -> bool {
|
||||
port_belongs_to_codex(runtime, port) && cdp_http_ready(port)
|
||||
}
|
||||
|
||||
fn running_cdp_port(runtime: &CodexRuntime) -> Option<u16> {
|
||||
codex_main_pids(runtime)
|
||||
.into_iter()
|
||||
.filter_map(process_command)
|
||||
.filter_map(|command| debug_port_from_command(&command))
|
||||
.find(|port| verified_cdp_endpoint(runtime, *port))
|
||||
}
|
||||
|
||||
fn select_available_port(preferred: u16) -> Result<u16> {
|
||||
let last = preferred.saturating_add(MAX_CDP_PORT_OFFSET);
|
||||
(preferred..=last)
|
||||
.find(|port| listener_pids(*port).is_empty())
|
||||
.ok_or_else(|| {
|
||||
CodexxError::Config(format!("未找到可用的本机 CDP 端口: {preferred}-{last}"))
|
||||
})
|
||||
}
|
||||
|
||||
fn wait_for_cdp(runtime: &CodexRuntime, port: u16, timeout: Duration) -> Result<()> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
while Instant::now() < deadline {
|
||||
if verified_cdp_endpoint(runtime, port) {
|
||||
return Ok(());
|
||||
}
|
||||
thread::sleep(Duration::from_millis(350));
|
||||
}
|
||||
Err(CodexxError::Config(format!(
|
||||
"Codex 未在 127.0.0.1:{port} 打开经过验证的调试端口"
|
||||
)))
|
||||
}
|
||||
|
||||
fn external_skin_watcher_pid(own_state: Option<&RuntimeStateFile>) -> Option<u32> {
|
||||
process_table().into_iter().find_map(|(pid, command)| {
|
||||
let is_external = command.contains("codex-dream-skin-studio")
|
||||
&& command.contains("injector.mjs")
|
||||
&& command.contains("--watch");
|
||||
(is_external && own_state.is_none_or(|state| state.injector_pid != pid)).then_some(pid)
|
||||
})
|
||||
}
|
||||
|
||||
fn canonical_managed_snapshot(path: &Path) -> Option<PathBuf> {
|
||||
let metadata = fs::symlink_metadata(path).ok()?;
|
||||
if metadata.file_type().is_symlink() || !metadata.is_dir() {
|
||||
return None;
|
||||
}
|
||||
let root = fs::canonicalize(snapshots_root().ok()?).ok()?;
|
||||
let candidate = fs::canonicalize(path).ok()?;
|
||||
candidate.starts_with(&root).then_some(candidate)
|
||||
}
|
||||
|
||||
fn is_managed_injector(path: &Path) -> bool {
|
||||
let Ok(metadata) = fs::symlink_metadata(path) else {
|
||||
return false;
|
||||
};
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() {
|
||||
return false;
|
||||
}
|
||||
let Ok(root) = runtime_root()
|
||||
.and_then(|path| fs::canonicalize(&path).map_err(|source| io_err(&path, source)))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
fs::canonicalize(path).is_ok_and(|candidate| {
|
||||
candidate.starts_with(root)
|
||||
&& candidate.file_name().and_then(|name| name.to_str()) == Some("injector.mjs")
|
||||
})
|
||||
}
|
||||
|
||||
fn state_process_matches(state: &RuntimeStateFile, runtime: &CodexRuntime) -> bool {
|
||||
if state.injector_pid == 0
|
||||
|| state.node_path != runtime.node.to_string_lossy()
|
||||
|| !is_managed_injector(Path::new(&state.injector_path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if canonical_managed_snapshot(Path::new(&state.theme_dir)).is_none() {
|
||||
return false;
|
||||
}
|
||||
let Some(command) = process_command(state.injector_pid) else {
|
||||
return false;
|
||||
};
|
||||
let expected = format!(
|
||||
"{} --watch --port {} --theme-dir {}",
|
||||
state.injector_path, state.port, state.theme_dir
|
||||
);
|
||||
command.starts_with(runtime.node.to_string_lossy().as_ref())
|
||||
&& command.contains(&expected)
|
||||
&& process_started_at(state.injector_pid).as_deref()
|
||||
== Some(state.injector_started_at.as_str())
|
||||
}
|
||||
|
||||
fn stop_recorded_injector(state: &RuntimeStateFile, runtime: &CodexRuntime) -> Result<()> {
|
||||
if state.injector_pid == 0 || !process_alive(state.injector_pid) {
|
||||
return Ok(());
|
||||
}
|
||||
if !state_process_matches(state, runtime) {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"记录的皮肤进程 PID {} 身份不匹配,已拒绝终止",
|
||||
state.injector_pid
|
||||
)));
|
||||
}
|
||||
let pid = state.injector_pid.to_string();
|
||||
let _ = Command::new("/bin/kill").args(["-TERM", &pid]).status();
|
||||
let deadline = Instant::now() + Duration::from_secs(6);
|
||||
while Instant::now() < deadline && state_process_matches(state, runtime) {
|
||||
thread::sleep(Duration::from_millis(150));
|
||||
}
|
||||
if state_process_matches(state, runtime) {
|
||||
let _ = Command::new("/bin/kill").args(["-KILL", &pid]).status();
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while Instant::now() < deadline && state_process_matches(state, runtime) {
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
if state_process_matches(state, runtime) {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"无法停止皮肤注入器 PID {}",
|
||||
state.injector_pid
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stop_codex(runtime: &CodexRuntime) -> Result<()> {
|
||||
let _ = Command::new("/usr/bin/osascript")
|
||||
.args(["-e", "tell application id \"com.openai.codex\" to quit"])
|
||||
.status();
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
while Instant::now() < deadline && codex_is_running(runtime) {
|
||||
thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
if !codex_is_running(runtime) {
|
||||
return Ok(());
|
||||
}
|
||||
for pid in codex_main_pids(runtime) {
|
||||
let _ = Command::new("/bin/kill")
|
||||
.args(["-TERM", &pid.to_string()])
|
||||
.status();
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while Instant::now() < deadline && codex_is_running(runtime) {
|
||||
thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
if codex_is_running(runtime) {
|
||||
for pid in codex_main_pids(runtime) {
|
||||
let _ = Command::new("/bin/kill")
|
||||
.args(["-KILL", &pid.to_string()])
|
||||
.status();
|
||||
}
|
||||
thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
if codex_is_running(runtime) {
|
||||
Err(CodexxError::Config(
|
||||
"无法安全关闭 Codex,换肤操作已中止".to_string(),
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn log_files(prefix: &str) -> Result<(File, File)> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let root = logs_root()?;
|
||||
ensure_runtime_directory(&root)?;
|
||||
let stdout_path = root.join(format!("{prefix}.log"));
|
||||
let stderr_path = root.join(format!("{prefix}-error.log"));
|
||||
let stdout = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.open(&stdout_path)
|
||||
.map_err(|source| io_err(&stdout_path, source))?;
|
||||
let stderr = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.open(&stderr_path)
|
||||
.map_err(|source| io_err(&stderr_path, source))?;
|
||||
fs::set_permissions(&stdout_path, fs::Permissions::from_mode(0o600))
|
||||
.map_err(|source| io_err(&stdout_path, source))?;
|
||||
fs::set_permissions(&stderr_path, fs::Permissions::from_mode(0o600))
|
||||
.map_err(|source| io_err(&stderr_path, source))?;
|
||||
Ok((stdout, stderr))
|
||||
}
|
||||
|
||||
fn launch_codex_with_cdp(runtime: &CodexRuntime, port: u16) -> Result<()> {
|
||||
let (stdout, stderr) = log_files("codex-launch")?;
|
||||
let status = Command::new("/usr/bin/open")
|
||||
.arg("-na")
|
||||
.arg(&runtime.bundle)
|
||||
.arg("--args")
|
||||
.arg("--remote-debugging-address=127.0.0.1")
|
||||
.arg(format!("--remote-debugging-port={port}"))
|
||||
.stdout(Stdio::from(stdout))
|
||||
.stderr(Stdio::from(stderr))
|
||||
.status()
|
||||
.map_err(|source| io_err(&runtime.bundle, source))?;
|
||||
if !status.success() {
|
||||
return Err(CodexxError::Config(
|
||||
"使用本机调试端口启动 Codex 失败".to_string(),
|
||||
));
|
||||
}
|
||||
if wait_for_cdp(runtime, port, Duration::from_secs(12)).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if codex_is_running(runtime) {
|
||||
stop_codex(runtime)?;
|
||||
}
|
||||
let (stdout, stderr) = log_files("codex-launch-direct")?;
|
||||
let mut child = Command::new(&runtime.executable)
|
||||
.arg("--remote-debugging-address=127.0.0.1")
|
||||
.arg(format!("--remote-debugging-port={port}"))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::from(stdout))
|
||||
.stderr(Stdio::from(stderr))
|
||||
.spawn()
|
||||
.map_err(|source| io_err(&runtime.executable, source))?;
|
||||
thread::Builder::new()
|
||||
.name("codex-x-codex-launch-reaper".to_string())
|
||||
.spawn(move || {
|
||||
let _ = child.wait();
|
||||
})
|
||||
.map_err(|error| CodexxError::Config(format!("启动 Codex 进程监控失败: {error}")))?;
|
||||
wait_for_cdp(runtime, port, Duration::from_secs(45))
|
||||
}
|
||||
|
||||
fn launch_codex_normally(runtime: &CodexRuntime) -> Result<()> {
|
||||
let status = Command::new("/usr/bin/open")
|
||||
.arg("-na")
|
||||
.arg(&runtime.bundle)
|
||||
.status()
|
||||
.map_err(|source| io_err(&runtime.bundle, source))?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CodexxError::Config(
|
||||
"恢复官方外观后重新启动 Codex 失败".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn active_state(
|
||||
runtime: &CodexRuntime,
|
||||
assets: &RuntimeAssets,
|
||||
port: u16,
|
||||
theme_id: &str,
|
||||
theme_dir: &Path,
|
||||
pid: u32,
|
||||
started_at: String,
|
||||
) -> RuntimeStateFile {
|
||||
let timestamp = now_rfc3339();
|
||||
RuntimeStateFile {
|
||||
schema_version: RUNTIME_STATE_SCHEMA,
|
||||
runtime_version: RUNTIME_VERSION.to_string(),
|
||||
upstream_commit: UPSTREAM_COMMIT.to_string(),
|
||||
session: "active".to_string(),
|
||||
port,
|
||||
injector_pid: pid,
|
||||
injector_started_at: started_at,
|
||||
injector_path: assets.injector.to_string_lossy().to_string(),
|
||||
node_path: runtime.node.to_string_lossy().to_string(),
|
||||
node_version: runtime.node_version.clone(),
|
||||
codex_bundle: runtime.bundle.to_string_lossy().to_string(),
|
||||
codex_executable: runtime.executable.to_string_lossy().to_string(),
|
||||
codex_version: runtime.version.clone(),
|
||||
codex_team_id: runtime.team_id.clone(),
|
||||
theme_id: theme_id.to_string(),
|
||||
theme_dir: theme_dir.to_string_lossy().to_string(),
|
||||
created_at: timestamp.clone(),
|
||||
updated_at: timestamp,
|
||||
}
|
||||
}
|
||||
|
||||
fn cleanup_snapshot(path: &str, keep: &Path) {
|
||||
let Some(path) = canonical_managed_snapshot(Path::new(path)) else {
|
||||
return;
|
||||
};
|
||||
let keep = canonical_managed_snapshot(keep);
|
||||
if keep.as_ref() != Some(&path) {
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_previous_after_failure(
|
||||
runtime: &CodexRuntime,
|
||||
assets: &RuntimeAssets,
|
||||
previous: Option<&RuntimeStateFile>,
|
||||
) {
|
||||
let Some(previous) = previous else {
|
||||
return;
|
||||
};
|
||||
let theme_dir = Path::new(&previous.theme_dir);
|
||||
if previous.session != "active"
|
||||
|| !theme_dir.is_dir()
|
||||
|| !verified_cdp_endpoint(runtime, previous.port)
|
||||
|| run_injector_once(runtime, assets, previous.port, theme_dir).is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Ok((pid, started_at)) = launch_watcher(runtime, assets, previous.port, theme_dir) {
|
||||
let restored = active_state(
|
||||
runtime,
|
||||
assets,
|
||||
previous.port,
|
||||
&previous.theme_id,
|
||||
theme_dir,
|
||||
pid,
|
||||
started_at,
|
||||
);
|
||||
let _ = write_runtime_state(&restored);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn apply_theme(
|
||||
source: &Path,
|
||||
theme_id: &str,
|
||||
restart_existing: bool,
|
||||
) -> Result<SkinRuntimeAction> {
|
||||
let runtime = discover_codex_runtime()?;
|
||||
let assets = ensure_runtime_assets()?;
|
||||
let previous = read_runtime_state()?;
|
||||
if let Some(pid) = external_skin_watcher_pid(previous.as_ref()) {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"检测到外部 Codex Dream Skin 注入器 PID {pid},请先在原工具中暂停或恢复官方外观"
|
||||
)));
|
||||
}
|
||||
|
||||
let running = codex_is_running(&runtime);
|
||||
let verified_port = previous
|
||||
.as_ref()
|
||||
.map(|state| state.port)
|
||||
.filter(|port| verified_cdp_endpoint(&runtime, *port))
|
||||
.or_else(|| running_cdp_port(&runtime));
|
||||
if running && verified_port.is_none() && !restart_existing {
|
||||
return Ok(SkinRuntimeAction::RestartRequired(
|
||||
"Codex 需要重启一次才能打开仅限本机的换肤调试端口".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let snapshot = stage_theme_snapshot(&runtime, &assets, source, theme_id)?;
|
||||
let apply_result = (|| -> Result<RuntimeStateFile> {
|
||||
if let Some(state) = previous.as_ref() {
|
||||
stop_recorded_injector(state, &runtime)?;
|
||||
}
|
||||
let port = if let Some(port) = verified_port {
|
||||
port
|
||||
} else {
|
||||
if running {
|
||||
stop_codex(&runtime)?;
|
||||
}
|
||||
let preferred = previous
|
||||
.as_ref()
|
||||
.map_or(DEFAULT_CDP_PORT, |state| state.port);
|
||||
let port = select_available_port(preferred)?;
|
||||
launch_codex_with_cdp(&runtime, port)?;
|
||||
port
|
||||
};
|
||||
run_injector_once(&runtime, &assets, port, &snapshot)?;
|
||||
let (pid, started_at) = launch_watcher(&runtime, &assets, port, &snapshot)?;
|
||||
let state = active_state(
|
||||
&runtime, &assets, port, theme_id, &snapshot, pid, started_at,
|
||||
);
|
||||
if let Err(error) = write_runtime_state(&state) {
|
||||
let _ = stop_recorded_injector(&state, &runtime);
|
||||
return Err(error);
|
||||
}
|
||||
Ok(state)
|
||||
})();
|
||||
|
||||
match apply_result {
|
||||
Ok(_) => {
|
||||
if let Some(previous) = previous.as_ref() {
|
||||
cleanup_snapshot(&previous.theme_dir, &snapshot);
|
||||
}
|
||||
Ok(SkinRuntimeAction::Applied("已应用 Codex 皮肤".to_string()))
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = fs::remove_dir_all(&snapshot);
|
||||
restore_previous_after_failure(&runtime, &assets, previous.as_ref());
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn pause_theme() -> Result<SkinRuntimeAction> {
|
||||
let assets = ensure_runtime_assets()?;
|
||||
let Some(mut state) = read_runtime_state()? else {
|
||||
return Ok(SkinRuntimeAction::Paused(
|
||||
"Codex 皮肤当前没有运行".to_string(),
|
||||
));
|
||||
};
|
||||
let runtime = discover_codex_runtime()?;
|
||||
if let Some(pid) = external_skin_watcher_pid(Some(&state)) {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"检测到外部 Codex Dream Skin 注入器 PID {pid},未处理该进程"
|
||||
)));
|
||||
}
|
||||
stop_recorded_injector(&state, &runtime)?;
|
||||
if verified_cdp_endpoint(&runtime, state.port) {
|
||||
if let Err(error) =
|
||||
remove_live_skin(&runtime, &assets, state.port, Path::new(&state.theme_dir))
|
||||
{
|
||||
restore_previous_after_failure(&runtime, &assets, Some(&state));
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
state.session = "paused".to_string();
|
||||
state.injector_pid = 0;
|
||||
state.injector_started_at.clear();
|
||||
state.updated_at = now_rfc3339();
|
||||
write_runtime_state(&state)?;
|
||||
Ok(SkinRuntimeAction::Paused(
|
||||
"已关闭 Codex 皮肤;Codex 保持打开".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn restore_official(restart_existing: bool) -> Result<SkinRuntimeAction> {
|
||||
let assets = ensure_runtime_assets()?;
|
||||
let Some(state) = read_runtime_state()? else {
|
||||
return Ok(SkinRuntimeAction::Restored(
|
||||
"Codex 当前已使用官方外观".to_string(),
|
||||
));
|
||||
};
|
||||
let runtime = discover_codex_runtime()?;
|
||||
if let Some(pid) = external_skin_watcher_pid(Some(&state)) {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"检测到外部 Codex Dream Skin 注入器 PID {pid},未处理该进程"
|
||||
)));
|
||||
}
|
||||
let running = codex_is_running(&runtime);
|
||||
let debug_ready = verified_cdp_endpoint(&runtime, state.port);
|
||||
if running && (debug_ready || state.session == "active") && !restart_existing {
|
||||
return Ok(SkinRuntimeAction::RestartRequired(
|
||||
"完整恢复需要重启 Codex,以关闭本机调试端口并清除当前渲染状态".to_string(),
|
||||
));
|
||||
}
|
||||
stop_recorded_injector(&state, &runtime)?;
|
||||
if debug_ready {
|
||||
remove_live_skin(&runtime, &assets, state.port, Path::new(&state.theme_dir))?;
|
||||
}
|
||||
if running && (debug_ready || state.session == "active") {
|
||||
stop_codex(&runtime)?;
|
||||
launch_codex_normally(&runtime)?;
|
||||
}
|
||||
remove_runtime_state()?;
|
||||
cleanup_snapshot(&state.theme_dir, Path::new(""));
|
||||
Ok(SkinRuntimeAction::Restored(
|
||||
"已恢复 Codex 官方外观并关闭 Codex-X 管理的换肤运行时".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn runtime_status() -> SkinRuntimeStatus {
|
||||
if let Err(error) = ensure_runtime_assets() {
|
||||
return SkinRuntimeStatus {
|
||||
supported: true,
|
||||
active: false,
|
||||
phase: "error".to_string(),
|
||||
port: None,
|
||||
theme_id: None,
|
||||
message: error.to_string(),
|
||||
};
|
||||
}
|
||||
let state = match read_runtime_state() {
|
||||
Ok(Some(state)) => state,
|
||||
Ok(None) => {
|
||||
return SkinRuntimeStatus {
|
||||
supported: true,
|
||||
active: false,
|
||||
phase: "inactive".to_string(),
|
||||
port: None,
|
||||
theme_id: None,
|
||||
message: "尚未应用 Codex 皮肤".to_string(),
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
return SkinRuntimeStatus {
|
||||
supported: true,
|
||||
active: false,
|
||||
phase: "error".to_string(),
|
||||
port: None,
|
||||
theme_id: None,
|
||||
message: error.to_string(),
|
||||
}
|
||||
}
|
||||
};
|
||||
if state.session == "paused" {
|
||||
return SkinRuntimeStatus {
|
||||
supported: true,
|
||||
active: false,
|
||||
phase: "paused".to_string(),
|
||||
port: Some(state.port),
|
||||
theme_id: Some(state.theme_id),
|
||||
message: "皮肤已暂停,Codex 保持打开".to_string(),
|
||||
};
|
||||
}
|
||||
let runtime = match discover_codex_runtime() {
|
||||
Ok(runtime) => runtime,
|
||||
Err(error) => {
|
||||
return SkinRuntimeStatus {
|
||||
supported: true,
|
||||
active: false,
|
||||
phase: "unavailable".to_string(),
|
||||
port: Some(state.port),
|
||||
theme_id: Some(state.theme_id),
|
||||
message: error.to_string(),
|
||||
}
|
||||
}
|
||||
};
|
||||
let active =
|
||||
state_process_matches(&state, &runtime) && verified_cdp_endpoint(&runtime, state.port);
|
||||
SkinRuntimeStatus {
|
||||
supported: true,
|
||||
active,
|
||||
phase: if active { "active" } else { "stale" }.to_string(),
|
||||
port: Some(state.port),
|
||||
theme_id: Some(state.theme_id),
|
||||
message: if active {
|
||||
"Codex 皮肤运行中".to_string()
|
||||
} else {
|
||||
"皮肤运行状态已失效,可重新应用或恢复官方外观".to_string()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn debug_port_parser_accepts_only_bounded_numeric_arguments() {
|
||||
assert_eq!(
|
||||
debug_port_from_command(
|
||||
"/Applications/ChatGPT.app/Contents/MacOS/ChatGPT --remote-debugging-port=9341"
|
||||
),
|
||||
Some(9341)
|
||||
);
|
||||
assert_eq!(
|
||||
debug_port_from_command("Codex --remote-debugging-port=80"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
debug_port_from_command("Codex --remote-debugging-port=not-a-port"),
|
||||
None
|
||||
);
|
||||
assert_eq!(debug_port_from_command("Codex"), None);
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
use super::assets::RuntimeAssets;
|
||||
use super::macos::{log_files, process_alive, process_started_at, snapshots_root};
|
||||
use super::macos_system::CodexRuntime;
|
||||
use super::node_runtime;
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::io_err;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(super) fn stage_theme_snapshot(
|
||||
runtime: &CodexRuntime,
|
||||
assets: &RuntimeAssets,
|
||||
source: &Path,
|
||||
theme_id: &str,
|
||||
) -> Result<PathBuf> {
|
||||
node_runtime::stage_theme_snapshot(&runtime.node, assets, &snapshots_root()?, source, theme_id)
|
||||
}
|
||||
|
||||
pub(super) fn run_injector_once(
|
||||
runtime: &CodexRuntime,
|
||||
assets: &RuntimeAssets,
|
||||
port: u16,
|
||||
theme_dir: &Path,
|
||||
) -> Result<()> {
|
||||
node_runtime::run_injector_once(&runtime.node, assets, port, theme_dir)
|
||||
}
|
||||
|
||||
pub(super) fn remove_live_skin(
|
||||
runtime: &CodexRuntime,
|
||||
assets: &RuntimeAssets,
|
||||
port: u16,
|
||||
theme_dir: &Path,
|
||||
) -> Result<()> {
|
||||
node_runtime::remove_live_skin(&runtime.node, assets, port, theme_dir)
|
||||
}
|
||||
|
||||
pub(super) fn launch_watcher(
|
||||
runtime: &CodexRuntime,
|
||||
assets: &RuntimeAssets,
|
||||
port: u16,
|
||||
theme_dir: &Path,
|
||||
) -> Result<(u32, String)> {
|
||||
let (stdout, stderr) = log_files("injector")?;
|
||||
let mut child = Command::new(&runtime.node)
|
||||
.arg(&assets.injector)
|
||||
.args(["--watch", "--port"])
|
||||
.arg(port.to_string())
|
||||
.arg("--theme-dir")
|
||||
.arg(theme_dir)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::from(stdout))
|
||||
.stderr(Stdio::from(stderr))
|
||||
.spawn()
|
||||
.map_err(|source| io_err(&assets.injector, source))?;
|
||||
let pid = child.id();
|
||||
thread::Builder::new()
|
||||
.name("codex-x-skin-injector-reaper".to_string())
|
||||
.spawn(move || {
|
||||
let _ = child.wait();
|
||||
})
|
||||
.map_err(|error| CodexxError::Config(format!("启动皮肤进程监控失败: {error}")))?;
|
||||
thread::sleep(Duration::from_millis(180));
|
||||
if !process_alive(pid) {
|
||||
return Err(CodexxError::Config(
|
||||
"皮肤注入器启动后立即退出,请检查运行日志".to_string(),
|
||||
));
|
||||
}
|
||||
let started_at = process_started_at(pid)
|
||||
.ok_or_else(|| CodexxError::Config("无法记录皮肤注入器启动时间".to_string()))?;
|
||||
Ok((pid, started_at))
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
use super::node_runtime::command_detail;
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::io_err;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
const EXPECTED_BUNDLE_ID: &str = "com.openai.codex";
|
||||
const EXPECTED_TEAM_ID: &str = "2DC432GLL2";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct CodexRuntime {
|
||||
pub(super) bundle: PathBuf,
|
||||
pub(super) executable: PathBuf,
|
||||
pub(super) version: String,
|
||||
pub(super) node: PathBuf,
|
||||
pub(super) node_version: String,
|
||||
pub(super) team_id: String,
|
||||
}
|
||||
|
||||
fn output_text(program: &Path, args: &[&str], label: &str) -> Result<String> {
|
||||
let output = Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|source| io_err(program, source))?;
|
||||
if !output.status.success() {
|
||||
let detail = command_detail(&output);
|
||||
return Err(CodexxError::Config(if detail.is_empty() {
|
||||
format!("{label}失败")
|
||||
} else {
|
||||
format!("{label}失败: {detail}")
|
||||
}));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
fn plist_value(bundle: &Path, key: &str) -> Result<String> {
|
||||
let plist = bundle.join("Contents/Info.plist");
|
||||
output_text(
|
||||
Path::new("/usr/bin/plutil"),
|
||||
&["-extract", key, "raw", "-o", "-", &plist.to_string_lossy()],
|
||||
"读取 Codex 应用信息",
|
||||
)
|
||||
}
|
||||
|
||||
fn bundle_candidates() -> Result<Vec<PathBuf>> {
|
||||
let home = crate::paths::home_dir()?;
|
||||
let mut candidates = vec![
|
||||
PathBuf::from("/Applications/ChatGPT.app"),
|
||||
home.join("Applications/ChatGPT.app"),
|
||||
PathBuf::from("/Applications/Codex.app"),
|
||||
home.join("Applications/Codex.app"),
|
||||
];
|
||||
if let Ok(output) = Command::new("/usr/bin/mdfind")
|
||||
.arg(format!(
|
||||
"kMDItemCFBundleIdentifier == \"{EXPECTED_BUNDLE_ID}\""
|
||||
))
|
||||
.output()
|
||||
{
|
||||
if output.status.success() {
|
||||
candidates.extend(
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|line| !line.is_empty())
|
||||
.map(PathBuf::from),
|
||||
);
|
||||
}
|
||||
}
|
||||
candidates.dedup();
|
||||
Ok(candidates)
|
||||
}
|
||||
|
||||
fn codesign_team_id(path: &Path) -> Result<String> {
|
||||
let output = Command::new("/usr/bin/codesign")
|
||||
.args(["-dv", "--verbose=4"])
|
||||
.arg(path)
|
||||
.output()
|
||||
.map_err(|source| io_err(path, source))?;
|
||||
let combined = format!(
|
||||
"{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
combined
|
||||
.lines()
|
||||
.find_map(|line| line.trim().strip_prefix("TeamIdentifier="))
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| CodexxError::Config("无法读取 Codex 签名 Team ID".to_string()))
|
||||
}
|
||||
|
||||
fn verify_signature(path: &Path, deep: bool) -> Result<()> {
|
||||
let mut command = Command::new("/usr/bin/codesign");
|
||||
command.arg("--verify");
|
||||
if deep {
|
||||
command.arg("--deep");
|
||||
}
|
||||
let output = command
|
||||
.arg("--strict")
|
||||
.arg(path)
|
||||
.output()
|
||||
.map_err(|source| io_err(path, source))?;
|
||||
if output.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CodexxError::Config(format!(
|
||||
"官方 Codex 代码签名校验失败: {}",
|
||||
path.display()
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn discover_codex_runtime() -> Result<CodexRuntime> {
|
||||
let mut bundle = None;
|
||||
for candidate in bundle_candidates()? {
|
||||
if !candidate.join("Contents/Info.plist").is_file() {
|
||||
continue;
|
||||
}
|
||||
if plist_value(&candidate, "CFBundleIdentifier")
|
||||
.ok()
|
||||
.as_deref()
|
||||
== Some(EXPECTED_BUNDLE_ID)
|
||||
{
|
||||
bundle = Some(candidate);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let bundle = bundle.ok_or_else(|| {
|
||||
CodexxError::Config("未找到官方 Codex Desktop (com.openai.codex)".to_string())
|
||||
})?;
|
||||
let executable_name = plist_value(&bundle, "CFBundleExecutable")?;
|
||||
if executable_name.is_empty() || executable_name.contains('/') || executable_name.contains('\\')
|
||||
{
|
||||
return Err(CodexxError::Config(
|
||||
"Codex 应用声明了无效的可执行文件名".to_string(),
|
||||
));
|
||||
}
|
||||
let executable = bundle.join("Contents/MacOS").join(executable_name);
|
||||
let node = bundle.join("Contents/Resources/cua_node/bin/node");
|
||||
if !executable.is_file() || !node.is_file() {
|
||||
return Err(CodexxError::Config(
|
||||
"Codex 可执行文件或内置 Node.js 不存在,请更新或重新安装官方 Codex".to_string(),
|
||||
));
|
||||
}
|
||||
verify_signature(&bundle, true)?;
|
||||
verify_signature(&node, false)?;
|
||||
let team_id = codesign_team_id(&bundle)?;
|
||||
let node_team_id = codesign_team_id(&node)?;
|
||||
if team_id != EXPECTED_TEAM_ID || node_team_id != team_id {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"Codex 签名身份不匹配,拒绝启动换肤运行时: {team_id}"
|
||||
)));
|
||||
}
|
||||
let node_version = output_text(&node, &["--version"], "读取 Codex Node.js 版本")?;
|
||||
let node_major = node_version
|
||||
.trim_start_matches('v')
|
||||
.split('.')
|
||||
.next()
|
||||
.and_then(|value| value.parse::<u32>().ok())
|
||||
.ok_or_else(|| CodexxError::Config(format!("无法解析 Node.js 版本: {node_version}")))?;
|
||||
if node_major < 20 {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"Codex 内置 Node.js 版本过低: {node_version},需要 20 或更高版本"
|
||||
)));
|
||||
}
|
||||
let machine_arch = output_text(Path::new("/usr/bin/uname"), &["-m"], "读取系统架构")?;
|
||||
let node_file = output_text(
|
||||
Path::new("/usr/bin/file"),
|
||||
&[&node.to_string_lossy()],
|
||||
"读取 Codex Node.js 架构",
|
||||
)?;
|
||||
if !node_file.contains(&machine_arch) {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"Codex 内置 Node.js 与当前 Mac 架构不匹配: {machine_arch}"
|
||||
)));
|
||||
}
|
||||
Ok(CodexRuntime {
|
||||
version: plist_value(&bundle, "CFBundleShortVersionString")?,
|
||||
bundle,
|
||||
executable,
|
||||
node,
|
||||
node_version,
|
||||
team_id,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn command_detail_is_bounded() {
|
||||
let output = Command::new("/usr/bin/printf")
|
||||
.arg("%0900d")
|
||||
.arg("1")
|
||||
.output()
|
||||
.expect("create fixture output");
|
||||
assert!(command_detail(&output).chars().count() <= 800);
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
use crate::error::CodexxError;
|
||||
use crate::error::Result;
|
||||
use serde::Serialize;
|
||||
use std::path::Path;
|
||||
|
||||
mod assets;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos_injector;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos_system;
|
||||
mod node_runtime;
|
||||
#[cfg(any(target_os = "windows", feature = "windows-runtime-check"))]
|
||||
#[cfg_attr(feature = "windows-runtime-check", allow(dead_code))]
|
||||
mod windows;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct SkinRuntimeStatus {
|
||||
pub(crate) supported: bool,
|
||||
pub(crate) active: bool,
|
||||
pub(crate) phase: String,
|
||||
pub(crate) port: Option<u16>,
|
||||
pub(crate) theme_id: Option<String>,
|
||||
pub(crate) message: String,
|
||||
}
|
||||
|
||||
impl SkinRuntimeStatus {
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn unsupported() -> Self {
|
||||
Self {
|
||||
supported: false,
|
||||
active: false,
|
||||
phase: "unsupported".to_string(),
|
||||
port: None,
|
||||
theme_id: None,
|
||||
message: "当前版本的 Codex 实机换肤仅支持 macOS 和 Windows".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum SkinRuntimeAction {
|
||||
Applied(String),
|
||||
RestartRequired(String),
|
||||
Paused(String),
|
||||
Restored(String),
|
||||
}
|
||||
|
||||
pub(crate) fn skin_runtime_status() -> SkinRuntimeStatus {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::runtime_status()
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
windows::runtime_status()
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
SkinRuntimeStatus::unsupported()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply_skin_runtime(
|
||||
theme_dir: &Path,
|
||||
theme_id: &str,
|
||||
restart_existing: bool,
|
||||
) -> Result<SkinRuntimeAction> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::apply_theme(theme_dir, theme_id, restart_existing)
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
windows::apply_theme(theme_dir, theme_id, restart_existing)
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
let _ = (theme_dir, theme_id, restart_existing);
|
||||
Err(CodexxError::Config(
|
||||
"当前版本的 Codex 实机换肤仅支持 macOS 和 Windows".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn pause_skin_runtime() -> Result<SkinRuntimeAction> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::pause_theme()
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
windows::pause_theme()
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
Err(CodexxError::Config(
|
||||
"当前版本的 Codex 实机换肤仅支持 macOS 和 Windows".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn restore_skin_runtime(restart_existing: bool) -> Result<SkinRuntimeAction> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::restore_official(restart_existing)
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
windows::restore_official(restart_existing)
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
let _ = restart_existing;
|
||||
Err(CodexxError::Config(
|
||||
"当前版本的 Codex 实机换肤仅支持 macOS 和 Windows".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
use super::assets::{ensure_runtime_directory, RuntimeAssets};
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::io_err;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const COMMAND_POLL_INTERVAL: Duration = Duration::from_millis(25);
|
||||
const THEME_STAGE_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const PAYLOAD_CHECK_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const INJECTOR_ONCE_TIMEOUT: Duration = Duration::from_secs(35);
|
||||
const INJECTOR_REMOVE_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
pub(super) fn command_detail(output: &std::process::Output) -> String {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
let detail = if stderr.is_empty() { stdout } else { stderr };
|
||||
if detail.chars().count() <= 800 {
|
||||
detail
|
||||
} else {
|
||||
detail
|
||||
.chars()
|
||||
.rev()
|
||||
.take(800)
|
||||
.collect::<String>()
|
||||
.chars()
|
||||
.rev()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn wait_for_output(
|
||||
mut child: std::process::Child,
|
||||
program: &Path,
|
||||
label: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<std::process::Output> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
match child.try_wait().map_err(|source| io_err(program, source))? {
|
||||
Some(_) => {
|
||||
return child
|
||||
.wait_with_output()
|
||||
.map_err(|source| io_err(program, source))
|
||||
}
|
||||
None if Instant::now() >= deadline => {
|
||||
let _ = child.kill();
|
||||
let output = child
|
||||
.wait_with_output()
|
||||
.map_err(|source| io_err(program, source))?;
|
||||
let detail = command_detail(&output);
|
||||
let suffix = if detail.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(": {detail}")
|
||||
};
|
||||
return Err(CodexxError::Config(format!(
|
||||
"{label}超时({} 秒){suffix}",
|
||||
timeout.as_secs()
|
||||
)));
|
||||
}
|
||||
None => thread::sleep(COMMAND_POLL_INTERVAL),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run_node(
|
||||
node: &Path,
|
||||
script: &Path,
|
||||
args: &[String],
|
||||
label: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<String> {
|
||||
let child = Command::new(node)
|
||||
.arg(script)
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|source| io_err(script, source))?;
|
||||
let output = wait_for_output(child, script, label, timeout)?;
|
||||
if output.status.success() {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
} else {
|
||||
let detail = command_detail(&output);
|
||||
Err(CodexxError::Config(if detail.is_empty() {
|
||||
format!("{label}失败")
|
||||
} else {
|
||||
format!("{label}失败: {detail}")
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn stage_theme_snapshot(
|
||||
node: &Path,
|
||||
assets: &RuntimeAssets,
|
||||
snapshots_root: &Path,
|
||||
source: &Path,
|
||||
theme_id: &str,
|
||||
) -> Result<PathBuf> {
|
||||
ensure_runtime_directory(snapshots_root)?;
|
||||
let snapshot = snapshots_root.join(format!(
|
||||
"{}-{}-{}",
|
||||
theme_id,
|
||||
std::process::id(),
|
||||
chrono::Local::now()
|
||||
.timestamp_nanos_opt()
|
||||
.unwrap_or_default()
|
||||
));
|
||||
ensure_runtime_directory(&snapshot)?;
|
||||
let result = (|| -> Result<()> {
|
||||
run_node(
|
||||
node,
|
||||
&assets.stage_theme,
|
||||
&[
|
||||
source.to_string_lossy().to_string(),
|
||||
snapshot.to_string_lossy().to_string(),
|
||||
],
|
||||
"暂存主题",
|
||||
THEME_STAGE_TIMEOUT,
|
||||
)?;
|
||||
run_node(
|
||||
node,
|
||||
&assets.injector,
|
||||
&[
|
||||
"--check-payload".to_string(),
|
||||
"--theme-dir".to_string(),
|
||||
snapshot.to_string_lossy().to_string(),
|
||||
],
|
||||
"校验主题注入负载",
|
||||
PAYLOAD_CHECK_TIMEOUT,
|
||||
)?;
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_dir_all(&snapshot);
|
||||
}
|
||||
result.map(|_| snapshot)
|
||||
}
|
||||
|
||||
pub(super) fn run_injector_once(
|
||||
node: &Path,
|
||||
assets: &RuntimeAssets,
|
||||
port: u16,
|
||||
theme_dir: &Path,
|
||||
) -> Result<()> {
|
||||
run_node(
|
||||
node,
|
||||
&assets.injector,
|
||||
&[
|
||||
"--once".to_string(),
|
||||
"--port".to_string(),
|
||||
port.to_string(),
|
||||
"--theme-dir".to_string(),
|
||||
theme_dir.to_string_lossy().to_string(),
|
||||
"--timeout-ms".to_string(),
|
||||
"20000".to_string(),
|
||||
],
|
||||
"注入并验证 Codex 皮肤",
|
||||
INJECTOR_ONCE_TIMEOUT,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn remove_live_skin(
|
||||
node: &Path,
|
||||
assets: &RuntimeAssets,
|
||||
port: u16,
|
||||
theme_dir: &Path,
|
||||
) -> Result<()> {
|
||||
run_node(
|
||||
node,
|
||||
&assets.injector,
|
||||
&[
|
||||
"--remove".to_string(),
|
||||
"--port".to_string(),
|
||||
port.to_string(),
|
||||
"--theme-dir".to_string(),
|
||||
theme_dir.to_string_lossy().to_string(),
|
||||
"--timeout-ms".to_string(),
|
||||
"10000".to_string(),
|
||||
],
|
||||
"移除 Codex 皮肤",
|
||||
INJECTOR_REMOVE_TIMEOUT,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wait_for_output_collects_a_completed_child() {
|
||||
let child = Command::new("/bin/echo")
|
||||
.arg("skin-ready")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn echo fixture");
|
||||
let output = wait_for_output(
|
||||
child,
|
||||
Path::new("/bin/echo"),
|
||||
"测试皮肤命令",
|
||||
Duration::from_secs(1),
|
||||
)
|
||||
.expect("collect output");
|
||||
assert!(output.status.success());
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "skin-ready");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_for_output_terminates_a_stuck_child() {
|
||||
let child = Command::new("/bin/sleep")
|
||||
.arg("5")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn sleep fixture");
|
||||
let started = Instant::now();
|
||||
let error = wait_for_output(
|
||||
child,
|
||||
Path::new("/bin/sleep"),
|
||||
"测试皮肤命令",
|
||||
Duration::from_millis(80),
|
||||
)
|
||||
.expect_err("timeout stuck child");
|
||||
assert!(error.to_string().contains("超时"));
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||