diff --git a/.gitignore b/.gitignore
index 9b145a06d..49f529856 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,7 +8,7 @@ release/
*.tsbuildinfo
.npmrc
CLAUDE.md
-# AGENTS.md
+AGENTS.md
GEMINI.md
/.claude
/.codex
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8af8ef1e3..610c7dd67 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,122 @@ All notable changes to CC Switch will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [3.16.3] - 2026-06-14
+
+Development since v3.16.2 focuses on getting usage accounting right end-to-end — billing route-takeover and format-conversion traffic by the real upstream model and pricing basis (schema v11), counting Claude Code Workflow sub-agent sessions, folding Claude Desktop into the Claude view, refreshing the model pricing seed, and reworking the usage dashboard with global provider/model filters, brand-icon toolbars, and far more resilient quota queries — while hardening the proxy (mislabeled SSE bodies, Codex image rectification, OAuth token and takeover-residue recovery, Hermes duplicate YAML keys), reworking provider configuration (a custom User-Agent override, a unified Codex advanced section, searchable preset selection, a Fable 5 tier, and refreshed Kimi/Unity2/Volcengine/MiniMax presets), and smoothing the update, About-panel, and provider-health experiences.
+
+**Stats**: 59 commits | 130 files changed | +10,223 insertions | -4,232 deletions
+
+### Added
+
+- **Custom User-Agent Override**: Provider configs can now set a custom User-Agent that the proxy applies consistently across request forwarding, stream check, and model listing (`GET /v1/models`), so coding-plan upstreams that gate on UA no longer fail detection or return 403 while the proxy itself works. The Claude and Codex forms expose it in advanced settings with a curated presets dropdown (Claude Code / Kilo Code families that pass UA whitelists) and live non-blocking validation; stale custom UAs are dropped when switching to an official preset to avoid silently altering headers (#3671).
+- **Unified Codex Session History**: Official Codex sessions can now share a single resume-history bucket with cc-switch third-party sessions via an opt-in toggle under Settings → Codex App Enhancements, so the resume picker no longer hides them from each other. When enabled, the live `config.toml` routes official runs through a shared `custom` model_provider that mirrors the built-in OpenAI provider (`auth.json` is untouched); the toggle is forward-only by default but the enable dialog offers a checkbox to migrate existing official sessions (with per-generation backups), and the disable dialog offers a precise ledger-based restore that only reverts sessions originally recorded as `openai` while leaving sessions created during the toggle untouched.
+- **Dashboard-Wide Provider/Model Filters**: The provider and model filters move from inside the request-log table up to the top bar, applying globally to the hero summary, trend chart, request logs, and both stats tabs so you can scope the whole dashboard to a given source and model. Sources match by exact display name (so session placeholder rows like "Claude (Session)" are selectable) and models match by effective pricing model, with the model dropdown cascading from the selected source and both lists showing only options that have data in the current range.
+- **Refreshed Model Pricing Seed**: Added pricing for 9 models including Claude Fable 5, Grok 4.3, Mistral Medium 3.5 / Small 4, and Qwen 3.7 Max/Plus, and corrected 28 existing prices against current official vendor list pricing (GLM, Grok, MiMo, Doubao, Kimi, MiniMax, Mistral, Qwen) so usage cost estimates are accurate. Each change updates the seed for fresh installs and adds a guarded repair for existing databases without clobbering user-edited rows.
+- **Claude Fable 5 Model Tier**: Provider forms now expose `claude-fable-5` as a fourth model-mapping tier on both the Claude Code and Claude Desktop proxy paths, with a fable → opus → default fallback mirroring the official downgrade and the `fable-` prefix whitelisted for the Desktop 1.12603.1+ validator. A clarified four-language fallback hint warns that leaving a tier blank on third-party endpoints forwards the literal model name and 404s (#3980, #4026, #4049).
+- **Unity2.ai Partner Provider**: Added Unity2.ai, an AI API relay partner, as a preset across all seven managed apps (Claude Code, Codex, Gemini, OpenCode, OpenClaw, Claude Desktop, Hermes), each carrying the referral signup link and partner promotion copy in all four locales. Codex uses the bare base URL (the gateway exposes `/responses` at root) while OpenCode / OpenClaw / Hermes use the `/v1` chat-completions endpoint with `gpt-5.5`.
+- **Kimi K2.7 Code Model**: Added the `kimi-k2.7-code` model (in $0.95 / out $4.00 / cache-read $0.19 per 1M tokens, 256K context) and pointed all six official Moonshot Kimi presets (Claude Code, Codex, Claude Desktop, Hermes, OpenCode, OpenClaw) at it, renaming the OpenCode / OpenClaw presets to "Kimi K2.7 Code". The pricing seed applies on startup via the idempotent insert path, so existing users pick up the new pricing without a migration.
+- **Codex "Kimi For Coding" Preset Restored**: Re-added the Codex "Kimi For Coding" preset (`openai_chat`, `kimi-for-coding`, 256K context) with thinking mode enabled by default; it was previously removed because the coding endpoint rejects Codex's default `codex-cli` User-Agent with 403. It now works via proxy takeover combined with the custom User-Agent override (set to a whitelisted UA such as `claude-cli/*`).
+- **Pricing-Model Audit in Request Detail**: The request detail panel now shows the requested model and the pricing model when they differ from the response model, making route-takeover bills auditable directly from the usage UI.
+- **Preset Provider Search & Sorting**: The provider preset selector gains a searchable, sorted list with an inline search box (toggled via a magnifier icon, dismissed on ESC or outside click). Buttons use a responsive grid with consistent sizing and default icons, and search matches only provider display/raw names so URL fragments and shared category labels no longer produce noisy matches (#3975, #4183).
+- **Claude Mythos 5 Pricing**: Registered the `claude-mythos-5` model in the bundled model/pricing table (in $10 / out $50 per 1M tokens, cache read $1.00, cache write $12.50), so usage metering prices and displays it correctly (#4077).
+- **Fable 5 Verified Banner**: The Settings About page now displays a Fable 5 Verified banner beside the app name and version, marking this as a special build, with the version badge centered under the app name.
+
+### Changed
+
+- **Claude Desktop Usage Folded Into Claude**: The dashboard no longer shows a standalone "Claude Desktop" bucket, which only ever displayed a partial number (Desktop chat usage never passes through the proxy and its Code-tab sessions write into the shared `~/.claude/projects` tree). Desktop proxy traffic is now folded into the `claude` view for display while still recorded under its own `app_type` for route-takeover billing audit, with the real value visible in the request detail panel.
+- **Lightweight Provider Health Check**: The provider health check no longer sends a real streaming model request (which many third-party providers blocked with 401/403/WAF, causing false negatives); it now performs a lightweight HTTP reachability probe of the provider `base_url`, treating any HTTP response as reachable and counting only DNS/connect/TLS/timeout as failure. The connectivity button is hidden for official providers (which use OAuth with an empty base URL and no reliable reachability target), the real-request confirmation dialog and test model/prompt fields are removed, and the degraded-latency threshold is set to 6s with an 8s timeout. The reachability check never resets the circuit breaker, so failover detection stays driven solely by real proxy traffic.
+- **Codex Advanced Options Section**: The Codex provider form now folds local routing, model mapping, reasoning overrides, and custom User-Agent into a single collapsible advanced section mirroring the Claude form (auto-expanding when a UA is set or local routing is on). Custom User-Agent is now also configurable for native Responses providers, where it was previously reachable only with `openai_chat` routing enabled.
+- **Usage Toolbar Refresh and Layout**: The app filter now renders brand icons (via ProviderIcon, with a grid icon for "All") instead of text tabs that wrapped awkwardly in narrow windows, and the usage hero shows the selected app's brand icon with Codex recolored to a neutral gray matching OpenAI's monochrome branding. The click-to-cycle refresh button becomes a Select with a localized "off" label, and the top-bar controls are compacted and aligned into consistent width groups with truncated long date-range labels.
+- **Faster About Panel Loading**: The Settings About panel now loads progressively: the app version badge appears the instant it resolves instead of waiting for tool probes, each tool card updates the moment its own version check finishes (probes run concurrently rather than sequentially), and results are cached for the app session with a 10-minute TTL so reopening the About tab reuses cached values and revalidates stale ones in the background instead of re-probing all six tools every time.
+- **Volcengine Ark Coding Plan Promo**: Updated the Volcengine Ark preset across all six apps with the new Coding Plan invite link (replacing the old Agent Plan / activity links) and refreshed the partner promotion copy in all four locales (two-month 75% off plus invite code 6J6FV5N2), correcting the product name from Agent Plan to Coding Plan.
+- **MiniMax Demoted to Regular Provider**: Removed the gold partner star badge and the API-key promotion banner for MiniMax by dropping the `isPartner` flag from all its presets; it stays as a regular `cn_official` provider keeping its icon and theme. The promotion copy is kept dormant so the partnership can be re-enabled with a single line.
+- **LemonData Removed, SudoCode Demoted**: Removed the LemonData provider preset entirely from all apps along with its promotion copy, icons, and sponsor listings, and demoted SudoCode from a partner to a regular `third_party` provider by dropping its `isPartner` flag and promotion copy (it keeps its icon).
+- **AtlasCloud Codex GLM 5.1 Context Window**: Declared the 200,000-token context window for the `zai-org/glm-5.1` model in the AtlasCloud Codex preset, matching the other GLM 5.1 preset entries.
+
+### Fixed
+
+- **Route-Takeover Traffic Billed by the Real Upstream Model**: When a request was routed to a different upstream (env model mapping, Claude Desktop routes, Copilot normalization, Codex chat override), the proxy used to attribute and price usage by whatever model the upstream echoed back, recording kimi/glm tokens as `claude-*` and overstating cost roughly 5–25×. The forwarder now captures the real outbound model, attributes usage by upstream-echo then outbound then client alias, persists the actual pricing basis on every row (schema v11), and keeps that basis through cost backfill and 30-day rollup pruning; Claude Desktop traffic is now logged under its own `app_type` so its pricing overrides apply.
+- **Usage Metering on Format-Conversion Proxy Paths**: Audited and fixed token/cache accounting across the proxy's format-conversion paths (Chat, Responses, and Gemini converted to Anthropic). The proxy now records the actually returned model, injects `stream_options.include_usage` so OpenAI-compatible upstreams emit usage in streaming, excludes `cache_read` and `cache_creation` from input on Claude←OpenAI paths to stop double-billing cache tokens, subtracts cached Gemini prompt tokens, still records fully-cached requests, and skips synthetic all-zero usage that previously inflated request counts (#2774).
+- **In-App Update No Longer Hangs on Restart**: Installing an update from within the app no longer freezes on the "restarting" screen, leaving the new version installed but requiring a manual force-quit. The download-install-restart chain now runs entirely in the backend (a new `install_update_and_restart` command) with platform-aware install ordering and single-instance-lock teardown before re-exec, instead of depending on the old WebView to keep running JS after the app bundle was already swapped; exit requests are also classified so restart requests fall through to Tauri's default flow rather than deadlocking on the window-state plugin mutex (#4069, #4074).
+- **Codex Upgrade No Longer Breaks the Install**: Upgrading Codex from the Settings "About" tab no longer leaves it throwing "Missing optional dependency @openai/codex-…" errors. The upgrade chain previously ran `codex update` first, which on an npm install is a bare reinstall that reports success even when the per-platform binary fails to land; Codex is now removed from the self-update-first path and a runnable check triggers an uninstall+reinstall self-heal (scoped to npm-managed installs) that actually re-lands the missing platform binary.
+- **Codex OAuth Auth Token Preserved on Proxy Takeover**: Enabling proxy takeover for a Codex provider no longer strips the `ANTHROPIC_AUTH_TOKEN` placeholder, which previously broke Claude Code's login on hot-switches, fresh installs, and configs already stripped by older releases. The placeholder is now injected unconditionally for managed (non-Copilot) Codex providers, including URL-only ones; GitHub Copilot behavior (API_KEY only) is unchanged (#3789, #3784).
+- **Takeover-Residue Recovery Across Config-Dir Switches**: Restarting the app after changing the config directory while proxy takeover is active no longer leaves Claude/Codex/Gemini pointed at a dead local proxy. The old instance now restores the taken-over live files before restarting, the first-run import refuses to persist a takeover placeholder as a provider, and SSOT restore validates that the current provider's config is free of placeholders before writing it back (#4076).
+- **Mislabeled SSE Bodies in Format-Transform Fallback**: Requests routed through Claude/Codex format conversion no longer fail with an opaque 422 "Failed to parse upstream response" when a MaaS gateway force-streams a `stream:false` request and returns an SSE body under a non-SSE Content-Type. The proxy now sniffs for SSE on parse failure, aggregates the chunks into a single JSON, and runs the existing converter so clients still get a valid non-stream response; remaining parse failures are enriched with content-type, encoding, and body-snippet diagnostics, and deflate decoding now tries zlib before raw (#2234).
+- **Duplicate YAML Keys in Hermes Config**: Hermes config writes no longer accumulate duplicate top-level keys (e.g. `mcp_servers`) that caused "Failed to parse Hermes config as YAML: duplicate entry with key" errors. Section replacement now strips all stale occurrences from the remainder instead of degrading into appends, the dedup safety net handles both LF and CRLF line endings, and healing keeps the last (newest) occurrence to match Hermes's own last-wins PyYAML semantics (#3267, #3633, #2973, #2529, #3310, #3762).
+- **Usage Query Resilience and Error Clarity**: Usage cards no longer flip to red on a single transient blip: queries now retry once and keep showing the last successful result for up to 10 minutes on network/timeout/5xx failures, while deterministic failures (auth, empty key, unknown provider, 4xx) surface immediately and clear the snapshot so a stale quota can't resurface after credentials change. Native balance/coding-plan/subscription timeouts were raised from 10s to 15s for slow cross-border endpoints, and coding-plan now returns explicit "API key is empty" / "Unknown coding plan provider" errors instead of a blank failure.
+- **Usage Script Provider Credential Resolution**: Custom JS-script usage queries resolved `{{apiKey}}` / `{{baseUrl}}` by guessing env fields only, so providers that store credentials elsewhere (e.g. Codex's `auth.OPENAI_API_KEY` plus `config.toml` base_url) always got empty values and failed despite being fully configured. Script queries and the test/preview now reuse the same per-app credential resolver as the native balance path, with explicit non-empty script values still taking precedence (#1479).
+- **Claude Code Workflow Sub-Agent Usage Counted**: Local (no-proxy) session-log usage accounting missed Claude Code Workflow sub-agent traffic, under-counting overall usage by roughly 4.1% (concentrated in workflow/subagent transcripts). The scanner now descends into the deeper `subagents/workflows/wf_*/` transcript directories, and the parser no longer drops billable assistant messages that lack a `stop_reason` but already incurred input/cache token cost; dedup is unchanged so no usage is double-counted.
+- **Codex Image Rectifier for /responses Text-Only Upstreams**: Codex `/responses` requests carrying images and routed to text-only OpenAI-chat models (e.g. DeepSeek `deepseek-v4-flash`) no longer fail with HTTP 400 "unknown variant `image_url`". The media rectifier now also covers the Codex adapter, scanning the responses `input` for `input_image` blocks so it can proactively strip images for known text-only models and reactively retry with images replaced on upstream image-unsupported errors.
+- **Zhipu Coding-Plan Quota Window Mislabeling**: The Zhipu coding-plan view no longer swaps the 5-hour and weekly quota buckets in the final hours of each weekly cycle. The two windows are now classified by the explicit `unit` field (3 = 5-hour, 6 = weekly) instead of by sorting reset-time ascending, which mislabeled them exactly when users check their weekly quota most; the old reset-time heuristic remains as a fallback (#3036).
+- **Duplicate Provider Terminal Sessions on macOS**: Launching a provider terminal on macOS no longer opens an extra empty window alongside the command session; Terminal.app uses `launch` (not `activate`) on cold start and Ghostty uses an initial-command so a single session opens, with a fallback retained if the AppleScript path fails (#4156).
+- **Claude Desktop Model-Mapping Placeholders**: The Claude Desktop model-mapping form previously showed mismatched example brands across the menu display name and request model columns (DeepSeek vs Kimi), implying a display name maps to an unrelated model. Both placeholders are now derived from each row's role so they stay brand-consistent, with the lightweight Haiku tier using a flash example.
+- **Popovers Behind Fullscreen Panels**: Popovers and tooltips such as the provider preset search no longer render behind fullscreen panels and appear unresponsive on click; their z-index is raised above the fullscreen overlay while staying below modal dialogs.
+- **ToggleRow Icon Shrinking**: Toggle row icons no longer shrink or distort when paired with long descriptions, keeping the icon at a fixed size next to multi-line text.
+
+### Docs
+
+- **Release Notes Contributor Mentions**: Restored contributor mentions in the v3.16.1 and v3.16.2 release notes across all three locales.
+
+## [3.16.2] - 2026-06-07
+
+Development since v3.16.1 focuses on broadening data portability and usage observability — S3-compatible cloud sync, OpenCode session usage import, and an opt-in official-subscription quota template — while hardening Codex Chat Completions routing (stream truncation, `tool_choice` / custom-tool / reasoning-token edge cases, file and audio attachments, and a Codex CLI models endpoint), strengthening proxy robustness (ephemeral ports, takeover/placeholder restore, system-message normalization, clearer upstream errors, and a text-only image fallback), fixing coding-plan quota lookups (Zhipu, MiniMax) and several Windows/macOS issues, adding the CherryIN and ZenMux providers, and refreshing the user manual.
+
+**Stats**: 41 commits | 132 files changed | +11,116 insertions | -1,636 deletions
+
+### Added
+
+- **S3-Compatible Cloud Sync**: Cloud Sync now supports S3-compatible object storage as a second backend alongside WebDAV, using hand-rolled AWS Signature V4 signing for broad compatibility. The settings panel offers one-click presets for AWS S3, MinIO, Cloudflare R2, Alibaba Cloud OSS, Tencent Cloud COS, and Huawei OBS plus a custom endpoint, with connection testing, manual upload/download, and auto-sync on configuration changes (provider, endpoint, MCP, prompt, skill, settings, and proxy tables — not high-frequency data like usage logs); enabling S3 sync disables active WebDAV sync and vice versa (#1351).
+- **OpenCode Session Usage Sync**: Added OpenCode as a usage-statistics source that imports per-message token, cost, and model data from OpenCode's local SQLite database, with a new "OpenCode" app filter tab and an "OpenCode Session" data-source label. The database path respects `OPENCODE_DB` and `XDG_DATA_HOME` (defaulting to `~/.local/share/opencode` on all platforms), only finalized messages are imported, and the freshness check accounts for the WAL file so newly written sessions are not skipped (#3215).
+- **Official Subscription Quota Template**: Added an explicit, opt-in "official subscription" usage template for Claude, Codex, and Gemini official providers that queries plan quota via CLI/OAuth credentials, replacing the previous implicit auto-query. It is disabled by default and enabled from the usage-script modal with a configurable refresh interval.
+- **Unsupported Image Fallback Rectifier**: Added a proxy rectifier that replaces Anthropic image blocks with an `[Unsupported Image]` marker when the routed model is text-only (declared, or detected via a built-in model-name heuristic) or when the upstream rejects image input, so conversations are not interrupted. A new Settings toggle controls the fallback, with a separate toggle for the heuristic detection.
+- **ZenMux Token Plan Provider**: Added ZenMux as a Token Plan coding-plan provider that accepts a manually entered API key and base URL in the usage-script modal and renders its quota with USD-denominated used / limit values (#2709).
+- **CherryIN Preset**: Added the CherryIN aggregator gateway as a quick-config preset across all seven supported apps — Anthropic-format endpoint for Claude Code / Claude Desktop / OpenClaw / Hermes, `@ai-sdk/anthropic` for OpenCode, the OpenAI-compatible endpoint for Codex, and the Gemini-compatible endpoint for Gemini CLI — with the official brand icon, placed next to AiHubMix (#3643).
+- **CCSub Preset**: Added CCSub, a multi-model aggregator partner, as a quick-config preset across six apps — Claude Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes — with the official brand icon and the partner referral link prefilled as the API-key signup URL (`gpt-5.5` for the OpenAI-compatible Codex and OpenCode endpoints).
+- **Codex CLI Models Endpoint**: The local proxy now answers `GET /v1/models`, which Codex CLI probes at startup, returning the cc-switch-managed Codex model catalog. A stale-catalog guard parses the live `config.toml` and only serves the catalog when `model_catalog_json` still references the cc-switch-owned file, so a leftover catalog from a previous provider is not advertised (#3818).
+- **Codex Chat File and Audio Attachments**: The Codex Responses-to-Chat converter now maps `input_file` parts (carrying `file_id` or inline `file_data`) and `input_audio` parts into their Chat Completions equivalents, and emits top-level `input_*` items that were previously dropped, so file and audio attachments reach Chat-only Codex upstreams.
+
+### Changed
+
+- **Usage Dashboard Hero Redesign**: Restructured the Usage Dashboard hero and summary cards into a more compact layout, consolidating the real-token total, request count, and cost into a single top row (#3426).
+- **SSSAiCode Endpoint Refresh**: Updated the SSSAiCode preset's website, signup, and API base URLs to the `sssaicodeapi.com` domain and refreshed its endpoint nodes (default `node-hk.sssaicodeapi.com`, plus `node-hk.sssaiapi.com` and `node-cf.sssaicodeapi.com`) across all seven app presets.
+
+### Fixed
+
+- **Codex Chat Truncated Stream Detection**: When a Chat Completions upstream ends a stream without a `finish_reason` or `[DONE]`, CC Switch no longer reports it as a normal completion — it finalizes normally only when the stream truly finished, emits an incomplete (`max_output_tokens`) response when partial output was produced, and emits a failed `stream_truncated` event when nothing was produced. Late-arriving reasoning is also attached to still-active streamed tool calls.
+- **Codex Chat `tool_choice` Without Tools**: The Responses-to-Chat converter now drops `tool_choice` and `parallel_tool_calls` whenever the resulting tools array is absent or empty, so strict OpenAI-compatible upstreams (vLLM, enterprise gateways) no longer reject the request with "When using `tool_choice`, `tools` must be set." (#3640).
+- **Codex Custom Tool Metadata Over Chat Routing**: Custom Codex tools (such as the freeform `apply_patch` tool) now preserve their full original definition — including format and grammar metadata — as a compact, order-stable JSON block in the generated Chat function description instead of a generic placeholder, keeping them usable on Chat Completions upstreams (#3644).
+- **Codex Chat `reasoning_tokens` in Usage**: The Chat-to-Responses usage conversion now always includes `output_tokens_details.reasoning_tokens` (defaulting to 0), even when a provider omits `completion_tokens_details` or returns it as a non-object, satisfying the Codex CLI's strict requirement and avoiding repeated parse failures and retries (#3514).
+- **Codex Cross-Turn Reasoning for Custom and Search Tools**: The cross-turn reasoning cache in Codex Chat history now covers the full tool-call set (`function_call`, `custom_tool_call`, `tool_search_call`) and their outputs, so `apply_patch` and tool-search calls keep their `reasoning_content` when restored via `previous_response_id`.
+- **Ephemeral Proxy Port Resolution**: When the proxy listens on port 0 (OS-assigned), takeover now starts the proxy first to learn the real port and writes it into the Live configs and database, so client URLs no longer point at a broken `:0` address; the Claude Desktop gateway URL is rejected if no concrete port has been resolved.
+- **Proxy Placeholder Backup/Restore Loop**: If a previous proxy stop left the proxy placeholders in Live, taking over again no longer overwrites a good backup with the proxy config, and restore no longer writes the placeholder back to Live — both paths detect the placeholder state and rebuild Live from the current provider, fixing cases where the proxy toggle became a no-op and clients stayed pinned to the local proxy (#3689).
+- **Official Provider Block Under Proxy Takeover**: While Local Routing takeover is active, only providers explicitly categorized as official are blocked from switching, instead of also disabling custom providers whose endpoint lives in metadata or whose fields are unfilled. The disabled Enable button now shows a lighter hint tooltip in place of the red "Blocked" badge.
+- **Localhost Listen Address Normalization**: Saving the proxy with a listen address of `localhost` now normalizes it to `127.0.0.1` before persisting, avoiding binding inconsistencies (#3016).
+- **Anthropic System Message Normalization**: For Anthropic-format providers, system-role entries inside the `messages` array are collapsed and merged into the top-level `system` field (preserving order and any existing top-level system), preventing strict upstreams from rejecting non-leading system messages; OpenAI Chat routing is untouched (#3775).
+- **Claude Desktop 1M-Context Model Routing**: Claude Desktop appends a `[1m]` marker to the model name when the 1M-context beta is active (e.g. `claude-opus-4-8[1m]`). The proxy now strips that suffix before route lookup so exact, alias, legacy, and role-keyword matching resolve correctly, fixing `route_unknown` (HTTP 400) failures when switching to a 1M-capable model mid-conversation.
+- **Codex 413 Error Clarity**: When a Codex upstream gateway rejects an oversized request with HTTP 413, the proxy now returns a dedicated message identifying it as the provider's server-side body-size limit (not a CC Switch limit) with recovery steps (run `/compact`, drop large logs or inline images, or ask the provider to raise its limit), instead of echoing the raw upstream HTML page.
+- **Proxy Panel Error Detail**: When toggling proxy takeover fails, the proxy panel toast now includes the underlying backend error detail instead of only a generic failure message (#3656).
+- **Copilot Infinite-Whitespace Threshold**: Raised the streaming infinite-whitespace abort threshold from 20 to 500 consecutive whitespace characters, so legitimate tool calls with deeply indented code arguments are no longer falsely aborted while still catching the real Copilot infinite-whitespace bug (#2647).
+- **Subscription Tier Tray Rendering**: Fixed tray and quota rendering for official subscription tiers via a unified tier-to-label mapping: Claude/Codex no longer drop the seven-day window, Gemini Pro/Flash/Flash-Lite tiers no longer leak raw machine names, and multi-window plans (e.g. Opus + Sonnet) now display the worst utilization instead of the first match.
+- **Inflated Claude Stream Input Tokens**: Some Anthropic-compatible streaming providers (e.g. Qwen, MiniMax) report the full context as `input_tokens` in `message_start`, double-counting the cached portion and artificially lowering the displayed cache hit rate. The parser now prefers a smaller positive `input_tokens` from `message_delta` and adopts the paired cache counts from the same usage block; native Claude and OpenRouter-converted paths are unchanged.
+- **Zhipu Quota Query Endpoint Routing**: The Zhipu coding-plan quota lookup was hard-coded to `api.z.ai`, so users on the mainland China preset (`open.bigmodel.cn`) could not retrieve usage when the international endpoint was unreachable. The quota request now routes to the host matching the user's configured base URL (#3702).
+- **MiniMax Balance API and Pricing**: Adapted MiniMax coding-plan quota to its new balance API (which returns remaining-percent fields instead of usage counts that broke the old parser and left the tray blank), filtered out non-coding models (e.g. video), handled plans without a weekly limit, and seeded default pricing for MiniMax M3 (#3518).
+- **GLM Coding Plan Endpoints and Model Fetch**: Corrected the ZhiPu / Z.AI GLM Coding Plan presets to the `/api/coding/paas/v4` endpoints across Codex, OpenCode, OpenClaw, and Hermes, and taught the model-list probe to query `{base}/models` for base URLs that already end in a `/v{N}` segment (keeping `/v1/models` as a fallback), so the Fetch Models button no longer 404s on versioned endpoints (#3524).
+- **Codex Model Catalog Path Portability**: Codex now writes only the relative filename `cc-switch-model-catalog.json` to `config.toml` instead of an absolute path (Codex CLI resolves it from the config directory), fixing the model catalog breaking on WSL and symlinked setups where the absolute path could not be translated (#3614).
+- **APINebula OpenCode SDK**: The APINebula OpenCode preset now loads `@ai-sdk/openai-compatible` instead of `@ai-sdk/openai`, so requests use the OpenAI Chat Completions format the relay expects rather than the Responses API.
+- **Windows Tray Icon Residue on Exit**: Quitting CC Switch on Windows could leave a dead tray icon until hovered; the app now removes the tray icon before exiting so it disappears cleanly (#3797).
+- **Windows Taskbar Icon**: Set an explicit Windows AppUserModelID at runtime and stamped the installer's desktop and start-menu shortcuts with the same ID and product icon, so CC Switch shows the correct icon and groups properly in the taskbar (#3457).
+- **Windows Subdirectory Skill Updates**: Normalized backslash path separators to forward slashes when scanning installed skills on Windows, so skills nested in subdirectories (e.g. `skills/my-skill`) are matched by the update check instead of being silently skipped (#3430).
+- **macOS Input Auto-Capitalization**: Disabled autocomplete, autocorrect, autocapitalize, and spellcheck on the shared text Input component so macOS no longer auto-capitalizes or auto-corrects the first letter typed into configuration fields (#3626).
+- **Codex VS Code Session Previews**: Codex session previews for requests sent from VS Code could show selection or open-file content instead of the prompt when a markdown heading preceded the injected request. Both the backend title and frontend preview now match the last "## My request for Codex:" heading (the IDE injects the real request as the final section) (#3593).
+- **VS Code Wording in Chinese UI**: Corrected the "Apply to Claude Code plugin" description in the Simplified and Traditional Chinese locales to write "VS Code" properly instead of "Vscode", aligning with the English and Japanese strings (#3228).
+
+### Docs
+
+- **User Manual Refresh**: Refreshed the README locales and the en / zh / ja user manuals to reflect all seven supported apps (adding Claude Desktop and Hermes), corrected the OpenCode config path to `~/.config/opencode/` (`opencode.json`), documented Hermes configuration files, updated the language docs to four languages, revised per-app MCP / Prompts / Skills availability, noted that export produces a timestamped SQL backup including usage logs, and documented the pricing model-ID matching rules (#3411).
+- **Codex Official Auth Preservation Guide**: Added a trilingual (en / zh / ja) guide explaining how to keep Codex official remote control and plugins working while routing model traffic to third-party APIs, and linked it from the v3.16.1 release notes.
+- **README Release-Note Links and Sponsor Markup**: Updated the Release Notes links in all README locales to point at v3.16.1 and fixed broken smart-quote characters in the README_ZH sponsor blocks so their HTML attributes render correctly (#3772).
+
## [3.16.1] - 2026-06-01
Development since v3.16.0 focuses on hardening Codex provider switching and Local Routing takeover: preserving official OAuth auth and model catalogs across normal switches, hot-switches, backup restore, and edit flows; restoring Codex Chat tool/plugin compatibility over Chat Completions upstreams; improving Codex proxy diagnostics and CLI discovery; and documenting DeepSeek routing.
diff --git a/README.md b/README.md
index d75e3392f..6254991c4 100644
--- a/README.md
+++ b/README.md
@@ -63,7 +63,7 @@ Register now via this lin
-
Thanks to Dola seed for sponsoring this project! Dola Seed 2.0 is a full‑modal general large model independently developed by ByteDance for the global market. Built on a unified multimodal architecture, it supports joint understanding and generation of text, images, audio, and video. It natively enables agent collaboration, with strong reasoning, long‑task execution, tool integration, and coding capabilities. It is widely applicable to smart cockpits, personal assistants, education, customer support, marketing, retail, and other scenarios. It excels in multimodal perception, end‑to‑end complex task delivery, stable interaction, and data security, and is readily accessible and deployable via the ModelArk platform.Register via this link to get 500,000 tokens of free inference quota per model. >>中国大陆地区的开发者请点击这里
+
Thanks to Dola seed for sponsoring this project! Dola Seed 2.0 is a full‑modal general large model independently developed by ByteDance for the global market. Built on a unified multimodal architecture, it supports joint understanding and generation of text, images, audio, and video. It natively enables agent collaboration, with strong reasoning, long‑task execution, tool integration, and coding capabilities. It is widely applicable to smart cockpits, personal assistants, education, customer support, marketing, retail, and other scenarios. It excels in multimodal perception, end‑to‑end complex task delivery, stable interaction, and data security, and is readily accessible and deployable via the ModelArk platform.Register via this link to get 500,000 tokens of free inference quota per model. >>中国大陆地区的开发者请点击这里
Thanks to Micu API for sponsoring this project! Micu API is a global LLM relay service provider dedicated to delivering the best cost-performance ratio with high stability. Backed by a registered enterprise for core assurance, eliminating any risk of service discontinuation, with fast official invoicing support! We champion "zero cost to try": top up from as low as ¥1 with no minimum, and get fee-free refunds anytime! Micu API offers an exclusive deal for CC Switch users: register via this link and enter promo code "ccswitch" when topping up to enjoy a 10% discount!
-
-
-
Thanks to LemonData for sponsoring this project! LemonData is a high-performance AI API aggregation platform — one API key for 300+ models including GPT, Claude, Gemini, DeepSeek, and more. All models priced 30–70% below official rates with auto-failover, smart routing, and unlimited concurrency. New users get $1 free credit instantly upon registration — sign up via this linkto claim your bonus and start building right away!
-
-
Thanks to CTok.ai for sponsoring this project! CTok.ai is dedicated to building a one-stop AI programming tool service platform. We offer professional Claude Code packages and technical community services, with support for Google Gemini and OpenAI Codex. Through carefully designed plans and a professional tech community, we provide developers with reliable service guarantees and continuous technical support, making AI-assisted programming a true productivity tool. Click here to register!
Atlas Cloud is a full-modal AI inference platform that gives developers a single AI API to access video generation, image generation, and LLM APIs. Instead of managing multiple vendor integrations, you connect once and get unified access to 300+ curated models across all modalities. Check out Atlas Cloud's new coding plan promotion for more budget-friendly API access!
+
+
+
Thanks to CCSub for sponsoring this project! CCSub is a stable, affordable AI API relay platform — your drop-in replacement for a Claude.ai subscription. One API key gives you access to Claude Opus 4.8, Sonnet, Haiku, GPT-5, Gemini, and DeepSeek at roughly 30% of direct API cost, with no VPN required from anywhere in the world. Compatible with Claude Code, Codex, Cursor, Cline, Continue, Windsurf, and all major AI coding tools. Register via this link and get $5 free credit on sign-up.
+
+
+
+
+
Thanks to Unity2.ai for sponsoring this project! Unity2.ai is a high-performance AI model API relay platform for individual developers, teams, and enterprises. Long trusted by leading companies in China, it serves over 30 billion tokens per day and supports high concurrency at the 5,000 RPM level. It offers balance-based billing, first top-up bonuses, bundle subscriptions, corporate invoicing, and dedicated support. Register via this link to get $2 in credits, plus another $10 for joining the official group — up to $12 in free credits!
+
+
diff --git a/README_DE.md b/README_DE.md
index 54ed50d03..dfd1bf1c1 100644
--- a/README_DE.md
+++ b/README_DE.md
@@ -63,7 +63,7 @@ Registrieren Sie sich jetzt über
-
Danke an Dola seed für die Unterstützung dieses Projekts! Dola Seed 2.0 ist ein voll-modales Allzweck-Großmodell, das von ByteDance eigenständig für den globalen Markt entwickelt wurde. Aufbauend auf einer einheitlichen multimodalen Architektur unterstützt es das gemeinsame Verstehen und Generieren von Text, Bildern, Audio und Video. Es ermöglicht von Haus aus die Zusammenarbeit von Agenten und verfügt über starke Fähigkeiten in den Bereichen Schlussfolgern, Ausführung langer Aufgaben, Werkzeugintegration und Programmierung. Es ist breit einsetzbar — etwa für intelligente Cockpits, persönliche Assistenten, Bildung, Kundensupport, Marketing, Einzelhandel und weitere Szenarien. Es überzeugt bei multimodaler Wahrnehmung, der Ende-zu-Ende-Bewältigung komplexer Aufgaben, stabiler Interaktion und Datensicherheit und ist über die ModelArk-Plattform einfach zugänglich und bereitstellbar. Registrieren Sie sich über diesen Link und erhalten Sie pro Modell ein kostenloses Inferenzkontingent von 500.000 Token. >>中国大陆地区的开发者请点击这里
+
Danke an Dola seed für die Unterstützung dieses Projekts! Dola Seed 2.0 ist ein voll-modales Allzweck-Großmodell, das von ByteDance eigenständig für den globalen Markt entwickelt wurde. Aufbauend auf einer einheitlichen multimodalen Architektur unterstützt es das gemeinsame Verstehen und Generieren von Text, Bildern, Audio und Video. Es ermöglicht von Haus aus die Zusammenarbeit von Agenten und verfügt über starke Fähigkeiten in den Bereichen Schlussfolgern, Ausführung langer Aufgaben, Werkzeugintegration und Programmierung. Es ist breit einsetzbar — etwa für intelligente Cockpits, persönliche Assistenten, Bildung, Kundensupport, Marketing, Einzelhandel und weitere Szenarien. Es überzeugt bei multimodaler Wahrnehmung, der Ende-zu-Ende-Bewältigung komplexer Aufgaben, stabiler Interaktion und Datensicherheit und ist über die ModelArk-Plattform einfach zugänglich und bereitstellbar. Registrieren Sie sich über diesen Link und erhalten Sie pro Modell ein kostenloses Inferenzkontingent von 500.000 Token. >>中国大陆地区的开发者请点击这里
@@ -106,11 +106,6 @@ Registrieren Sie sich jetzt über diesen Link und geben Sie beim Aufladen den Gutscheincode „ccswitch" ein, um 10 % Rabatt zu erhalten!
-
-
-
Danke an LemonData für die Unterstützung dieses Projekts! LemonData ist eine leistungsstarke KI-API-Aggregationsplattform — ein API-Schlüssel für mehr als 300 Modelle, darunter GPT, Claude, Gemini, DeepSeek und weitere. Alle Modelle zu Preisen 30–70 % unter den offiziellen Tarifen, mit automatischem Failover, intelligentem Routing und unbegrenzter Nebenläufigkeit. Neukunden erhalten bei der Registrierung sofort 1 $ Gratisguthaben — registrieren Sie sich über diesen Link, um Ihren Bonus einzulösen und sofort mit dem Entwickeln zu beginnen!
-
-
Danke an CTok.ai für die Unterstützung dieses Projekts! CTok.ai widmet sich dem Aufbau einer Komplettlösung für KI-Programmierwerkzeuge. Wir bieten professionelle Claude-Code-Pakete und Dienste einer technischen Community, mit Unterstützung für Google Gemini und OpenAI Codex. Durch sorgfältig gestaltete Pläne und eine professionelle Tech-Community geben wir Entwicklern verlässliche Servicegarantien und kontinuierlichen technischen Support an die Hand und machen KI-gestützte Programmierung zu einem echten Produktivitätswerkzeug. Klicken Sie hier, um sich zu registrieren!
@@ -146,6 +141,16 @@ Registrieren Sie sich jetzt über Coding-Plan-Aktion von Atlas Cloud für kostengünstigeren API-Zugang an!
+
+
+
Danke an CCSub für die Unterstützung dieses Projekts! CCSub ist eine zuverlässige und kostengünstige AI-API-Relay-Plattform — Ihr direkter Ersatz für ein Claude.ai-Abonnement. Mit einem einzigen API-Schlüssel erhalten Sie Zugriff auf Claude Opus 4.8, Sonnet, Haiku, GPT-5, Gemini und DeepSeek zu etwa 30 % der Kosten der direkten API-Nutzung — ohne VPN, weltweit nutzbar. Kompatibel mit Claude Code, Codex, Cursor, Cline, Continue, Windsurf und allen gängigen AI-Coding-Tools. Registrieren Sie sich über diesen Link und erhalten Sie $5 Startguthaben bei der Anmeldung.
+
+
+
+
+
Danke an Unity2.ai für die Unterstützung dieses Projekts! Unity2.ai ist eine leistungsstarke AI-Modell-API-Relay-Plattform für Einzelentwickler, Teams und Unternehmen. Sie wird seit Langem von führenden Unternehmen in China genutzt, verarbeitet täglich über 30 Milliarden Tokens und unterstützt hohe Parallelität auf 5.000-RPM-Niveau. Geboten werden Guthaben-Abrechnung, Ersteinzahlungsbonus, Kombi-Abonnements, Firmenrechnungen und persönliche Betreuung. Registrieren Sie sich über diesen Link und erhalten Sie $2 Guthaben, plus weitere $10 für den Beitritt zur offiziellen Gruppe — bis zu $12 Gratis-Guthaben!
Atlas Cloud は、1 つの API で動画・画像生成や LLM(大規模言語モデル)を利用できる全モーダル対応の AI 推論プラットフォームです。複数のベンダーを個別に管理する手間を省き、一度の接続で 300 以上の厳選されたマルチモーダルモデルにアクセスできます。より低コストで API を利用できる、開発者向けの新しい「コーディングプラン」プロモーションをぜひチェックしてください!
+
+
+
CCSub のご支援に感謝します!CCSub は安定した低価格の AI API リレープラットフォームで、Claude Code 公式サブスクリプションの強力な代替です。1 つの API キーで Claude Opus 4.8、Sonnet 4.6、Haiku 4.5、GPT-5、Gemini、DeepSeek の全モデルを公式直接利用の約 1/3 のコストでご利用いただけます。VPN 不要で世界中から直接接続可能。Claude Code、Codex、Cursor、Cline、Continue、Windsurf など主要な AI コーディングツールすべてに対応しています。こちらのリンクから登録すると $5 の無料クレジットがもらえます。
+
+
+
+
+
Unity2.ai のご支援に感謝します!Unity2.ai は個人開発者・チーム・企業向けの高性能 AI モデル API リレープラットフォームです。中国の大手企業に長年利用されており、1 日 300 億トークン以上を処理し、5000 RPM クラスの高並列に対応しています。残高課金、初回チャージボーナス、組み合わせサブスクリプション、企業向け請求書発行、専任サポートを提供。こちらのリンクから登録すると $2 のクレジット、公式グループへの参加でさらに $10、最大 $12 の無料クレジットがもらえます!
感谢火山方舟Agent Plan 模型赞助了本项目!方舟Agent Plan 模型订阅套餐集成了包含Doubao-Seed、Doubao-Seedance、Doubao-Seedream等在内的字节跳动自研SOTA级模型,覆盖文本、代码、图像、视频等多模态任务。同时支持一站式接入DeepSeek V4、GLM 5.1等主流大模型。超全模态模型与 Harness 升级一步到位,深度支持 Agent 框架与 AI 编程工具。方舟 Agent Plan 为 CC Switch 的用户提供了专属福利:通过此链接订阅方舟AgentPlan,新客户首月40元起!>>For developers outside Mainland China, please click here
+
+
感谢火山方舟 Agent Plan 模型赞助了本项目!方舟 Agent Plan 模型订阅套餐集成了包含 Doubao-Seed、Doubao-Seedance、Doubao-Seedream 等在内的字节跳动自研 SOTA 级模型,覆盖文本、代码、图像、视频等多模态任务。最新支持 MiniMax-M3、DeepSeek-V4 系列、GLM-5.1、Doubao-Seed-2.0 系列、Kimi-K2.6 等模型,工具不限。超全模态模型与 Harness 升级一步到位,深度支持 Agent 框架与 AI 编程工具。一次订阅,可以为不同任务切换合适的 AI 引擎。方舟 Coding Plan 为 CC Switch 的用户提供了专属福利:通过此链接订阅方舟 Coding Plan,新客户首两个月享 2.5 折优惠,再用专属邀请码 6J6FV5N2 领取奖励叠加 9.5 折,低至 9.4 元/月!>>For developers outside Mainland China, please click here
Atlas Cloud 是一个全模态 AI 推理平台,通过单一 API 为开发者提供视频生成、图像生成及 LLM 接入。免去繁琐的多供应商对接,一次连接即可调用 300+ 款全模态精选模型。立即查看 Atlas Cloud 全新“编程计划”优惠,获取更具性价比的 API 接入!
+
+
+
感谢 CCSub 赞助本项目!CCSub 是稳定、实惠的 AI API 中转平台,是 Claude Code 官方订阅的超强平替。一个 API Key 即可调用 Claude Opus 4.8、Sonnet 4.6、Haiku 4.5、GPT-5、Gemini、DeepSeek 全系列模型,价格约为官方直连的 1/3,全球直连无需梯子。兼容 Claude Code、Codex、Cursor、Cline、Continue、Windsurf 等所有主流 AI 编程工具。通过此链接注册即送 $5 体验额度!
+
diff --git a/assets/partners/banners/fable5.png b/assets/partners/banners/fable5.png
new file mode 100644
index 000000000..a27b82ea3
Binary files /dev/null and b/assets/partners/banners/fable5.png differ
diff --git a/assets/partners/logos/ccsub.jpg b/assets/partners/logos/ccsub.jpg
new file mode 100644
index 000000000..92fae2452
Binary files /dev/null and b/assets/partners/logos/ccsub.jpg differ
diff --git a/assets/partners/logos/lemondata.png b/assets/partners/logos/lemondata.png
deleted file mode 100644
index b645b4b14..000000000
Binary files a/assets/partners/logos/lemondata.png and /dev/null differ
diff --git a/assets/partners/logos/unity2.jpg b/assets/partners/logos/unity2.jpg
new file mode 100644
index 000000000..ec3b05740
Binary files /dev/null and b/assets/partners/logos/unity2.jpg differ
diff --git a/cc-switch-main/src/config/universalProviderPresets.ts b/cc-switch-main/src/config/universalProviderPresets.ts
deleted file mode 100644
index e2f9cd04b..000000000
--- a/cc-switch-main/src/config/universalProviderPresets.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-/**
- * 统一供应商(Universal Provider)预设配置
- *
- * 统一供应商是跨应用共享的配置,修改后会自动同步到 Claude、Codex、Gemini 三个应用。
- * 适用于 NewAPI 等支持多种协议的 API 网关。
- */
-
-import type {
- UniversalProvider,
- UniversalProviderApps,
- UniversalProviderModels,
-} from "@/types";
-
-/**
- * 统一供应商预设接口
- */
-export interface UniversalProviderPreset {
- /** 预设名称 */
- name: string;
- /** 供应商类型标识 */
- providerType: string;
- /** 默认启用的应用 */
- defaultApps: UniversalProviderApps;
- /** 默认模型配置 */
- defaultModels: UniversalProviderModels;
- /** 网站链接 */
- websiteUrl?: string;
- /** 图标名称 */
- icon?: string;
- /** 图标颜色 */
- iconColor?: string;
- /** 描述 */
- description?: string;
- /** 是否为自定义模板(允许用户完全自定义) */
- isCustomTemplate?: boolean;
-}
-
-/**
- * NewAPI 默认模型配置
- */
-const NEWAPI_DEFAULT_MODELS: UniversalProviderModels = {
- claude: {
- model: "claude-sonnet-4-20250514",
- haikuModel: "claude-haiku-4-20250514",
- sonnetModel: "claude-sonnet-4-20250514",
- opusModel: "claude-sonnet-4-20250514",
- },
- codex: {
- model: "gpt-4o",
- reasoningEffort: "high",
- },
- gemini: {
- model: "gemini-2.5-pro",
- },
-};
-
-const N1N_DEFAULT_MODELS: UniversalProviderModels = {
- claude: {
- model: "claude-3-5-sonnet-20240620",
- haikuModel: "claude-3-haiku-20240307",
- sonnetModel: "claude-3-5-sonnet-20240620",
- opusModel: "claude-3-opus-20240229",
- },
- codex: {
- model: "gpt-4o",
- reasoningEffort: "high",
- },
- gemini: {
- model: "gemini-1.5-pro-latest",
- },
-};
-
-/**
- * 统一供应商预设列表
- */
-export const universalProviderPresets: UniversalProviderPreset[] = [
- {
- name: "n1n.ai",
- providerType: "n1n",
- defaultApps: {
- claude: true,
- codex: true,
- gemini: true,
- },
- defaultModels: N1N_DEFAULT_MODELS,
- websiteUrl: "https://n1n.ai",
- icon: "openai",
- iconColor: "#000000",
- description:
- "n1n.ai - 聚合 OpenAI, Anthropic, Google 等主流大模型的一站式 AI 服务平台",
- },
- {
- name: "NewAPI",
- providerType: "newapi",
- defaultApps: {
- claude: true,
- codex: true,
- gemini: true,
- },
- defaultModels: NEWAPI_DEFAULT_MODELS,
- websiteUrl: "https://www.newapi.pro",
- icon: "newapi",
- iconColor: "#00A67E",
- description:
- "NewAPI 是一个可自部署的 API 网关,支持 Anthropic、OpenAI、Gemini 等多种协议",
- },
- {
- name: "自定义网关",
- providerType: "custom_gateway",
- defaultApps: {
- claude: true,
- codex: true,
- gemini: true,
- },
- defaultModels: NEWAPI_DEFAULT_MODELS,
- icon: "openai",
- iconColor: "#6366F1",
- description: "自定义配置的 API 网关",
- isCustomTemplate: true,
- },
-];
-
-/**
- * 根据预设创建统一供应商
- */
-export function createUniversalProviderFromPreset(
- preset: UniversalProviderPreset,
- id: string,
- baseUrl: string,
- apiKey: string,
- customName?: string,
-): UniversalProvider {
- return {
- id,
- name: customName || preset.name,
- providerType: preset.providerType,
- apps: { ...preset.defaultApps },
- baseUrl,
- apiKey,
- models: JSON.parse(JSON.stringify(preset.defaultModels)), // Deep copy
- websiteUrl: preset.websiteUrl,
- icon: preset.icon,
- iconColor: preset.iconColor,
- createdAt: Date.now(),
- };
-}
-
-/**
- * 获取预设的显示名称(用于 UI)
- */
-export function getPresetDisplayName(preset: UniversalProviderPreset): string {
- return preset.name;
-}
-
-/**
- * 根据类型查找预设
- */
-export function findPresetByType(
- providerType: string,
-): UniversalProviderPreset | undefined {
- return universalProviderPresets.find((p) => p.providerType === providerType);
-}
diff --git a/docs/guides/codex-unified-session-history-guide-en.md b/docs/guides/codex-unified-session-history-guide-en.md
new file mode 100644
index 000000000..0d0e37122
--- /dev/null
+++ b/docs/guides/codex-unified-session-history-guide-en.md
@@ -0,0 +1,467 @@
+# Unified Codex Session History: Feature Overview and Usage Guide (CC Switch)
+
+> Applies to CC Switch v3.16.x and later. This guide is based on the current code; every command and path can be verified by hand. Examples use de-identified data and contain no real session content or API keys.
+
+## What this feature is
+
+"Unified Codex session history" is a switch that CC Switch v3.16.x adds for Codex. You'll find it under **Settings -> General -> the "Codex App Enhancements" group** ("Codex App Enhancements" is the group title; the switch itself is called "Unified Codex session history"). Once enabled, **sessions from your official subscription (ChatGPT login / OpenAI API key) appear in the same history / resume list as sessions from every third-party provider CC Switch manages**—they are no longer split into two lists that can't see each other.
+
+## What problem it solves
+
+Codex classifies sessions by a "provider tag" (a field called `model_provider`), and **the resume / history list only shows sessions whose tag matches your currently active provider**. As a result, sessions are naturally sorted into two separate "drawers":
+
+- Sessions from your official subscription go under Codex's built-in **`openai`** tag;
+- Every third-party provider CC Switch manages goes under the **`custom`** tag.
+
+The two drawers can't see each other. If you **switch frequently between official and third-party**, you'll hit this kind of fragmentation: "the session I was just chatting in with the official account disappeared from the history list after I switched to a third-party provider"—it isn't actually gone, it's just been sorted into the other drawer. This split both makes it easy to believe a session was lost, and makes it inconvenient to review and resume all your sessions in one place.
+
+**This switch exists to eliminate that fragmentation**: it makes the official subscription run under the `custom` tag too, so official and third-party sessions merge into one list and everything is easy to find and resume in a single place.
+
+> ✅ **One important premise that runs through this whole guide, please remember it first**: this feature (unify / migrate / restore) **only ever rewrites that one classification tag `model_provider` in your session records, and it automatically makes a backup of the original file before every rewrite**. It never deletes, clears, or overwrites a single line of your conversations. So whenever this guide later mentions "some sessions are no longer visible," it almost always means "they've been sorted into the other drawer," not "the data is gone." If you're truly worried, jump straight to the [symptom reference table](#i-feel-like-my-sessions-are-gone-symptom-reference-table) and [verify the files are still there by hand](#verify-by-hand-your-session-files-are-still-on-disk-the-most-important-section).
+
+## How it works (one-line version)
+
+Think of it as **two drawers + automatic backup**:
+
+- By default, official sessions live in the `openai` drawer and third-party sessions live in the `custom` drawer, invisible to each other;
+- The switch makes **the official side use the `custom` drawer too**, merging the two drawers into one shared list;
+- You can optionally choose to "move" your **existing official sessions** into the shared drawer as well (this step is called **migration**; it's optional and requires you to opt in by checking a box), and **before anything is moved a backup copy is made first**, so the whole process is **reversible**;
+- **Authentication is completely unaffected**—your official subscription still uses your ChatGPT login and still goes through the official backend; only the session's classification tag changes.
+
+For the full mechanism (what gets injected, why it's reversible, how migration / restore guarantee no data loss) see [The core mental model](#the-core-mental-model-two-drawers--automatic-backup) and the [Advanced mechanism appendix](#advanced-mechanism-appendix-for-users-who-want-to-truly-understand-how-it-works) at the end.
+
+## How to use it (at a glance)
+
+1. **Enable**: Settings -> General -> Codex App Enhancements -> turn on "Unified Codex session history" -> in the dialog decide whether to check "Also migrate existing official session history" (check it if you want your **earlier** official sessions merged into the unified list too; leave it unchecked if you only want unification from now on) -> confirm. See [What happens when you enable it](#what-happens-when-you-enable-it-step-by-step).
+2. **Disable**: turn the same switch off -> in the dialog keep "restore exactly from backup" checked (it's checked by default) -> confirm, and the official sessions you migrated in will be precisely flipped back to the official list. See [What happens when you disable it](#what-happens-when-you-disable-it-step-by-step).
+3. **Feel like a session is gone?** Don't panic—jump to the [symptom reference table](#i-feel-like-my-sessions-are-gone-symptom-reference-table) to locate it by symptom, and use the commands in the [verify by hand](#verify-by-hand-your-session-files-are-still-on-disk-the-most-important-section) section to see for yourself that the files are all there.
+
+---
+
+## The core mental model: two drawers + automatic backup
+
+To understand this feature, you only need to remember two things: **drawers** and **backups**.
+
+### Drawers: how Codex classifies sessions
+
+Every time you start a Codex session, Codex records a tag `model_provider` in the session file header, marking "which provider this session was chatted with." Codex's **resume / history list is filtered precisely by the currently active tag**—it only shows sessions whose tag matches "the provider you're on right now."
+
+- Sessions from your official subscription (ChatGPT login / OpenAI API key) carry the built-in tag **`openai`**.
+- Every third-party provider CC Switch manages uses the tag **`custom`**.
+
+So by default, official sessions and third-party sessions are inherently invisible to each other—they live in two different drawers. This is **Codex's own design**, not CC Switch losing anything.
+
+```text
+Default state (unified switch off):
+ ┌───────────────────────┐ ┌──────────────────────────┐
+ │ openai drawer │ │ custom drawer │
+ │ (official sessions) │ │ (third-party sessions) │
+ └───────────────────────┘ └──────────────────────────┘
+ ▲ ▲
+ visible only while visible only while
+ on the official provider on a third-party provider
+
+ The two drawers can't see each other.
+```
+
+**What the "Unified Codex session history" switch does is make the official subscription run under the `custom` tag too, merging the two drawers into one**, so official and third-party sessions appear in the same resume list. Note: **authentication doesn't change**—your official subscription still uses your ChatGPT login and still goes through the official backend; only the session's "classification tag" changes from `openai` to `custom`.
+
+```text
+After the unified switch is on:
+ ┌──────────────────────────────────────────────┐
+ │ custom shared drawer │
+ │ official sessions + third-party sessions │
+ │ (appear in the same history / resume list) │
+ └──────────────────────────────────────────────┘
+```
+
+### Backups: a copy is made before every tag change
+
+"Merging the drawers" requires changing the tag of some official sessions from `openai` to `custom` (this step is called **migration**, and it's **optional and requires you to opt in**). And **before any rewrite, CC Switch first copies the original file untouched** to here:
+
+```text
+~/.cc-switch/backups/codex-official-history-unify-v1//
+```
+
+This backup is the sole basis for "restore exactly from backup" later. It makes the whole process **reversible**: at any time you can turn off the switch and precisely flip the official sessions you migrated in back to the `openai` drawer.
+
+Remember these two words—**drawer** (a session just gets reclassified) and **backup** (a copy is always made before a change)—and everything that follows will be easy to understand.
+
+---
+
+## What happens when you enable it: step by step
+
+### Step 1: Find the switch
+
+```text
+Settings -> General -> Codex App Enhancements
+```
+
+In the "Codex App Enhancements" block there are two rows of switches; the **second row** (the blue history icon) is the subject of this guide:
+
+> **Unified Codex session history**
+
+Below it is a line of description text (verbatim):
+
+> When enabled, the official subscription runs under the shared "custom" provider id so official and third-party sessions appear in one history list, optionally migrating existing official sessions in (backed up first). When turning it off, the migrated sessions can be restored from backup. Note: resuming an old session across providers may fail because its encrypted_content reasoning can only be decrypted by the backend that created it.
+
+> **Note**: this single line of description already previews three things—sessions will appear in one list, you can optionally migrate them in with an automatic backup, and resuming across providers "may fail." Here, "fail" means **you can't resume / can't generate a new turn**, not "the record is lost." This is exactly the core misunderstanding we'll dig into below.
+
+### Step 2: Flip the switch from off to on -> a confirmation dialog pops up
+
+The moment you flip the switch on, CC Switch **does not save immediately**; instead it first pops up a confirmation dialog. The dialog text reads as follows (verbatim):
+
+- **Title**: Unified Codex session history
+- **Body**:
+
+ > When enabled, the official subscription and third-party providers share one session history list. Note: resuming an old session across providers may fail because its encrypted_content reasoning cannot be decrypted by another backend.
+ >
+ > You can also migrate your existing official session history into the shared list (originals are backed up to ~/.cc-switch/backups first and can be restored when you turn this off).
+
+- **Checkbox**: Also migrate existing official session history
+- **Confirm button**: I understand, enable
+- **Cancel button**: Cancel
+
+**This checkbox is unchecked by default.** This is an important fork in the road:
+
+| Your choice | Effect | Where your data is right now |
+|---|---|---|
+| **Unchecked** (default) | Only switches the tag. **Only official sessions created after enabling** land in the `custom` shared drawer | Your official sessions from **before** enabling keep the `openai` tag, stay exactly where they were, still in `~/.codex/sessions/` |
+| **Checked** | In addition to switching the tag, also migrates your **existing official sessions** from the `openai` drawer into the `custom` drawer | After being **copied to backup**, the old sessions' tag is rewritten to `custom`; the original data is covered by the backup |
+
+> **If you want "my earlier official sessions to appear in the unified list too," you must opt in by checking this box.** Otherwise you'll run into "scenario A" in the reference table below—the old sessions look "gone," when in fact they're just sitting in the original drawer.
+
+Click "Cancel" or click outside the dialog: the switch flips straight back to off and nothing happens.
+Click "I understand, enable": the switch is saved as on, and CC Switch persists the configuration in the background (and runs the migration if you checked it).
+
+### Step 3 (only if you checked migration): how migration runs + data safety
+
+If you check "Also migrate existing official session history," CC Switch runs this procedure on your existing official sessions:
+
+```text
+For each official (openai tag) session file:
+ ① First copy the original file untouched into the backup directory <- data now has its first safety net
+ ② Using "write a temp file -> replace the whole thing" atomic style,
+ change only the model_provider in the session_meta line at the header
+ from "openai" to "custom" <- not a single byte of the conversation body is touched
+ ③ Update the index database state_5.sqlite to switch the tag in the same transaction
+```
+
+- **Backup location**: `~/.cc-switch/backups/codex-official-history-unify-v1//`. Each migration produces one timestamped "generation directory," containing `jsonl/` (session copies), `state/` (index DB copy), and `meta.json` (recording which Codex directory this migration belongs to).
+- **What's changed**: only the value of the single field `model_provider`. Your conversation content, reasoning content, and all body text are **kept exactly as is**.
+- **What's deleted**: **nothing**. The backup is a "copy," the rewrite is an "atomic replacement of the same file," and at no point is any session or index deleted. The file is complete at every moment (either the old content or the new content, never empty or half-written).
+
+After a successful migration, these existing official sessions show up in the unified list. **At this moment your data is**: ① the original copy in the backup directory; ② in the active file, only the classification tag changed, the content intact.
+
+> **Note**: enabling and migration themselves **do not pop a success toast**. Migration runs as a side task on the backend during save; in the UI you'll only see the switch turn on. So "I didn't see a migration-success popup" is normal and does not mean failure.
+
+---
+
+## What happens when you disable it: step by step
+
+### Step 1: Flip the switch from on to off -> probe for backups -> a confirmation dialog pops up
+
+When disabling, CC Switch **first spends a moment probing whether there's a migration backup**, then pops up a confirmation dialog (so the disable dialog has a slight delay, which is normal). The text reads as follows (verbatim):
+
+- **Title**: Turn off unified session history
+- **Body**:
+
+ > After turning this off, the official subscription and third-party providers return to separate history lists. Sessions created while it was on cannot be attributed to a provider, so they stay in the third-party history and the official subscription will not see them.
+
+- **Checkbox** (shown conditionally): Restore the official sessions migrated at enable time back to the official history (exact restore from backup)
+- **Confirm button**: Turn off
+- **Cancel button**: Cancel
+
+> **Key point**: the body says the official subscription **will not see them**—**won't see**, not **delete**. The new sessions you chatted during the unified period are still fully present in the `custom` drawer; after disabling, the official side simply won't see them.
+
+**This restore checkbox is checked by default.** In other words, the default behavior is "restore the official sessions you migrated in back to the official history at the same time you disable." You only need to keep it checked and click "Turn off."
+
+If the checkbox **doesn't appear**, the system has determined there's no backup that needs restoring (either you never checked migration, or no backup was found)—in that case your existing official sessions were never touched, and turning off the switch returns them to the `openai` drawer on their own.
+
+### Step 2: How restore runs (precise flip-back per the backup ledger)
+
+If you keep the box checked and click "Turn off," CC Switch's restore flow goes like this:
+
+```text
+① First copy the current state once more into a separate restore-backup directory
+ ~/.cc-switch/backups/codex-official-history-unify-restore-v1//
+ (restore itself backs up first, so restore won't lose data either)
+② Comb through all migration backup generations, find the session ids "whose tag was originally openai," and assemble a "ledger"
+③ Only for sessions that are [both in the ledger AND currently still custom], change the tag back to "openai"
+```
+
+Note the **dual condition** in step ③—it must be in the ledger (proving it really was migrated from the official side) AND currently still `custom` (showing you haven't manually changed it). Only when both conditions hold does it get flipped back. This guarantees the restore is both precise and free of collateral damage.
+
+**At this moment your data is**: the migrated-back official sessions have their tag changed back to `openai` and reappear in the official list; meanwhile both the migration backup and the restore backup copies are still on disk.
+
+### Step 3: Read the toast, confirm the result
+
+Only the "disable + check restore" path pops a result toast. The toasts you may see (verbatim):
+
+| Toast you see | Meaning |
+|---|---|
+| **Official session history restored from backup ({{files}} session files, {{rows}} index rows)** | Restore succeeded. `{{files}}` / `{{rows}}` show the actual numbers |
+| **No restorable migration backup for the current Codex directory** | Nothing to restore (**does not mean data is lost**, see scenario E in the reference table) |
+| **Unified session history was re-enabled; restore skipped** | You turned the switch back on while restore was queued, so the system deliberately abandoned the restore (see scenario F) |
+| **Failed to restore official session history, please try again** | The restore process errored; just retry, the data is not corrupted |
+| **Save failed, please try again** | The disable save itself failed; in this case **restore is never triggered** and the switch flips back to its original position |
+
+> **A thoughtful safety design**: if the "disable the switch" save fails, CC Switch **never runs the restore**. Otherwise you'd end up in a torn state of "switch still on, but sessions flipped back to the openai bucket." When the save fails, the switch **automatically flips back to its original position**, so you won't be stuck in a fake state of "looks off but didn't actually save."
+
+---
+
+## "I feel like my sessions are gone?" symptom reference table
+
+The six scenarios below are the situations where users most easily believe "sessions are gone." **The truth in every one is: the data is intact, it just moved drawers or is temporarily out of sight.** Use this table to locate your symptom first, then read the detailed explanation below.
+
+| Scenario | What you see | The data truth | One-line fix |
+|---|---|---|---|
+| **A** Didn't check migration | Old official sessions not in the unified list | All present, still carry the `openai` tag | Re-enable and check migration, or turn off the switch |
+| **B** Cross-provider resume fails | Can't resume / errors out | Files intact, the ciphertext just can't be decrypted across backends | Resume on the original provider; to only read content, read the jsonl directly |
+| **C** Proxy takeover / injection refused | No migration and no restore | Migration was safely skipped, files untouched | Exit takeover -> restart and retry; or just turn off the switch |
+| **D** New sessions didn't return to official after restore | New sessions from the unified period aren't on the official side | They're in the `custom` drawer, untouched by design | Switch to a third-party provider to see them |
+| **E** Toast "no restorable backup" | Restore "failed" | Usually nothing was ever migrated, sessions are in the original drawer | Turn off the switch and the official sessions reappear automatically |
+| **F** Toast "switch was re-enabled, restore skipped" | Restore refused | Prevents a torn data state, nothing was changed | Fully turn off the switch first, then restore |
+
+### Scenario A: You enabled the switch but didn't check migration -> old official sessions "disappear"
+
+**Symptom**: you turned on the unified switch, but didn't check "Also migrate existing official session history" in the enable dialog (it's unchecked by default). After enabling, your earlier official sessions seem to be gone from the list.
+
+**The truth**: 100% of your data is present, not a single line moved. The switch only takes effect on official sessions "created after enabling"; your official sessions from **before** enabling still carry the `openai` tag and sit untouched in `~/.codex/sessions/`. You're now on the `custom` drawer, so naturally you can't see the old sessions left in the `openai` drawer—that's the entire reason for the "apparent disappearance."
+
+**What to do** (pick either):
+1. **Re-enable the switch and check "Also migrate existing official session history,"** which moves the old sessions to the `custom` drawer and they immediately appear in the unified list (automatic backup before the rewrite).
+2. **Or simply turn off the unified switch**, the official side runs on the `openai` drawer again, and the old sessions reappear right where they were.
+
+### Scenario B: Cross-provider resume of an old session fails -> you think "this session is broken / gone"
+
+**Symptom**: after unification, the list shows an old session chatted with "another provider." You switch to your current provider and click "Resume," but it errors out or can't connect.
+
+**The truth**: the session file is intact; what's lost is not data, it's "cross-backend decryption ability." A Codex session stores an encrypted block of reasoning content `encrypted_content`, and **this ciphertext can only be decrypted by the backend that originally generated it**. Using provider B to resume a session generated by provider A means B can't decrypt A's ciphertext -> resume fails. This is **a design limitation of upstream Codex (by design)** and has nothing to do with whether CC Switch touched the file. The text content of the session is readable at any time.
+
+> This is the **only "looks like a real problem" genuine exception** in this whole guide—but note: it just means **you can't resume (can't generate a new turn)**, and **the original file is still fully present**, the conversation text readable at any time.
+
+**What to do**:
+- **Resume with "the provider that originally created this session,"** so it can decrypt normally and connect.
+- Just want to read the history without continuing? Read that session's `.jsonl` file directly (commands at the end).
+- Rule of thumb: **cross-provider is better suited to "starting a new session"; resume old sessions on their original provider whenever possible.**
+
+### Scenario C: You enabled the switch and checked migration, but migration was silently skipped -> you think "migration lost the sessions"
+
+**Symptom**: you enabled the switch and checked migration, but the old official sessions neither entered the unified list nor could be restored when you turned the switch off (or the restore checkbox didn't even appear in the disable dialog, see scenario E). You suspect migration lost the sessions during the process.
+
+**The truth**: migration **never ran**, so it couldn't have lost anything—not a single character of your sessions was changed. CC Switch has a safety gate before migration: it checks whether Codex's live config (`~/.codex/config.toml`) is **actually** routed to the shared `custom` drawer right now, and only migrates if the routing truly went there. The following two situations are judged "not yet unified" (internal reason code `live_not_unified`), so CC Switch **deliberately skips the migration, preserves your switch and migration intent, and migrates later once the conditions are met**:
+
+- **During proxy takeover**: CC Switch's proxy has taken over the live config, and the live config during takeover doesn't carry the unified routing marker.
+- **Injection refused**: your `config.toml` already has a manually specified `model_provider`, or there's already a differently-shaped `[model_providers.custom]` table (possibly with a third-party address). To avoid incorrectly routing official traffic to a third-party backend, CC Switch would rather not inject and not migrate.
+
+Skipping migration = touching no session files. **No migration means nothing moved, so there's nothing to lose.** This is "safe deferral," not "failure with data loss."
+
+**What to do**:
+- Exit proxy takeover -> **restart CC Switch**: on startup it automatically retries migration (your migration intent is preserved the whole time).
+- Check `~/.codex/config.toml`: if there's a conflicting route you wrote by hand, clean up the conflict before enabling the switch.
+- If you'd rather not bother: just turn off the switch, the official sessions still display normally on the `openai` drawer, completely intact.
+
+### Scenario D: You turned off the switch and restored, but "the new sessions chatted during the unified period" didn't return to official -> you think "the new sessions are gone"
+
+**Symptom**: during the unified period, you chatted a few more new sessions with the official account. Later you turned off the switch, checked restore, and after restoring you find those new sessions didn't return to the official drawer.
+
+**The truth**: this is **intentional** design; the new sessions are perfectly fine in the `custom` drawer, visible and resumable. Restore is based on "the backup ledger from migration time"—**only sessions that were originally migrated in from the `openai` drawer** are recorded in the backup and get precisely flipped back to `openai`. The sessions you **created during the unified period** are in no backup ledger; and after unification both official and third-party use the `custom` tag, so **CC Switch can't tell whether a new session was chatted with the official account or a third-party**. To avoid wrongly stuffing third-party sessions into the official history, the product decision is: these new sessions all stay in the `custom` (third-party) history and are never moved automatically. The disable dialog's text says this explicitly too—"Sessions created while it was on cannot be attributed to a provider, so they stay in the third-party history."
+
+**What to do**:
+- Switch to any third-party provider (the `custom` drawer) to see these sessions in the history list.
+- To read content, read the `.jsonl` directly; to resume, follow scenario B's rule (go back to the backend that originally generated it).
+- If you really want to manually return **one specific** session to official: there's currently no automatic button (deliberately omitted, to avoid misjudging the direction). Advanced users can, **after backing up** that file first, manually change `model_provider` in the `session_meta` of the first line of its `.jsonl` from `custom` back to `openai` (an advanced operation; always make a copy before editing).
+
+### Scenario E: Restore toast "No restorable migration backup for the current Codex directory" -> you think "restore failed = data is gone"
+
+**Symptom**: you checked restore when turning off the switch, and got the toast "No restorable migration backup for the current Codex directory." You panic: restore failed, is the data completely gone?
+
+**The truth**: "nothing to restore" ≠ "data is lost." On the contrary, it's usually because **there was no migration that needed restoring**. Common reasons:
+
+- **You never checked "migrate existing official sessions" in the first place**: with no migration, there's naturally no migration backup and no sessions to flip back. Your old official sessions have been in the `openai` drawer all along and reappear after you turn off the switch (same as scenario A). (In this case, the disable dialog may **not even show the restore checkbox**—because the system can't find any backup.)
+- **You've already restored once**: the session tags have all been flipped back to `openai`, so clicking again naturally finds "no targets still in custom to restore"—this is **idempotent protection, not failure**.
+- **You switched Codex directories**: restore only recognizes the backup ledger belonging to the **current** directory; switch directories and it can't find the old directory's ledger. Just switch the directory back.
+
+In all three cases, no session was deleted.
+
+**What to do**: use the end-of-guide commands to count the total session files in `~/.codex/sessions/` and confirm the files are all there; then check whether `~/.cc-switch/backups/` contains a `codex-official-history-unify-v1` directory—if even this directory is absent, you never triggered a migration and the sessions have been in their original drawer all along.
+
+### Scenario F: Restore refused, toast "Unified session history was re-enabled; restore skipped"
+
+**Symptom**: you turned off the switch -> checked restore -> but you were quick and immediately turned the switch back on, then saw the toast "Unified session history was re-enabled; restore skipped."
+
+**The truth**: this is a safeguard against putting your data into a "torn" state, and again no sessions are lost. The restore action is "flip session tags from `custom` back to `openai`," but if the switch is on again at this moment, the live config is routing to `custom`—flipping history back to `openai` on one side while new sessions land in `custom` on the other would artificially tear sessions in two. So when CC Switch detects "the switch is on again," it **deliberately abandons this restore and changes nothing**. Sessions stay as they are, with no deletion or corruption.
+
+**What to do**: to truly restore, **turn the switch off and keep it off** (don't immediately turn it back on), then do disable + check restore; to keep things unified, don't restore, and let the sessions stay in the `custom` shared drawer for normal use.
+
+**The overriding principle: CC Switch's unify / migrate / restore only ever changes a single tag field in a session, and automatically backs up before every rewrite. It never deletes your conversations. Out of sight ≠ gone—look in the other drawer, or use the commands below to confirm with your own eyes.**
+
+---
+
+## Verify by hand: your session files are still on disk (the most important section)
+
+No amount of text beats seeing it for yourself. Below are the **real paths** (taken from the CC Switch source) and how to view session files and backup directories on different systems. **The whole process is read-only and changes nothing; you're strongly encouraged to try it by hand.**
+
+### The simplest way: open it directly in a file manager (no command line at all)
+
+- **macOS (Finder)**: press `Cmd + Shift + G`, paste `~/.codex/sessions` and hit Enter to see a pile of `.jsonl` session files and their modification times; for the backup directory paste `~/.cc-switch/backups`.
+- **Windows (File Explorer)**: paste `%USERPROFILE%\.codex\sessions` into the address bar and hit Enter to see the session folders and the `.jsonl` files inside; for the backup directory paste `%USERPROFILE%\.cc-switch\backups`.
+
+**As long as you can see a batch of `.jsonl` files here, that proves your session data is intact on disk.** The file count and modification times are more intuitive than any amount of text.
+
+### Where exactly your session / history files live
+
+| Content | Real path | Notes |
+|---|---|---|
+| **Session body (the core)** | `~/.codex/sessions/` (includes date-based subdirectories, recursive) | One `.jsonl` text file per session—**this is your conversation content** |
+| **Archived sessions** | `~/.codex/archived_sessions/` | Also `.jsonl` |
+| **Session index database** | `~/.codex/state_5.sqlite` | The `model_provider` column of the `threads` table is the "drawer tag"—**this is the actual classification source the resume list reads** |
+| **Migration backup** (auto-created when migration is enabled) | `~/.cc-switch/backups/codex-official-history-unify-v1//` | Contains `jsonl/`, `state/`, `meta.json` |
+| **Restore backup** (auto-created when you restore) | `~/.cc-switch/backups/codex-official-history-unify-restore-v1//` | A safety copy taken before restore |
+
+> **Note**: if you've changed the Codex directory in CC Switch, or set `sqlite_home` in `config.toml`, replace `~/.codex` above with your actual directory. Below, `~` = your user home directory.
+
+### macOS / Linux commands
+
+**1. Count the total number of session files (this is the hard evidence of "nothing lost")**
+
+```bash
+# Count the total number of session files -- as long as this number matches your expectation, the data is all there
+find ~/.codex/sessions ~/.codex/archived_sessions -name '*.jsonl' 2>/dev/null | wc -l
+
+# Show the 10 most recently modified session files
+find ~/.codex/sessions -name '*.jsonl' 2>/dev/null -print0 \
+ | xargs -0 ls -lt 2>/dev/null | head -10
+```
+
+**2. (Auxiliary) See how many sessions are in each "drawer"**
+
+```bash
+# Number of session files in the official drawer (openai)
+grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"openai"' ~/.codex/sessions 2>/dev/null | wc -l
+
+# Number of session files in the unified drawer (custom)
+grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"custom"' ~/.codex/sessions 2>/dev/null | wc -l
+
+# See the tag distribution at a glance
+grep -rhoE '"model_provider"[[:space:]]*:[[:space:]]*"[^"]*"' ~/.codex/sessions 2>/dev/null | sort | uniq -c
+```
+
+> **Important note, don't let this step scare you**: **early versions of Codex did not write the `model_provider` field into the `.jsonl`**, so these old official sessions **can't be counted** by the grep above—but they're still classified as `openai` in the index database `state_5.sqlite` and still show up in the resume list. So **judge "nothing lost" by the total file count from step 1**—the per-drawer grep is only there to help you understand the classification, and counting fewer than the total file count is **completely normal** and never means "a batch was lost."
+
+**3. (Advanced) Query the index database `state_5.sqlite`—the classification the resume list actually reads**
+
+```bash
+# Requires sqlite3 to be installed; skip if you don't have it
+sqlite3 ~/.codex/state_5.sqlite \
+ "SELECT COALESCE(model_provider,''), COUNT(*) FROM threads GROUP BY 1;"
+```
+
+> This `threads` table is the actual classification source Codex's resume list reads; the `openai` row count ≈ the number of sessions you can see in your official drawer. It may not match step 2's jsonl grep—the reason is exactly what's described above: "old sessions don't write the jsonl field, but they're still openai in the index database." A mismatch between the two is not an anomaly.
+
+**4. Read the content of a specific session directly (confirm the conversation text is still there)**
+
+```bash
+# Replace with one of the .jsonl paths listed by ls above
+python3 -m json.tool < ".jsonl" 2>/dev/null | head -50
+
+# Or just open it in an editor (plain text)
+open -e ".jsonl" # macOS
+```
+
+**5. Look at CC Switch's backup directory (proof that a copy was kept before migration / restore)**
+
+```bash
+ls -la ~/.cc-switch/backups/codex-official-history-unify-v1/ 2>/dev/null
+ls -la ~/.cc-switch/backups/codex-official-history-unify-restore-v1/ 2>/dev/null
+```
+
+### Windows commands (PowerShell)
+
+The session directory is usually at `C:\Users\\.codex\`, and backups at `C:\Users\\.cc-switch\backups\`.
+
+```powershell
+# 1. Total number of session files (hard evidence of "nothing lost")
+(Get-ChildItem "$env:USERPROFILE\.codex\sessions","$env:USERPROFILE\.codex\archived_sessions" -Recurse -Filter *.jsonl -ErrorAction SilentlyContinue).Count
+
+# 2. The 10 most recently modified sessions
+Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
+ Sort-Object LastWriteTime -Descending | Select-Object -First 10 FullName,LastWriteTime
+
+# 3. (Auxiliary) How many session files in the official (openai) / unified (custom) drawers
+(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
+ Select-String -Pattern 'model_provider"\s*:\s*"openai"' -List).Count
+(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
+ Select-String -Pattern 'model_provider"\s*:\s*"custom"' -List).Count
+
+# 4. Look at the backup directories
+Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-v1" -ErrorAction SilentlyContinue
+Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-restore-v1" -ErrorAction SilentlyContinue
+```
+
+> Same reminder: the step-3 grep counting **fewer** than the total file count is normal (old sessions don't write that field); judge "nothing lost" by the **total file count** from step 1.
+
+---
+
+## Advanced mechanism appendix (for users who want to truly understand how it works)
+
+### 1. The bucketing mechanism (the essence of the drawers)
+
+Codex's resume / history list filters by the currently active `model_provider` id with **exact string matching**. The **first line** of a session's `.jsonl` file is a `type:"session_meta"` record whose `payload.model_provider` is the drawer that session belongs to (`grep -rl` counts a file as long as the tag appears once anywhere in it, so no line-by-line parsing is needed; sessions from old versions that didn't write the field can't be counted). What actually drives the resume list is the `threads.model_provider` column of the index database `state_5.sqlite`. When `config.toml` has no explicit `model_provider`, the official subscription falls into the built-in default id `openai`; all of CC Switch's third-party providers uniformly use `custom`.
+
+### 2. What the switch does (injection, lives only in live)
+
+When enabled, CC Switch injects the following into the official live `config.toml`:
+
+```toml
+model_provider = "custom"
+
+[model_providers.custom]
+name = "OpenAI"
+requires_openai_auth = true
+supports_websockets = true
+wire_api = "responses"
+```
+
+Every field has a purpose: `requires_openai_auth = true` keeps authentication going through the ChatGPT login in `auth.json`, with the base_url defaulting back to the official Codex backend; `name = "OpenAI"` lets Codex's official feature gates (web search, remote compaction, etc.) keep matching; `supports_websockets = true` restores the capability that custom entries lose by default; `wire_api = "responses"` uses the official responses protocol. **The net effect is: authentication is unchanged, only the bucket name changed.**
+
+**Key invariant: this injection can only exist in the live `config.toml`, and is never written into the database's stored configuration.** When you switch away from the official provider and write live back to the database, CC Switch strips this injection precisely (it strips only when the shape exactly matches the injected artifact; a third-party-customized `custom` table is kept as is). Precisely because of this, "turning off the switch + switching once" fully restores live, and the database always holds your original clean official configuration—this is the cornerstone of the whole switch's reversibility.
+
+### 3. The two refusal gates for injection (corresponding to scenario C)
+
+- `config.toml` already has an explicit `model_provider` -> don't override the user's route;
+- A differently-shaped `[model_providers.custom]` table already exists (possibly with a third-party `base_url`) -> refuse injection, otherwise ChatGPT OAuth traffic would be routed to the wrong backend.
+
+When injection is refused, live is not unified, and the migration gate (checking whether live's `model_provider` equals `custom` after trim) judges `live_not_unified` -> skip migration, preserve intent, and do it later on the next startup retry. This is "safe deferral," not "failure with data loss."
+
+### 4. The three session classes (which determine the migration / restore boundary)
+
+- **Class A**: existing official sessions migrated in at enable time—the backup is the ledger, and they can be precisely restored back to `openai`;
+- **Class B**: created during the unified period—in no backup, and official / third-party can't be distinguished, so they're **never moved automatically** (stay `custom`);
+- **Class C**: pure third-party history from before enabling—never touched.
+
+### 5. The safety of migration / restore (data is never truly deleted; where the guarantee comes from)
+
+Four layers of design jointly guarantee that under **all paths, normal and abnormal**, the original session data is never truly deleted.
+
+- **Only change the field, never the body**: migration / restore only switch the `model_provider` value in session metadata between `openai` and `custom`; conversation content, `response_item`, and `encrypted_content` are all kept exactly as is.
+- **Always copy a backup before a rewrite**: jsonl uses file copy, the state DB uses a full SQLite copy, both stored in a timestamped generation directory. Migration backups live in `codex-official-history-unify-v1/`, restore backups in the separate `codex-official-history-unify-restore-v1/`—the two are kept apart to keep the ledger clean.
+- **Only move, never delete + atomic writes**: all jsonl rewrites go through "temp file + whole-file replacement," and the state DB goes through a transactional `UPDATE`, with no deletion of any session or index at any point. The file is complete at every moment.
+- **Pessimistic skip + idempotent and retryable**: when buckets are inconsistent (`live_not_unified`), it would rather not migrate; a single process lock serializes migration and restore to avoid "startup retry / post-save background task / disable-time restore" concurrently rewriting the same batch of files in both directions; the completion marker is bound to the Codex directory and written conditionally to prevent missed migrations; restore uses the "in the ledger + currently still custom" dual condition to prevent wrong changes. Restore scans the union of all backup generations, so even after many switch cycles it can still restore early-migrated sessions; a repeated restore returns `nothing_to_restore`, which is idempotent protection rather than failure.
+
+### 6. Cross-backend encrypted_content (corresponding to scenario B)
+
+The reasoning ciphertext inside a session can only be decrypted by the backend that generated it; upstream Codex by design does not support cross-backend decryption. This is the root cause of "resume failure" and has nothing to do with file integrity—the session `.jsonl` sits fully on disk and `encrypted_content` is intact too. Switching back to the original provider to resume, or starting a new session, both work fine.
+
+---
+
+## References
+
+- [Keep Codex Remote Control and Official Plugins While Using Third-Party APIs: CC Switch Setup Guide](./codex-official-auth-preservation-guide-en.md)
+- [Using DeepSeek-Style Chat APIs in Codex: CC Switch Local Routing Guide](./codex-deepseek-routing-guide-en.md)
+- The "Codex App Enhancements" section in the CC Switch user manual
+
+---
+
+**One last word for you**: what you see as "sessions disappeared / resume failed" is essentially **the session being moved to another history list (drawer), or the other backend being unable to decrypt the old reasoning content**; the files always sit untouched in `~/.codex/sessions/` (and `state_5.sqlite`). Checking "restore from backup" when you turn off the switch precisely flips the official sessions you migrated in back to the official list; and even if you don't restore, both the original `.jsonl` files and the backup copies under `~/.cc-switch/backups/codex-official-history-unify-*/` are all still there—**the data is never truly lost.**
diff --git a/docs/guides/codex-unified-session-history-guide-ja.md b/docs/guides/codex-unified-session-history-guide-ja.md
new file mode 100644
index 000000000..2505fee37
--- /dev/null
+++ b/docs/guides/codex-unified-session-history-guide-ja.md
@@ -0,0 +1,467 @@
+# Codex セッション履歴の統一: 機能紹介と利用ガイド(CC Switch)
+
+> 対象バージョン: CC Switch v3.16.x 以降。本記事は現在のコードをもとに整理しており、コマンドとパスはご自身で検証できます。例示には匿名化したデータを使用しており、実際のセッション内容や API Key は含まれていません。
+
+## この機能とは何か
+
+「Codex セッション履歴を統一」は、CC Switch v3.16.x が Codex 向けに新しく追加したスイッチです。その場所は **設定 → 一般 → 「Codex アプリ拡張」グループ** の中にあります(「Codex アプリ拡張」はこのグループの見出しで、スイッチ自体は「Codex セッション履歴を統一」という名前です)。オンにすると、**公式サブスクリプション(ChatGPT ログイン / OpenAI API Key)のセッションが、CC Switch で管理するすべてのサードパーティプロバイダーのセッションと同じ履歴 / セッション再開リストに表示されます**——もう、互いに見えない 2 つのリストに分断されることはありません。
+
+## どんな問題を解決するのか
+
+Codex は「プロバイダーのラベル」(`model_provider` というフィールド)でセッションを分類しており、しかも **セッション再開 / 履歴リストには、現在アクティブなプロバイダーと同じラベルのセッションしか表示しません**。そのため、セッションは自然と 2 つの「引き出し」に分けられてしまいます。
+
+- 公式サブスクリプションのセッションは、Codex 内蔵の **`openai`** ラベルに分類されます。
+- CC Switch が管理するすべてのサードパーティプロバイダーは、**`custom`** ラベルに分類されます。
+
+2 つの引き出しは互いに見えません。**公式とサードパーティを頻繁に切り替えている** 場合、この分断に遭遇します——「さっき公式で話したセッションが、サードパーティに切り替えたら履歴リストから消えた」というように。実際にはなくなっておらず、別の引き出しに分けられただけです。この分断は、セッションが失われたと誤解させやすいうえに、すべてのセッションを 1 か所でまとめて振り返ったり再開したりするのにも不便です。
+
+**このスイッチは、まさにこの分断を解消するためのものです**。公式サブスクリプションも `custom` ラベルで動作させることで、公式とサードパーティのセッションが同じリストに統合され、探すのも再開するのも 1 か所で済みます。
+
+> ✅ **本記事全体を貫く重要な前提を、まず覚えておいてください**: この機能(統一 / 移行 / 復元)は **常にセッション記録内のあの分類ラベル `model_provider` 1 つだけを書き換え、しかも毎回書き換える前に自動で元ファイルをバックアップします**。あなたの会話を 1 文たりとも削除・消去・上書きすることはありません。ですので、本記事の後半で「あるセッションが見えなくなった」とあっても、そのほとんどは「別の引き出しに分けられた」だけであり、「データが消えた」わけではありません——本当に心配なときは、[症状対照表](#会話が消えた症状対照表) と [自分の目でファイルが残っていることを確認する](#自分の目で確認-セッションファイルはディスク上に残っている最重要セクション) を直接ご覧ください。
+
+## 動作原理(一言版)
+
+これを **2 つの引き出し + 自動バックアップ** と考えてください。
+
+- デフォルトでは、公式セッションは `openai` の引き出しに、サードパーティのセッションは `custom` の引き出しにあり、互いに見えません。
+- スイッチは **公式も `custom` の引き出しを使うように** させ、2 つの引き出しを 1 つの共有リストに統合します。
+- **既存の公式の古いセッション** も一緒に共有の引き出しへ「移す」ことを選べます(この操作を **移行** と呼びます。任意で、能動的にチェックを入れる必要があります)。そして **いかなる移動の前にも、まずコピーをバックアップ** するので、プロセス全体が **可逆** です。
+- **認証はまったく影響を受けません**——公式サブスクリプションは引き続きあなたの ChatGPT ログインを使い、引き続き公式バックエンドを経由します。変わるのはセッションの分類ラベルだけです。
+
+完全な仕組み(何が注入されるのか、なぜ可逆なのか、移行 / 復元がどうやってデータ消失を防ぐのか)は、後述の [コア・メンタルモデル](#コアメンタルモデル-2-つの引き出し--自動バックアップ) と巻末の [応用原理付録](#応用原理付録仕組みを本当に理解したい人向け) をご覧ください。
+
+## 使い方(クイック)
+
+1. **有効化**: 設定 → 一般 → Codex アプリ拡張 → 「Codex セッション履歴を統一」をオン → ダイアログで「既存の公式セッション履歴も移行する」にチェックを入れるか決める(**以前** の公式セッションも統一リストに合流させたいならチェックを入れる。今後だけ統一したいならチェックを入れない)→ 確定。詳しくは [有効化したとき何が起きるか](#有効化したとき何が起きるか-ステップ別解説) を参照。
+2. **無効化**: 同じスイッチをオフにする → ダイアログで「バックアップから正確に復元する」のチェックを保持(デフォルトでチェック済み)→ 確定すれば、移行した公式セッションを正確に公式リストへ戻せます。詳しくは [無効化したとき何が起きるか](#無効化したとき何が起きるか-ステップ別解説) を参照。
+3. **セッションが消えた気がする?** 慌てずに [症状対照表](#会話が消えた症状対照表) へ進んで症状から原因を特定し、[自分の目で確認](#自分の目で確認-セッションファイルはディスク上に残っている最重要セクション) セクションのコマンドで、ファイルがすべて残っていることを自分の目で確かめてください。
+
+---
+
+## コア・メンタルモデル: 2 つの引き出し + 自動バックアップ
+
+この機能を理解するには、**引き出し** と **バックアップ** の 2 つだけ覚えれば十分です。
+
+### 引き出し: Codex はどうやってセッションを分類するか
+
+Codex セッションを 1 つ開くたびに、Codex はセッションファイルの先頭に `model_provider` というラベルを記録し、「このセッションはどのプロバイダーで話したか」を示します。Codex の **セッション再開 / 履歴リストは、現在アクティブなこのラベルで正確にフィルタリングされます**——「今あなたが使っているプロバイダー」と同じラベルのセッションだけが表示されます。
+
+- 公式サブスクリプション(ChatGPT ログイン / OpenAI API Key)のセッションのラベルは、内蔵の **`openai`** です。
+- CC Switch が管理するすべてのサードパーティプロバイダーは、一律にラベル **`custom`** を使います。
+
+そのためデフォルトでは、公式セッションとサードパーティセッションは生まれつき互いに見えません——2 つの異なる引き出しにあるからです。これは **Codex 自身の設計** であり、CC Switch が何かをなくしたわけではありません。
+
+```text
+デフォルト状態(統一スイッチをオンにしていない):
+ ┌──────────────────────┐ ┌──────────────────────────────────┐
+ │ openai の引き出し │ │ custom の引き出し │
+ │ (公式セッション) │ │ (サードパーティのセッション) │
+ └──────────────────────┘ └──────────────────────────────────┘
+ ▲ ▲
+ 公式のときは サードパーティのときは
+ こちらだけ表示 こちらだけ表示
+
+ (2 つの引き出しは互いに見えない)
+```
+
+**「Codex セッション履歴を統一」スイッチがすることは、公式サブスクリプションも `custom` ラベルで動作させ、2 つの引き出しを 1 つに統合することです**。その結果、公式セッションとサードパーティセッションが同じセッション再開リストに表示されます。注意してほしいのは、**認証は変わらない** ということです——あなたの公式サブスクリプションは引き続き ChatGPT ログインを使い、引き続き公式バックエンドを経由します。変わるのはセッションの「分類ラベル」が `openai` から `custom` になることだけです。
+
+```text
+統一スイッチをオンにした後:
+ ┌────────────────────────────────────────────────┐
+ │ custom 共有引き出し │
+ │ 公式セッション + サードパーティのセッション │
+ │ (同じ履歴 / 再開リストに表示される) │
+ └────────────────────────────────────────────────┘
+```
+
+### バックアップ: ラベルを変更する前に必ずコピーを取る
+
+「引き出しの統合」では、一部の公式セッションのラベルを `openai` から `custom` に変更する必要があります(この操作を **移行** と呼び、これは **任意で、あなたが能動的にチェックを入れる必要があります**)。そして **どの書き換えの前にも、CC Switch はまず元ファイルをそのままコピー** して、ここに保存します。
+
+```text
+~/.cc-switch/backups/codex-official-history-unify-v1/<時間スタンプ>/
+```
+
+このバックアップが、後の「バックアップから正確に復元する」ための唯一の拠り所です。これによってプロセス全体が **可逆** になります——いつでもスイッチをオフにして、移行した公式セッションを正確に `openai` の引き出しへ戻せます。
+
+この 2 つの言葉——**引き出し**(セッションは分類が変わるだけ)、**バックアップ**(変更前に必ずコピー)——を覚えておけば、以降の内容はすべて簡単に理解できます。
+
+---
+
+## 有効化したとき何が起きるか: ステップ別解説
+
+### Step 1: スイッチを見つける
+
+```text
+設定 → 一般 → Codex アプリ拡張
+```
+
+「Codex アプリ拡張」のセクションには 2 行のスイッチがあり、**2 行目**(青い履歴アイコン)が本ガイドの主役です。
+
+> **Codex セッション履歴を統一**
+
+その下には説明文があります(逐語)。
+
+> オンにすると、公式サブスクリプションも共有の custom プロバイダー ID で動作し、公式とサードパーティのセッションが同じ履歴リストに表示されます。既存の公式セッションの移行も選択できます(移行前に自動バックアップ)。オフにする際はバックアップから復元できます。注意:プロバイダーをまたいで古いセッションを再開すると、encrypted_content の推論内容を相手のバックエンドが復号できず、再開に失敗する場合があります。
+
+> **注意**: この説明文には、すでに 3 つのことが予告されています——同じリストに表示される、移行を選べて自動バックアップされる、プロバイダーをまたいだ再開は「失敗する場合がある」。ここでの「再開に失敗する」は **続けられない、新しいターンを生成できない** という意味であり、「記録が消える」ではありません。これこそ、この後で重点的に解きほぐす核心的な誤解です。
+
+### Step 2: スイッチをオフからオンに切り替える → 確認ダイアログが表示される
+
+スイッチをオンに切り替えると、CC Switch は **すぐには保存せず**、まず確認ダイアログを表示します。ダイアログの文言は次のとおりです(逐語)。
+
+- **タイトル**: Codex セッション履歴を統一
+- **本文**:
+
+ > オンにすると、公式サブスクリプションとサードパーティが同じセッション履歴リストを共有します。注意:プロバイダーをまたいで古いセッションを再開すると、encrypted_content を相手のバックエンドが復号できず失敗する場合があります。
+ >
+ > 既存の公式セッション履歴を共有リストへ移行することもできます(移行前に ~/.cc-switch/backups へ自動バックアップされ、オフにする際に復元を選択できます)。
+
+- **チェックボックス**: 既存の公式セッション履歴も移行する
+- **確認ボタン**: 理解しました、オンにする
+- **キャンセルボタン**: キャンセル
+
+**このチェックボックスはデフォルトでオフです。** これは重要な分岐点です。
+
+| あなたの選択 | 効果 | この時点でデータはどこにあるか |
+|---|---|---|
+| **チェックしない**(デフォルト) | ラベルを切り替えるだけ。**オンにした後に新規作成された公式セッションだけ** が `custom` の共有引き出しに入る | あなたが **オンにする前** の公式の古いセッションは、ラベルが `openai` のまま、その場で動かず、引き続き `~/.codex/sessions/` にある |
+| **チェックする** | ラベルの切り替えに加えて、**既存の公式の古いセッション** も `openai` の引き出しから `custom` の引き出しへ移行する | 古いセッションは **コピーしてバックアップ** された後、ラベルが `custom` に書き換えられる。元データはバックアップで保護される |
+
+> **「以前の公式セッションも統一リストに表示したい」なら、必ずこのチェックボックスを能動的にオンにしてください。** さもないと、下の対照表の「シナリオ A」に遭遇します——古いセッションが「消えた」ように見えますが、実際は元の引き出しに残っているだけです。
+
+「キャンセル」を押すか、ダイアログの外側をクリックすると、スイッチはそのままオフ状態に戻り、何も起きません。
+「理解しました、オンにする」を押すと、スイッチはオンとして保存され、CC Switch はバックグラウンドで設定をディスクに書き込みます(移行にチェックを入れていれば、移行を実行します)。
+
+### Step 3(移行にチェックを入れた場合のみ): 移行はどう実行されるか + データの安全性
+
+「既存の公式セッション履歴も移行する」にチェックを入れた場合、CC Switch はあなたの公式の古いセッションに対して、次の一連の流れを実行します。
+
+```text
+公式(openai ラベル)の各セッションファイルについて:
+ ① まず元ファイルをそのままバックアップディレクトリへコピー ← データの一次保険ができる
+ ② 「一時ファイルに書く → まるごと置換」という原子的な方法で、
+ 先頭行 session_meta 内の model_provider を
+ "openai" から "custom" へ変更するだけ ← 会話本文は 1 バイトも触らない
+ ③ インデックス DB state_5.sqlite も同じトランザクション内でラベルを変更
+```
+
+- **バックアップの場所**: `~/.cc-switch/backups/codex-official-history-unify-v1/<時間スタンプ>/`。移行のたびに、タイムスタンプ付きの「世代ディレクトリ」を生成し、その中に `jsonl/`(セッションのコピー)、`state/`(インデックス DB のコピー)、`meta.json`(この移行がどの Codex ディレクトリに属するかの記録)が含まれます。
+- **変更するもの**: `model_provider` というフィールドの値だけ。あなたの会話内容、推論内容、すべての本文は **そのまま保持** されます。
+- **削除するもの**: **何も削除しません**。バックアップは「コピー」、書き換えは「同一ファイルの原子的な置換」であり、全工程でセッションやインデックスを削除する操作は一切ありません。ファイルはいかなる時点でも完全です(古い内容か新しい内容かのどちらかであり、空や中途半端になることは決してありません)。
+
+移行が成功すると、これらの公式の古いセッションが統一リストに表示されます。**この時点でのあなたのデータ**: ① 元のコピーがバックアップディレクトリにある。② アクティブファイルは分類ラベルが変わっただけで、内容は無傷。
+
+> **注意**: 有効化と移行そのものは **成功通知を表示しません**。移行は保存時にバックエンドが付随的に実行するもので、UI 上ではスイッチがオン状態になったのが見えるだけです。ですので「移行成功のダイアログが見えなかった」のは正常であり、失敗を意味しません。
+
+---
+
+## 無効化したとき何が起きるか: ステップ別解説
+
+### Step 1: スイッチをオンからオフに切り替える → バックアップを探索 → 確認ダイアログが表示される
+
+無効化のとき、CC Switch はまず **一瞬かけて移行バックアップの有無を探索** し、それから確認ダイアログを表示します(そのため無効化のダイアログは少しだけ遅延しますが、これは正常です)。文言は次のとおりです(逐語)。
+
+- **タイトル**: セッション履歴の統一をオフにする
+- **本文**:
+
+ > オフにすると、公式サブスクリプションとサードパーティはそれぞれ独立した履歴リストに戻ります。オン期間中に作成されたセッションは提供元を判別できないため、サードパーティの履歴に残り、公式サブスクリプションからは見えなくなります。
+
+- **チェックボックス**(条件付き表示): オンにした際に移行した公式セッションを公式履歴へ復元する(バックアップから正確に復元)
+- **確認ボタン**: オフにする
+- **キャンセルボタン**: キャンセル
+
+> **ポイント**: 本文が言っているのは「公式サブスクリプションからは **見えなくなる**」——**見えなくなる** であり、**削除される** ではありません。オン期間中に新たに話したセッションは、引き続き `custom` の引き出しに完全な形で残っており、オフにした後で公式側から見えなくなるだけです。
+
+**この復元チェックボックスはデフォルトでオンです。** つまりデフォルトの動作は「オフにすると同時に、移行した公式セッションを公式履歴へ正確に復元する」です。チェックを保持したまま「オフにする」を押すだけで構いません。
+
+チェックボックスが **表示されない** 場合は、復元が必要なバックアップがないとシステムが判断したことを意味します(移行に一度もチェックを入れていない、またはバックアップを探索できない)——この場合、あなたの公式の古いセッションは一度も変更されていないので、スイッチをオフにすれば自然と `openai` の引き出しに戻ります。
+
+### Step 2: 復元はどう実行されるか(バックアップ台帳に従って正確に戻す)
+
+チェックを保持して「オフにする」を押すと、CC Switch の復元フローは次のようになります。
+
+```text
+① まず現在の状態を独立した復元バックアップディレクトリへもう一度コピー
+ ~/.cc-switch/backups/codex-official-history-unify-restore-v1/<時間スタンプ>/
+ (復元自体もまずバックアップするので、復元でもデータは失われない)
+② すべての移行バックアップ世代を走査し、「当初のラベルが openai」のセッション id を集めて「台帳」を作る
+③ 【台帳に含まれ、かつ現在もまだ custom】のセッションだけ、ラベルを "openai" に戻す
+```
+
+③ のステップの **二重条件** に注意してください——台帳に含まれていること(当初確かに公式から移行されたものだと証明できる)に加えて、現在もまだ `custom` であること(あなたが手動で変更していないことを示す)。両方の条件を満たして初めて戻します。これにより、復元は正確であり、かつ誤って手を加えることもありません。
+
+**この時点でのあなたのデータ**: 戻された公式セッションはラベルが `openai` に変わり、再び公式リストに表示されます。同時に、移行バックアップと復元バックアップの 2 つのコピーがどちらもディスク上に残っています。
+
+### Step 3: 通知を見て、結果を確認する
+
+「オフにする + 復元にチェック」というパスだけが結果通知を表示します。表示され得る通知(逐語)。
+
+| 表示される通知 | 意味 |
+|---|---|
+| **バックアップから公式セッション履歴を復元しました(セッションファイル {{files}} 件、インデックス {{rows}} 行)** | 復元成功。`{{files}}` / `{{rows}}` の部分には実際の数字が表示される |
+| **現在の Codex ディレクトリに復元可能な移行バックアップはありません** | 復元できる内容がない(**データが消えたわけではない**。対照表シナリオ E を参照) |
+| **統一セッション履歴が再度有効化されたため、復元をスキップしました** | 復元のキュー待ち中にスイッチを再びオンにしたため、システムが復元を自発的に取りやめた(対照表シナリオ F を参照) |
+| **公式セッション履歴の復元に失敗しました。もう一度お試しください** | 復元の途中でエラー。もう一度試せばよく、データは破壊されていない |
+| **保存に失敗しました。もう一度お試しください** | オフにするステップの保存そのものが失敗。この場合 **復元は決して起動されず**、スイッチは元の位置に戻る |
+
+> **気の利いた安全設計**: 「スイッチをオフにする」ステップの保存が失敗した場合、CC Switch は **復元を決して実行しません**。さもないと「スイッチはまだオン、しかしセッションは `openai` バケットに戻された」という矛盾状態が生じてしまいます。保存失敗時、スイッチは **自動で元の位置に戻る** ので、「オフに見えるのに実は保存されていない」という偽の状態に取り残されることはありません。
+
+---
+
+## 「会話が消えた?」症状対照表
+
+以下の 6 つのシナリオは、ユーザーが最も「セッションが消えた」と誤解しやすいケースです。**どれも真相は: データは無傷で、引き出しが変わったか一時的に見えないだけ。** まずこの表で症状から原因を特定し、その後で下の詳細説明を読んでください。
+
+| シナリオ | あなたが見るもの | データの真相 | 一言での解決法 |
+|---|---|---|---|
+| **A** 移行にチェックなし | 公式の古いセッションが統一リストにない | すべて存在、`openai` ラベルのまま | 移行にチェックを入れて再度オンにする、またはスイッチをオフにする |
+| **B** プロバイダーをまたいだ再開が失敗 | 続けられない / エラー | ファイルは無傷、暗号文がバックエンドをまたいで復号できないだけ | 元のプロバイダーで再開する。内容だけ見るなら jsonl を直接読む |
+| **C** プロキシ接管 / 注入が拒否 | 移行も復元もされない | 移行が安全にスキップされ、ファイルは未変更 | 接管を終了 → 再起動して再試行。またはスイッチを直接オフにする |
+| **D** 復元後、新セッションが公式に戻らない | オン期間中の新セッションが公式にない | `custom` の引き出しにある、設計上動かさない | サードパーティプロバイダーに切り替えれば見える |
+| **E** 「復元可能なバックアップなし」と通知 | 復元が「失敗」 | 通常はそもそも移行していない、セッションは元の引き出しにある | スイッチをオフにすれば公式セッションが自動で再表示 |
+| **F** 「スイッチが再度有効化、復元スキップ」と通知 | 復元が拒否 | データの矛盾を防止、何も変更していない | まずスイッチを完全にオフにしてから復元する |
+
+### シナリオ A: スイッチをオンにしたが移行にチェックを入れなかった → 公式の古いセッションが「消えた」
+
+**現象**: 統一スイッチをオンにしたが、有効化ダイアログの「既存の公式セッション履歴も移行する」にチェックを入れなかった(デフォルトでチェックなし)。オンにした後で見ると、以前の公式の古いセッションがすべてリストにないように見える。
+
+**真相**: データは 100% すべて存在し、1 行も動いていません。スイッチは「オンにした後に新規作成された」公式セッションにのみ効きます。あなたが **オンにする前** の公式の古いセッションはラベルが `openai` のままで、そっくりそのまま `~/.codex/sessions/` に横たわっています。今あなたがアクティブにしているのは `custom` の引き出しなので、`openai` の引き出しに残った古いセッションが見えないのは当然です——これが「消えたように見える」理由のすべてです。
+
+**どうするか**(いずれか):
+1. **スイッチを再度オンにするときに「既存の公式セッション履歴も移行する」にチェックを入れ**、古いセッションを `custom` の引き出しへ移せば、すぐに統一リストに表示されます(書き換え前に自動バックアップ)。
+2. **または単に統一スイッチをオフにする** と、公式は再び `openai` の引き出しで動作し、古いセッションがその場で再表示されます。
+
+### シナリオ B: プロバイダーをまたいで古いセッションを再開して失敗 → 「このセッションが壊れた / 消えた」と思う
+
+**現象**: 統一した後、リストに「別のプロバイダー」で話した古いセッションが見える。今のプロバイダーに切り替えて「再開」を押すと、エラーになったり繋がらなかったりする。
+
+**真相**: セッションファイルは完全に無傷で、失われたのはデータではなく「バックエンドをまたいだ復号能力」です。Codex セッションには暗号化された推論内容 `encrypted_content` が保存されており、**この暗号文は、それを生成したバックエンドだけが復号できます**。B プロバイダーで A プロバイダーが生成したセッションを再開しようとすると、B は A の暗号文を解けない → 再開失敗。これは **上流の Codex の設計上の制約(by design)** であり、CC Switch がファイルに手を加えたかどうかとは無関係です。セッション内の文字内容はいつでも読めます。
+
+> これは本記事全体で **唯一「本当に問題が起きたように見える」実在の例外** です——ただし注意してください: これは **再開できない(新しいターンを生成できない)** だけであり、**元ファイルは依然として完全に存在し**、会話の文字はいつでも読めます。
+
+**どうするか**:
+- **「このセッションを最初に作成したプロバイダー」で再開すれば**、正常に復号でき、繋がります。
+- 履歴の内容だけ見たくて、続ける必要がない場合は、そのセッションの `.jsonl` ファイルを直接読んでください(巻末にコマンドあり)。
+- 経験則: **プロバイダーをまたぐ場合は「新規セッションを始める」のが向いており、古いセッションはできるだけ元のプロバイダーで再開してください。**
+
+### シナリオ C: スイッチをオンにし移行にもチェックを入れたが、移行が静かにスキップされた → 「移行がセッションをなくした」と思う
+
+**現象**: オンにして移行にチェックを入れたのに、公式の古いセッションは統一リストに入らず、スイッチをオフにして復元しようとしても「復元できるものがない」と通知される(または無効化ダイアログに復元チェックボックスがそもそも現れない。シナリオ E を参照)。あなたは、移行の過程でセッションをなくしたのではと疑います。
+
+**真相**: 移行はそもそも **実行されていない** ので、なくすことも不可能です——あなたのセッションは 1 文字も変更されていません。CC Switch には移行前に安全ゲートがあります: Codex の live 設定(`~/.codex/config.toml`)が、この時点で **本当に** 共有の `custom` 引き出しへルーティングされているかを確認し、本当にルーティングされている場合だけ移行します。以下の 2 つのケースでは「まだ統一されていない」と判定され(内部の理由コード `live_not_unified`)、**移行を自発的にスキップし、あなたのスイッチと移行の意思は保持し、条件が満たされてから移行します**。
+
+- **プロキシ接管中**: CC Switch のプロキシが live 設定を接管しており、接管中の live には統一ルーティングのマークが付いていません。
+- **注入が拒否された**: あなたの `config.toml` にすでに手動指定の `model_provider` があるか、形態の異なる `[model_providers.custom]` テーブルが既に存在する(サードパーティのアドレスが付いている可能性がある)。公式トラフィックを誤ってサードパーティバックエンドへルーティングするのを避けるため、CC Switch は注入も移行もしないことを選びます。
+
+移行のスキップ = どのセッションファイルにも触れない。**移行していない=動かしていない、消えようがない。** これは「安全な先送り」であり、「失敗してデータが消えた」ではありません。
+
+**どうするか**:
+- プロキシ接管を終了 → **CC Switch を再起動**: 起動時に自動で移行を再試行します(あなたの移行の意思はずっと保持されています)。
+- `~/.codex/config.toml` を確認: 手動で書いた競合するルーティングがあれば、競合を整理してからスイッチをオンにします。
+- どうしても手間をかけたくない場合は、スイッチをオフにすれば、公式セッションは引き続き `openai` の引き出しで正常に表示され、まったく無傷です。
+
+### シナリオ D: スイッチをオフにして復元したが、「オン期間中に新たに話したセッション」が公式に戻らない → 「新セッションが消えた」と思う
+
+**現象**: 統一をオンにしている間、公式でさらにいくつかの新セッションを話した。後でスイッチをオフにし、復元にチェックを入れた。復元が終わると、その数本の新セッションが公式の引き出しに戻っていない。
+
+**真相**: これは **意図的な** 設計で、新セッションはちゃんと `custom` の引き出しにあり、見えるし続けられます。復元の拠り所は「移行時のバックアップ台帳」です——**当初 `openai` の引き出しから移行されてきたセッションだけ** がバックアップに記録されており、正確に `openai` へ戻されます。あなたが **オン期間中に新規作成した** セッションはどのバックアップ台帳にもありません。しかも統一後は公式もサードパーティも `custom` ラベルを使うので、**CC Switch はこの新セッションが公式で話したものかサードパーティで話したものか判別できません**。サードパーティのセッションを公式履歴に誤って押し込まないため、プロダクトの決定として、これらの新セッションは一律に `custom`(サードパーティ)の履歴に残し、決して自動で動かしません。無効化ダイアログの文言もこれを明示しています——「オン期間中に作成されたセッションは提供元を判別できないため、サードパーティの履歴に残ります」。
+
+**どうするか**:
+- 任意のサードパーティプロバイダー(`custom` の引き出し)に切り替えれば、履歴リストでこれらのセッションが見えます。
+- 内容を見たいなら `.jsonl` を直接読み、再開したいならシナリオ B のルール(それを生成した元のバックエンドに戻る)に従ってください。
+- もし **ある 1 本** を手動で公式に戻したい場合: 現在は自動ボタンはありません(方向を誤判定するのを避けるため、あえて作っていません)。上級ユーザーは、そのファイルを **先にバックアップ** したうえで、`.jsonl` の 1 行目 `session_meta` 内の `model_provider` を `custom` から `openai` に手動で戻せます(上級操作です。変更前に必ずコピーを取ってください)。
+
+### シナリオ E: 復元時に「現在の Codex ディレクトリに復元可能な移行バックアップはありません」と通知 → 「復元失敗 = データが消えた」と思う
+
+**現象**: スイッチをオフにするときに復元にチェックを入れたら、「現在の Codex ディレクトリに復元可能な移行バックアップはありません」と通知が出た。あなたは慌てます: 復元すら失敗した、データは完全に消えたのでは?
+
+**真相**: 「復元できるものがない」≠「データが消えた」。むしろ逆で、通常は **そもそも復元すべき移行が存在しない** からです。よくある原因:
+
+- **当初「既存の公式セッションを移行する」にチェックを入れていない**: 移行していない以上、移行バックアップもなく、戻すべきセッションもありません。あなたの公式の古いセッションはずっと `openai` の引き出しにあり、スイッチをオフにすれば直接再表示されます(シナリオ A と同じ)。(この場合、無効化ダイアログは復元チェックボックスを **そもそも表示しない** こともあります——システムがバックアップを一切探索できないためです。)
+- **すでに一度復元済み**: セッションラベルはすべて `openai` に戻っており、もう一度押しても「まだ `custom` の対象がない」のは当然です——これは **冪等保護であり、失敗ではありません**。
+- **Codex ディレクトリを切り替えた**: 復元は **現在の** ディレクトリに属するバックアップ台帳しか認識しないので、ディレクトリを変えると旧ディレクトリの台帳が見つかりません。ディレクトリを戻せば解決します。
+
+この 3 つのケースでは、どのセッションも削除されていません。
+
+**どうするか**: 巻末のコマンドで `~/.codex/sessions/` 内のセッションファイル総数を数え、ファイルがすべて残っていることを確認してください。次に `~/.cc-switch/backups/` に `codex-official-history-unify-v1` ディレクトリがあるかを見てください——もしこのディレクトリすらなければ、あなたは一度も移行を起動しておらず、セッションはずっと元の引き出しにある、ということです。
+
+### シナリオ F: 復元が拒否され、「統一セッション履歴が再度有効化されたため、復元をスキップしました」と通知
+
+**現象**: スイッチをオフにする → 復元にチェック → 手が速くて、すぐにスイッチを再びオンにした。すると「統一セッション履歴が再度有効化されたため、復元をスキップしました」と通知が出た。
+
+**真相**: これはデータを「矛盾」状態にしてしまうのを防ぐ防護であり、セッションは同じく消えていません。復元の動作は「セッションラベルを `custom` から `openai` へ戻す」ことですが、この時点でスイッチが再びオンになっていると、live 設定は `custom` へルーティングしています——一方で履歴を `openai` へ戻し、一方で新セッションを `custom` に落とせば、セッションが人為的に 2 つに引き裂かれてしまいます。そのため CC Switch は「スイッチが再びオンになった」のを検知すると、**この復元を自発的に取りやめ、何も変更しません**。セッションは現状を維持し、削除も破壊もありません。
+
+**どうするか**: 本当に復元したいなら、**まずスイッチを安定してオフにし**(すぐにオンにし直さない)、それから「オフにする + 復元にチェック」を実行してください。統一を保ちたいなら、復元せず、セッションを `custom` の共有引き出しに残して通常どおり使ってください。
+
+**大原則: CC Switch の統一 / 移行 / 復元は、全工程でセッションの 1 つのラベルフィールドだけを変更し、しかも毎回書き換える前に自動でバックアップします。あなたの会話を削除することはありません。見えない ≠ 消えた——別の引き出しを見るか、下のコマンドで自分の目で確かめてください。**
+
+---
+
+## 自分の目で確認: セッションファイルはディスク上に残っている(最重要セクション)
+
+文字をいくら重ねるより、自分の目で見るのが一番です。以下に **実際のパス**(CC Switch のソースコードから取得)と、異なる OS でセッションファイル・バックアップディレクトリを見る方法を示します。**全工程は読み取りのみで変更なし。ぜひ一度ご自身で試してみてください。**
+
+### 最も簡単な方法: ファイルマネージャーで直接開く(コマンドライン完全不要)
+
+- **macOS(Finder)**: `Cmd + Shift + G` を押して `~/.codex/sessions` を貼り付けて Enter すれば、たくさんの `.jsonl` セッションファイルとその更新時刻が見えます。バックアップディレクトリは `~/.cc-switch/backups` を貼り付けます。
+- **Windows(エクスプローラー)**: アドレスバーに `%USERPROFILE%\.codex\sessions` を貼り付けて Enter すれば、セッションフォルダとその中の `.jsonl` が見えます。バックアップディレクトリは `%USERPROFILE%\.cc-switch\backups` を貼り付けます。
+
+**ここで一連の `.jsonl` ファイルが見えれば、それがセッションデータが無傷でディスク上にある証拠です。** ファイル数や更新時刻は、どんな文章よりも直感的です。
+
+### あなたのセッション / 履歴ファイルはどこにあるのか
+
+| 内容 | 実際のパス | 説明 |
+|---|---|---|
+| **セッション本文(コア)** | `~/.codex/sessions/`(日付別サブディレクトリを含む、再帰的) | セッション 1 つにつき 1 つの `.jsonl` テキストファイル。**これがあなたの会話内容** |
+| **アーカイブ済みセッション** | `~/.codex/archived_sessions/` | 同じく `.jsonl` |
+| **セッションインデックス DB** | `~/.codex/state_5.sqlite` | `threads` テーブルの `model_provider` 列が「引き出しラベル」。**これこそ、セッション再開リストが実際に読み取る分類のソース** |
+| **移行バックアップ**(移行をオンにすると自動生成) | `~/.cc-switch/backups/codex-official-history-unify-v1/<時間スタンプ>/` | `jsonl/`、`state/`、`meta.json` を含む |
+| **復元バックアップ**(復元を押すと自動生成) | `~/.cc-switch/backups/codex-official-history-unify-restore-v1/<時間スタンプ>/` | 復元前の安全なコピー |
+
+> **注意**: CC Switch で Codex ディレクトリを変更した場合や、`config.toml` で `sqlite_home` を設定している場合は、上記の `~/.codex` をあなたの実際のディレクトリに置き換えてください。以下の `~` = あなたのユーザーホームディレクトリ。
+
+### macOS / Linux コマンド
+
+**1. セッションファイル総数を数える(これこそ「消えていない」確固たる証拠)**
+
+```bash
+# セッションファイルの総数を数える —— この数が想定どおりなら、データはすべて残っている
+find ~/.codex/sessions ~/.codex/archived_sessions -name '*.jsonl' 2>/dev/null | wc -l
+
+# 最近更新されたセッションファイル上位 10 件を見る
+find ~/.codex/sessions -name '*.jsonl' 2>/dev/null -print0 \
+ | xargs -0 ls -lt 2>/dev/null | head -10
+```
+
+**2. (補助)各「引き出し」にそれぞれ何個のセッションがあるか見る**
+
+```bash
+# 公式の引き出し(openai)のセッションファイル数
+grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"openai"' ~/.codex/sessions 2>/dev/null | wc -l
+
+# 統一の引き出し(custom)のセッションファイル数
+grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"custom"' ~/.codex/sessions 2>/dev/null | wc -l
+
+# 各ラベルの分布をひと目で確認
+grep -rhoE '"model_provider"[[:space:]]*:[[:space:]]*"[^"]*"' ~/.codex/sessions 2>/dev/null | sort | uniq -c
+```
+
+> **重要なヒント、このステップに驚かないでください**: **初期バージョンの Codex は `.jsonl` に `model_provider` フィールドを書き込みません**。これらの古い公式セッションは上記の grep では **数えられません** が、インデックス DB `state_5.sqlite` では依然として `openai` に分類されており、セッション再開リストではちゃんと見えます。ですので **「セッションが消えていない」かの判断はステップ 1 のファイル総数を基準にしてください**——バケット別 grep は分類を理解する補助に過ぎず、数えた結果がファイル総数より少ないのは **まったく正常** であり、決して「ひとまとまり消えた」ことを意味しません。
+
+**3. (応用)インデックス DB `state_5.sqlite` を見る——セッション再開リストが実際に読む分類**
+
+```bash
+# sqlite3 がインストール済みであること;未インストールならスキップ可
+sqlite3 ~/.codex/state_5.sqlite \
+ "SELECT COALESCE(model_provider,'<空>'), COUNT(*) FROM threads GROUP BY 1;"
+```
+
+> この `threads` テーブルこそ、Codex のセッション再開リストが実際に読み取る分類のソースであり、`openai` の行数 ≈ あなたの公式の引き出しで見えるセッション数です。ステップ 2 の jsonl grep とは数が合わないことがあります——その理由は、上述の「古いセッションは jsonl フィールドを書き込まないが、インデックス DB では依然として openai」だからです。両者が合わないのは異常ではありません。
+
+**4. あるセッションの内容を直接読む(会話の文字が残っていることを確認)**
+
+```bash
+# <ファイル名> を、上の ls で表示された .jsonl のパスに置き換える
+python3 -m json.tool < "<ファイル名>.jsonl" 2>/dev/null | head -50
+
+# またはエディタで直接開いて見る(プレーンテキスト)
+open -e "<ファイル名>.jsonl" # macOS
+```
+
+**5. CC Switch のバックアップディレクトリを見る(移行 / 復元の前に必ずコピーを残した証拠)**
+
+```bash
+ls -la ~/.cc-switch/backups/codex-official-history-unify-v1/ 2>/dev/null
+ls -la ~/.cc-switch/backups/codex-official-history-unify-restore-v1/ 2>/dev/null
+```
+
+### Windows コマンド(PowerShell)
+
+セッションディレクトリは通常 `C:\Users\<あなたのユーザー名>\.codex\` にあり、バックアップは `C:\Users\<あなたのユーザー名>\.cc-switch\backups\` にあります。
+
+```powershell
+# 1. セッションファイルの総数(「消えていない」ことの動かぬ証拠)
+(Get-ChildItem "$env:USERPROFILE\.codex\sessions","$env:USERPROFILE\.codex\archived_sessions" -Recurse -Filter *.jsonl -ErrorAction SilentlyContinue).Count
+
+# 2. 最近更新されたセッション上位 10 件
+Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
+ Sort-Object LastWriteTime -Descending | Select-Object -First 10 FullName,LastWriteTime
+
+# 3. (補助)公式(openai) / 統一(custom) の引き出しにそれぞれ何件のセッションファイルがあるか
+(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
+ Select-String -Pattern 'model_provider"\s*:\s*"openai"' -List).Count
+(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
+ Select-String -Pattern 'model_provider"\s*:\s*"custom"' -List).Count
+
+# 4. バックアップディレクトリを見る
+Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-v1" -ErrorAction SilentlyContinue
+Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-restore-v1" -ErrorAction SilentlyContinue
+```
+
+> 同じく注意: ステップ 3 の grep の数がファイル総数より **少なくなる** のは正常です(古いセッションはこのフィールドを書き込まないため)。「セッションが消えていない」の判断は、ステップ 1 の **ファイル総数** を基準にしてください。
+
+---
+
+## 応用原理付録(仕組みを本当に理解したい人向け)
+
+### 1. バケット分け機構(引き出しの本質)
+
+Codex のセッション再開 / 履歴リストは、現在アクティブな `model_provider` id で **厳密な文字列フィルタリング** を行います。セッションファイル `.jsonl` の **1 行目** は `type:"session_meta"` のレコードで、その `payload.model_provider` がそのセッションの属する引き出しです(`grep -rl` はファイル内にそのラベルが 1 回でも出現すればそのファイルをカウントするので、行ごとに解析する必要はありません。旧バージョンでこのフィールドを書き込んでいないセッションは数えられません)。セッション再開リストを実際に駆動するのはインデックス DB `state_5.sqlite` の `threads.model_provider` 列です。公式サブスクリプションは `config.toml` に明示的な `model_provider` がないとき、内蔵のデフォルト id `openai` に入ります。CC Switch のすべてのサードパーティプロバイダーは一律に `custom` を使います。
+
+### 2. スイッチがすること(注入、live にのみ存在)
+
+オンにすると、CC Switch は公式 live `config.toml` に次の内容を注入します。
+
+```toml
+model_provider = "custom"
+
+[model_providers.custom]
+name = "OpenAI"
+requires_openai_auth = true
+supports_websockets = true
+wire_api = "responses"
+```
+
+各フィールドには役割があります。`requires_openai_auth = true` は認証を引き続き `auth.json` 内の ChatGPT ログインで行わせ、base_url 未指定時は公式 Codex バックエンドへフォールバックさせます。`name = "OpenAI"` は Codex の公式機能ゲート(web search、リモート圧縮など)を引き続きヒットさせます。`supports_websockets = true` は custom エントリでデフォルトに失われる能力を補います。`wire_api = "responses"` は公式の responses プロトコルを使います。**正味の効果は: 認証は変わらず、バケット名が変わるだけ。**
+
+**重要な不変条件: この注入は live `config.toml` にのみ存在でき、決してデータベースの保存設定には書き込まれません。** 公式プロバイダーから切り替えて離れ、live をデータベースへ書き戻すとき、CC Switch はこの注入を正確に剥離します(形態が注入物と完全に一致するときだけ剥離し、サードパーティがカスタムした `custom` テーブルはそのまま保持します)。だからこそ「スイッチをオフにする + 一度切り替える」だけで live を完全に復元でき、データベースには常にあなた本来のクリーンな公式設定が保たれます——これがスイッチ全体の可逆性の礎です。
+
+### 3. 注入の 2 つの拒否ゲート(シナリオ C に対応)
+
+- `config.toml` に明示的な `model_provider` がすでにある → ユーザーのルーティングを上書きしない。
+- 形態の異なる `[model_providers.custom]` テーブルがすでに存在する(サードパーティの `base_url` が付いている可能性がある)→ 注入を拒否、さもないと ChatGPT OAuth トラフィックを誤ったバックエンドへルーティングしてしまう。
+
+注入を拒否したとき live は統一されず、移行ゲート(live の `model_provider` が trim 後に `custom` と等しいかを確認)が `live_not_unified` と判定 → 移行をスキップし、意思を保持し、次回起動の再試行時に行います。これは「安全な先送り」であり、「失敗してデータが消えた」ではありません。
+
+### 4. セッションの三分類(移行 / 復元の境界を決める)
+
+- **A 類**: オン時に移行した既存の公式セッション——バックアップが台帳であり、正確に `openai` へ復元可能。
+- **B 類**: オン期間中に新規作成——どのバックアップにもなく、公式 / サードパーティを判別不能、**決して自動で動かさない**(`custom` に残す)。
+- **C 類**: オン前の純粋なサードパーティ履歴——絶対に触れない。
+
+### 5. 移行 / 復元の安全性(データが本当に削除されることはない、その保証はどこから来るか)
+
+4 層の設計が共同で保証します: **正常・異常のあらゆるパス** において、元のセッションデータが本当に削除されることはありません。
+
+- **フィールドだけ変更、本文には触れない**: 移行 / 復元はセッションメタデータ内の `model_provider` の値を `openai` と `custom` の間で切り替えるだけで、会話内容、`response_item`、`encrypted_content` はすべてそのまま保持します。
+- **書き換え前に必ずコピーをバックアップ**: jsonl はファイルコピー、state DB は SQLite の完全なコピーで、タイムスタンプ付きの世代ディレクトリに保存します。移行バックアップは `codex-official-history-unify-v1/` に、復元バックアップは独立した `codex-official-history-unify-restore-v1/` にあり、台帳を純粋に保つため両者は分けられています。
+- **移すだけ削除しない + 原子書き込み**: すべての jsonl 書き換えは「一時ファイル + 全体置換」を経由し、state DB はトランザクション化された `UPDATE` を経由し、全工程でセッションやインデックスを削除する操作は一切ありません。ファイルはいかなる時点でも完全です。
+- **悲観的スキップ + 冪等で再試行可能**: バケットが不一致のとき(`live_not_unified`)は移行しないことを選びます。一つのプロセスロックが移行と復元を直列化し、「起動時の再試行 / 保存後のバックグラウンドタスク / 無効化時の復元」が同じ一群のファイルを並行して双方向に書き換えるのを防ぎます。完了マークは Codex ディレクトリに紐づけて条件付きで書き込み、移行漏れを防ぎます。復元は「台帳にある + 現在もまだ custom」の二重条件を使い、誤変更を防ぎます。復元スキャンはすべてのバックアップ世代の和集合を取り、何度もスイッチを切り替えた後でも初期に移行したセッションを復元できます。重複した復元は `nothing_to_restore` を返しますが、これは冪等保護であり失敗ではありません。
+
+### 6. バックエンドをまたいだ encrypted_content(シナリオ B に対応)
+
+セッション内の推論暗号文は、それを生成したバックエンドだけが復号でき、上流の Codex は by design でバックエンドをまたいだ復号をサポートしません。これが「再開失敗」の根本原因であり、ファイルの完全性とは無関係です——セッション `.jsonl` は完全にディスク上に横たわり、`encrypted_content` も無傷です。元のプロバイダーに戻して再開するか、新規セッションを始めれば、どちらも正常です。
+
+---
+
+## 参考リンク
+
+- [サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する: CC Switch 設定ガイド](./codex-official-auth-preservation-guide-ja.md)
+- [Codex で DeepSeek などの Chat 形式 API を使う: CC Switch ローカルルーティングガイド](./codex-deepseek-routing-guide-ja.md)
+- CC Switch ユーザーマニュアル内の「Codex アプリ拡張」関連の章
+
+---
+
+**最後に一言**: あなたが見た「セッションが消えた / 再開失敗」は、本質的には **セッションが別の履歴リスト(引き出し)に移されたか、相手のバックエンドが古い推論内容を復号できない** ことであり、ファイルは常にそっくりそのまま `~/.codex/sessions/`(および `state_5.sqlite`)に横たわっています。スイッチをオフにするとき「バックアップから復元する」にチェックを入れれば、移行した公式セッションを正確に公式リストへ戻せます。たとえ復元しなくても、元の `.jsonl` ファイルと `~/.cc-switch/backups/codex-official-history-unify-*/` 配下のバックアップコピーはどちらも残っています——**データが本当に失われることは決してありません。**
diff --git a/docs/guides/codex-unified-session-history-guide-zh.md b/docs/guides/codex-unified-session-history-guide-zh.md
new file mode 100644
index 000000000..796b12de4
--- /dev/null
+++ b/docs/guides/codex-unified-session-history-guide-zh.md
@@ -0,0 +1,467 @@
+# 统一 Codex 会话历史:功能介绍与使用攻略(CC Switch)
+
+> 适用版本:CC Switch v3.16.x 及以上。本文根据当前代码整理,命令与路径均可亲手验证;示例使用去敏数据,不包含真实会话内容或 API Key。
+
+## 这个功能是什么
+
+「统一 Codex 会话历史」是 CC Switch v3.16.x 为 Codex 新增的一个开关。它的位置在 **设置 → 通用 → 「Codex 应用增强」分组**里("Codex 应用增强"是这个分组的标题,开关本身叫"统一 Codex 会话历史")。开启后,**官方订阅(ChatGPT 登录 / OpenAI API Key)的会话,会和 CC Switch 管理的所有第三方供应商会话,出现在同一个历史 / 续聊列表里**——不再被分隔在两个互相看不见的列表中。
+
+## 它解决什么问题
+
+Codex 自己按"供应商标签"(一个叫 `model_provider` 的字段)给会话分类,而且**续聊 / 历史列表只显示和你当前激活的供应商同标签的会话**。于是会话天然被分进两个"抽屉":
+
+- 官方订阅的会话,归在 Codex 内建的 **`openai`** 标签下;
+- CC Switch 管理的所有第三方供应商,归在 **`custom`** 标签下。
+
+两个抽屉互相看不见。如果你**经常在官方与第三方之间切换**,就会遇到这种割裂:"刚才用官方聊的会话,切到第三方后在历史列表里找不到了"——它其实没丢,只是被分到了另一个抽屉。这种割裂既容易让人误以为会话丢失,也不方便把所有会话放在一处统一回顾、续聊。
+
+**这个开关就是为了消除这种割裂**:让官方订阅也以 `custom` 标签运行,于是官方与第三方会话合并进同一个列表,找起来、续起来都在一处。
+
+> ✅ **一个贯穿全文的重要前提,请先记住**:这个功能(统一 / 迁移 / 还原)**全程只改写会话记录里那一个归类标签 `model_provider`,而且每次改写前都会自动把原文件备份一份**。它不会删除、清空或覆盖你的任何一句对话。所以本文后面若提到"某些会话看不到了",几乎都是"被分到了另一个抽屉",而不是"数据没了"——真担心时,直接看 [症状对照表](#我感觉会话丢了症状对照表) 与 [亲手验证文件还在](#亲手验证你的会话文件还在硬盘上最重要的一节)。
+
+## 工作原理(一句话版)
+
+把它想成 **两个抽屉 + 自动备份**:
+
+- 默认时,官方会话在 `openai` 抽屉、第三方会话在 `custom` 抽屉,互不可见;
+- 开关让**官方也改用 `custom` 抽屉**,于是两个抽屉合并成一个共享列表;
+- 你可以选择把**现有的官方老会话**也一并"搬"进共享抽屉(这一步叫**迁移**,可选、需主动勾选),而**任何搬动前都会先复制一份备份**,所以整个过程**可逆**;
+- **认证完全不受影响**——官方订阅照常用你的 ChatGPT 登录、照常走官方后端,变的只是会话的归类标签。
+
+完整机制(注入了什么、为什么可逆、迁移/还原如何保证不丢数据)见下文 [核心心智模型](#核心心智模型两个抽屉--自动备份) 与文末 [进阶原理附录](#进阶原理附录给想真正搞懂机制的用户)。
+
+## 如何使用(速览)
+
+1. **开启**:设置 → 通用 → Codex 应用增强 → 打开「统一 Codex 会话历史」→ 在弹窗里决定是否勾选"同时迁入现有官方会话历史"(想让**以前**的官方会话也并进统一列表,就勾上;只想从现在起统一,就不勾)→ 确认。详见 [开启时会发生什么](#开启时会发生什么分步说明)。
+2. **关闭**:关掉同一开关 → 弹窗里保持勾选"按备份精确还原"(默认就勾着)→ 确认,即可把当初迁入的官方会话精确翻回官方列表。详见 [关闭时会发生什么](#关闭时会发生什么分步说明)。
+3. **感觉会话丢了?** 别慌,跳到 [症状对照表](#我感觉会话丢了症状对照表) 按症状定位,并用 [亲手验证](#亲手验证你的会话文件还在硬盘上最重要的一节) 一节的命令亲眼确认文件都在。
+
+---
+
+## 核心心智模型:两个抽屉 + 自动备份
+
+要理解这个功能,你只需要记住两件事:**抽屉**和**备份**。
+
+### 抽屉:Codex 怎么给会话分类
+
+你每开一个 Codex 会话,Codex 会在会话文件头部记一个标签 `model_provider`,标记"这条会话是用哪个供应商聊的"。Codex 的**续聊 / 历史列表是按当前激活的这个标签精确过滤的**——只显示和"你现在这个供应商"同标签的会话。
+
+- 官方订阅(ChatGPT 登录 / OpenAI API Key)的会话,标签是内建的 **`openai`**。
+- CC Switch 管理的所有第三方供应商,统一用标签 **`custom`**。
+
+所以默认情况下,官方会话和第三方会话天生互相看不见——它们在两个不同的抽屉里。这是 **Codex 自身的设计**,不是 CC Switch 弄丢了什么。
+
+```text
+默认状态(没开统一开关):
+
+ ┌─────────────────┐ ┌─────────────────┐
+ │ openai 抽屉 │ │ custom 抽屉 │
+ │ (官方订阅会话) │ │ (第三方供应商会话)│
+ └─────────────────┘ └─────────────────┘
+ ▲ ▲
+ 用官方时只看到这边 用第三方时只看到这边
+ (两个抽屉互相看不见)
+```
+
+**「统一 Codex 会话历史」开关做的事,就是让官方订阅也以 `custom` 标签运行,把两个抽屉合并成一个**,于是官方会话和第三方会话出现在同一个续聊列表里。注意:**认证没变**——你的官方订阅照常用你的 ChatGPT 登录、照常走官方后端,只是会话的"归类标签"从 `openai` 变成了 `custom`。
+
+```text
+开启统一开关后:
+
+ ┌─────────────────────────────────────────┐
+ │ custom 共享抽屉 │
+ │ 官方订阅会话 + 第三方供应商会话 │
+ │ (出现在同一个历史 / 续聊列表里) │
+ └─────────────────────────────────────────┘
+```
+
+### 备份:每次改标签前都先复制一份
+
+"合并抽屉"需要把一部分官方会话的标签从 `openai` 改成 `custom`(这一步叫**迁移**,且是**可选的、需要你主动勾选**)。而**任何一次改写之前,CC Switch 都会先把原文件原封不动地复制一份**到这里:
+
+```text
+~/.cc-switch/backups/codex-official-history-unify-v1/<时间戳>/
+```
+
+这份备份,就是日后"按备份精确还原"的唯一依据。它让整个过程变得**可逆**:你随时可以关掉开关,把当初迁进来的官方会话精确地翻回 `openai` 抽屉。
+
+记住这两个词——**抽屉**(会话只是换了归类)、**备份**(改前必先复制)——后面所有内容你都能轻松理解。
+
+---
+
+## 开启时会发生什么:分步说明
+
+### 第 1 步:找到开关
+
+```text
+设置 → 通用 → Codex 应用增强
+```
+
+在"Codex 应用增强"这个区块里有两行开关,**第二行**(蓝色历史图标)就是本攻略的主角:
+
+> **统一 Codex 会话历史**
+
+它下方有一段说明文字(逐字):
+
+> 开启后,官方订阅将以共享的 custom 供应商标识运行,官方与第三方会话出现在同一历史列表中,并可选择把现有官方会话一并迁入(迁移前自动备份)。关闭开关时可按备份恢复迁入的会话。注意:跨供应商继续旧会话时,对方后端可能无法解密会话中的 encrypted_content 推理内容,导致继续失败
+
+> **注意**:这一句说明里已经预告了三件事——会出现在同一列表、可选迁入并自动备份、跨供应商续聊"可能继续失败"。这里的"继续失败"指的是**续不上、生成不了新回合**,不是"记录丢失"。这正是后面要重点拆解的核心误解。
+
+### 第 2 步:把开关从关拨到开 → 弹出确认窗
+
+一旦你把开关拨到开,CC Switch **不会立刻保存**,而是先弹出一个确认窗口。窗口文案如下(逐字):
+
+- **标题**:统一 Codex 会话历史
+- **正文**:
+
+ > 开启后,官方订阅与第三方将共用同一个会话历史列表。注意:跨供应商继续旧会话时,可能因对方后端无法解密 encrypted_content 推理内容而失败。
+ >
+ > 可选择同时把现有官方会话历史迁入共享列表(迁移前自动备份到 ~/.cc-switch/backups,关闭开关时可选择恢复)。
+
+- **复选框**:同时迁入现有官方会话历史
+- **确认按钮**:我已了解,继续开启
+- **取消按钮**:取消
+
+**这个复选框默认是不勾选的。** 这是一个重要的分岔点:
+
+| 你的选择 | 效果 | 此刻你的数据在哪 |
+|---|---|---|
+| **不勾**(默认) | 只切换标识。**只有开启之后新建的官方会话**才会落进 `custom` 共享抽屉 | 你**开启前**的官方老会话,标签仍是 `openai`,原地未动,仍在 `~/.codex/sessions/` |
+| **勾上** | 除了切换标识,还会把**现有的官方老会话**也从 `openai` 抽屉迁进 `custom` 抽屉 | 老会话被**复制备份**后,标签改写为 `custom`;原始数据有备份兜底 |
+
+> **如果你希望"以前的官方会话也出现在统一列表里",必须主动勾选这个复选框。** 否则你会遇到下面对照表里的"场景 A"——老会话看起来"不见了",其实只是留在原抽屉里。
+
+点"取消"或点窗口外面:开关直接弹回关闭状态,什么都没发生。
+点"我已了解,继续开启":开关保存为开启,CC Switch 在后台落盘配置(如果勾了迁移,就执行迁移)。
+
+### 第 3 步(仅当勾了迁移):迁移如何执行 + 数据安全
+
+如果你勾了"同时迁入现有官方会话历史",CC Switch 会对你的官方老会话做这套流程:
+
+```text
+对每个官方(openai 标签)会话文件:
+ ① 先把原文件原样复制一份到备份目录 ← 数据有了第一道保险
+ ② 用「写临时文件 → 整体替换」的原子方式,
+ 只把头部那行 session_meta 里的 model_provider
+ 从 "openai" 改成 "custom" ← 对话正文一个字节都不动
+ ③ 索引数据库 state_5.sqlite 同步在一个事务里把标签改过来
+```
+
+- **备份位置**:`~/.cc-switch/backups/codex-official-history-unify-v1/<时间戳>/`,每次迁移生成一个带时间戳的"代际目录",内含 `jsonl/`(会话副本)、`state/`(索引库副本)、`meta.json`(记录这次迁移属于哪个 Codex 目录)。
+- **改的是什么**:只有 `model_provider` 这一个字段值。你的对话内容、推理内容、所有正文**原样保留**。
+- **删的是什么**:**什么都没删**。备份是"复制",改写是"原子替换同一个文件",全程没有任何删除会话或索引的动作。文件在任何时刻都是完整的(要么是旧内容、要么是新内容,绝不会是空或半截)。
+
+迁移成功后,这些官方老会话就出现在统一列表里了。**此刻你的数据**:① 原始副本在备份目录;② 活动文件里只有归类标签变了,内容完好。
+
+> **注意**:开启与迁移本身**不会弹成功提示**。迁移是后端在保存时顺带跑的,UI 上你只会看到开关变成了打开状态。所以"没看到迁移成功的弹窗"是正常的,不代表失败。
+
+---
+
+## 关闭时会发生什么:分步说明
+
+### 第 1 步:把开关从开拨到关 → 探测备份 → 弹出确认窗
+
+关闭时,CC Switch 会**先花一瞬间探测有没有迁移备份**,然后弹出确认窗口(所以关闭弹窗会有一点点延迟,属正常)。文案如下(逐字):
+
+- **标题**:关闭统一会话历史
+- **正文**:
+
+ > 关闭后,官方订阅与第三方将恢复各自独立的会话历史列表。开启期间产生的会话因无法区分来源,将留在第三方历史中,官方订阅将看不到它们。
+
+- **复选框**(条件显示):把开启时迁入的官方会话还原回官方历史(按备份精确还原)
+- **确认按钮**:关闭
+- **取消按钮**:取消
+
+> **划重点**:正文说的是"官方订阅**将看不到它们**"——是**看不到**,不是**删除**。开启期间你新聊的会话仍然完整地在 `custom` 抽屉里,只是关闭后官方那一侧看不到而已。
+
+**这个还原复选框默认是勾选的。** 也就是说,默认行为就是"关闭的同时,把当初迁入的官方会话精确还原回官方历史"。你只要保持勾选、点"关闭"即可。
+
+如果复选框**没有出现**,说明系统判断当前没有需要还原的备份(要么你从没勾过迁移、要么探测不到备份)——这种情况下你的官方老会话从没被改动过,关掉开关它们自己就回到 `openai` 抽屉了。
+
+### 第 2 步:还原如何执行(按备份账本精确翻回)
+
+如果你保持勾选并点"关闭",CC Switch 的还原流程是这样的:
+
+```text
+① 先把当前现场再复制一份到独立的还原备份目录
+ ~/.cc-switch/backups/codex-official-history-unify-restore-v1/<时间戳>/
+ (还原本身也先备份,所以还原也不会丢数据)
+② 翻遍所有迁移备份代际,找出"当初标签是 openai"的会话 id,组成一份"账本"
+③ 只对【既在账本里、当前又仍是 custom】的会话,把标签改回 "openai"
+```
+
+注意第 ③ 步的**双重条件**——既要在账本里(证明它当初确实是官方迁来的),又要当前仍是 `custom`(说明你没手动改过它)。两个条件都满足才翻回。这保证了还原既精确又不会误伤。
+
+**此刻你的数据**:被迁回的官方会话标签改回 `openai`,重新出现在官方列表;同时迁移备份和还原备份两份副本都还在硬盘上。
+
+### 第 3 步:看提示,确认结果
+
+只有"关闭 + 勾选还原"这条路径会弹结果提示。可能看到的提示(逐字):
+
+| 你看到的提示 | 含义 |
+|---|---|
+| **已按备份还原官方会话历史({{files}} 个会话文件、{{rows}} 条索引记录)** | 还原成功。`{{files}}` / `{{rows}}` 处会显示实际数字 |
+| **当前 Codex 目录没有可恢复的迁移备份** | 没有可还原的内容(**不等于数据丢了**,详见对照表场景 E) |
+| **统一会话历史开关已重新开启,已跳过还原** | 还原排队期间你又把开关打开了,系统主动放弃还原(详见对照表场景 F) |
+| **还原官方会话历史失败,请重试** | 还原过程报错,重试即可,数据未被破坏 |
+| **保存失败,请重试** | 关闭这一步保存本身就失败了;此时**绝不会触发还原**,开关弹回原位 |
+
+> **一个贴心的安全设计**:如果"关闭开关"这一步保存失败,CC Switch **绝不会去执行还原**。否则就会出现"开关还开着、会话却被翻回 openai 桶"的撕裂状态。保存失败时开关会**自动弹回原来的位置**,你不会停留在一个"看起来已关、实则没保存"的假状态里。
+
+---
+
+## "我感觉会话丢了?"症状对照表
+
+下面六个场景,是用户最容易误以为"会话丢了"的情形。**每一个的真相都是:数据完好,只是换了抽屉或暂时看不到。** 先用这张表按症状定位,再看下面的详细说明。
+
+| 场景 | 你看到的 | 数据真相 | 一句话解法 |
+|---|---|---|---|
+| **A** 没勾迁移 | 官方老会话不在统一列表 | 全在,仍带 `openai` 标签 | 重开并勾迁移,或关开关 |
+| **B** 跨供应商续聊失败 | 续不上 / 报错 | 文件完好,只是密文跨后端解不开 | 回原供应商续;只看内容直接读 jsonl |
+| **C** 代理接管 / 注入被拒 | 没迁也没还原 | 迁移被安全跳过,文件没动 | 退出接管 → 重启重试;或直接关开关 |
+| **D** 还原后新会话没回官方 | 开启期间新会话不在官方 | 在 `custom` 抽屉,设计上不动 | 切第三方供应商即可见 |
+| **E** 提示"没有可恢复备份" | 还原"失败" | 通常压根没迁移过,会话在原抽屉 | 关开关官方会话自动复现 |
+| **F** 提示"开关已重新开启,跳过还原" | 还原被拒 | 防数据撕裂,啥也没改 | 先彻底关开关再还原 |
+
+### 场景 A:开了开关但没勾迁移 → 官方老会话"不见了"
+
+**现象**:你开了统一开关,但开启弹窗里那个"同时迁入现有官方会话历史"没勾(它默认就不勾)。开启后一看,以前的官方老会话好像都不在列表里了。
+
+**真相**:数据 100% 都在,一行都没动。开关只对"开启之后新建"的官方会话生效,你**开启前**的官方老会话标签仍是 `openai`,原封不动地躺在 `~/.codex/sessions/` 里。你现在激活的是 `custom` 抽屉,自然看不到留在 `openai` 抽屉里的老会话——这就是"看起来消失"的全部原因。
+
+**怎么办**(任选其一):
+1. **重新开启开关时勾上"同时迁入现有官方会话历史"**,把老会话换到 `custom` 抽屉,它们立刻出现在统一列表(改写前自动备份)。
+2. **或者干脆关掉统一开关**,官方重新以 `openai` 抽屉运行,老会话原地复现。
+
+### 场景 B:跨供应商续聊旧会话失败 → 以为"这条会话坏了 / 没了"
+
+**现象**:统一之后列表里能看到一条用"另一家供应商"聊出来的旧会话,你切到现在的供应商点"继续",结果报错或接不上。
+
+**真相**:会话文件完好无损,丢的不是数据,是"跨后端解密能力"。Codex 会话里保存了一段加密的推理内容 `encrypted_content`,**这段密文只有当初生成它的那个后端能解密**。你用 B 供应商去续 A 供应商生成的会话,B 解不开 A 的密文 → 续聊失败。这是**上游 Codex 的设计限制(by design)**,与 CC Switch 是否动过文件无关。会话里的文字内容你随时能读到。
+
+> 这是整篇攻略里**唯一一个"看起来真出了问题"的真实例外**——但请注意:它只是**无法续聊(生成不了新回合)**,**原始文件依然完整存在**,对话文字随时可读。
+
+**怎么办**:
+- **用"当初创建这条会话的那个供应商"去续聊**,就能正常解密、接上。
+- 只想看历史内容、不必继续?直接读那条会话的 `.jsonl` 文件(文末有命令)。
+- 经验法则:**跨供应商更适合"开新会话",老会话尽量回原供应商续。**
+
+### 场景 C:开了开关也勾了迁移,但迁移被静默跳过 → 以为"迁移把会话弄丢了"
+
+**现象**:你开启并勾了迁移,但官方老会话既没进统一列表、关开关想还原也提示没东西可还原(或者关闭弹窗里压根没出现还原复选框,参见场景 E)。你怀疑迁移过程中把会话搞丢了。
+
+**真相**:迁移根本**没执行**,所以也不可能弄丢——你的会话一个字都没被改。CC Switch 在迁移前有一道安全闸门:它会检查 Codex 的 live 配置(`~/.codex/config.toml`)此刻是否**真的**路由到了共享 `custom` 抽屉,只有真路由过去了才迁移。以下两种情况会判定"还没统一"(内部原因码 `live_not_unified`),于是**主动跳过迁移、保留你的开关和迁移意愿、等条件满足后再迁**:
+
+- **代理接管期间**:CC Switch 的代理接管了 live 配置,接管期的 live 不带统一路由标记。
+- **注入被拒**:你的 `config.toml` 已有手工指定的 `model_provider`,或已存在一张形态不同的 `[model_providers.custom]` 表(可能带第三方地址)。为避免把官方流量错误路由到第三方后端,CC Switch 宁可不注入、不迁移。
+
+跳过迁移 = 不碰任何会话文件。**没迁,等于没动,谈不上丢。** 这是"安全延后",不是"失败丢数据"。
+
+**怎么办**:
+- 退出代理接管 → **重启 CC Switch**:启动时会自动重试迁移(你的迁移意愿一直保留着)。
+- 检查 `~/.codex/config.toml`:若有你手工写的冲突路由,整理掉冲突后再开开关。
+- 实在不想折腾:直接关开关,官方会话仍以 `openai` 抽屉正常显示,毫发无损。
+
+### 场景 D:关了开关并还原,但"开启期间新聊的会话"没回官方 → 以为"新会话丢了"
+
+**现象**:你开启统一期间,用官方又聊了几条新会话。后来关开关、勾了还原,还原完发现那几条新会话没回到官方抽屉。
+
+**真相**:这是**有意为之**的设计,新会话好端端在 `custom` 抽屉里,能看见、能续。还原的依据是"迁移时的备份账本"——**只有当初从 `openai` 抽屉迁进来的会话**,备份里有据可查,才会被精确翻回 `openai`。你**开启期间新建**的会话不在任何备份账本里;而且统一之后官方和第三方都用 `custom` 标签,**CC Switch 无法分辨这条新会话到底是官方聊的还是第三方聊的**。为了不把第三方会话误塞进官方历史,产品决策是:这些新会话一律留在 `custom`(第三方)历史里,绝不自动搬动。关闭弹窗的文案也明示了这一点——"开启期间产生的会话因无法区分来源,将留在第三方历史中"。
+
+**怎么办**:
+- 切到任意一个第三方供应商(`custom` 抽屉),就能在历史列表里看到这些会话。
+- 想看内容直接读 `.jsonl`;想续聊遵循场景 B 的规则(回到当初生成它的后端)。
+- 如果你确实想把**某一条**手动归回官方:目前没有自动按钮(刻意不做,避免误判方向)。进阶用户可在**先备份**该文件后,手动把它 `.jsonl` 第一行 `session_meta` 里的 `model_provider` 从 `custom` 改回 `openai`(属高阶操作,改前务必复制一份)。
+
+### 场景 E:还原提示"当前 Codex 目录没有可恢复的迁移备份" → 以为"还原失败 = 数据没了"
+
+**现象**:关开关时勾了还原,结果弹出提示"当前 Codex 目录没有可恢复的迁移备份"。你慌了:还原都失败了,是不是数据彻底没了?
+
+**真相**:"没有可还原的东西"≠"数据丢了"。恰恰相反,通常是因为**根本没有需要还原的迁移**。常见原因:
+
+- **你当初没勾过"迁入现有官方会话"**:既然没迁移,自然没有迁移备份、也没有需要翻回去的会话。你的官方老会话一直在 `openai` 抽屉,关开关后直接复现(同场景 A)。(这种情况下,关闭弹窗甚至可能**根本不显示还原复选框**——因为系统探测不到任何备份。)
+- **已经还原过一遍了**:会话标签已全部翻回 `openai`,再点一次自然"没有仍是 custom 的目标可还原"——这是**幂等保护,不是失败**。
+- **切换过 Codex 目录**:还原只认属于**当前**目录的备份账本,换了目录就找不到旧目录的账本,把目录切回去即可。
+
+这三种情况下,没有任何会话被删除。
+
+**怎么办**:用文末命令统计 `~/.codex/sessions/` 里的会话文件总数,确认文件都在;再看 `~/.cc-switch/backups/` 里有没有 `codex-official-history-unify-v1` 目录——如果连这个目录都没有,说明你从没触发过迁移,会话一直在原抽屉。
+
+### 场景 F:还原被拒,提示"统一会话历史开关已重新开启,已跳过还原"
+
+**现象**:关开关 → 勾还原 → 你手很快,紧接着又把开关重新打开了,然后看到提示"统一会话历史开关已重新开启,已跳过还原"。
+
+**真相**:这是一道防护,防止把数据弄成"撕裂"状态,会话同样没丢。还原的动作是"把会话标签从 `custom` 翻回 `openai`",但如果此刻开关又开着,live 配置正路由到 `custom`——一边把历史翻回 `openai`、一边新会话往 `custom` 落,会话会被人为撕成两半。所以 CC Switch 检测到"开关又开了",**主动放弃这次还原、什么都不改**。会话维持现状,没有任何删除或破坏。
+
+**怎么办**:想真正还原,就**先把开关稳定地关掉**(别再立刻打开),再执行关闭 + 勾还原;想保持统一,就别还原,让会话留在 `custom` 共享抽屉正常使用。
+
+**总原则:CC Switch 的统一 / 迁移 / 还原全程只改会话的一个标签字段,并且每次改写前都自动备份。它不会删你的对话。看不见 ≠ 丢了——换个抽屉看,或用下面的命令亲眼确认。**
+
+---
+
+## 亲手验证:你的会话文件还在硬盘上(最重要的一节)
+
+文字再多,不如亲眼看见。下面给出**真实路径**(取自 CC Switch 源码)和在不同系统下查看会话文件、备份目录的方法。**全程只读不改,强烈建议你亲手试一遍。**
+
+### 最简单的方式:用文件管理器直接打开(完全不用命令行)
+
+- **macOS(Finder)**:按 `Cmd + Shift + G`,粘贴 `~/.codex/sessions` 回车,就能看到一堆 `.jsonl` 会话文件和它们的修改时间;备份目录粘贴 `~/.cc-switch/backups`。
+- **Windows(文件资源管理器)**:在地址栏粘贴 `%USERPROFILE%\.codex\sessions` 回车,就能看到会话文件夹和里面的 `.jsonl`;备份目录粘贴 `%USERPROFILE%\.cc-switch\backups`。
+
+**只要你能在这里看到一批 `.jsonl` 文件,就证明会话数据完好无损地在硬盘上。** 文件数量、修改时间,比任何文字都直观。
+
+### 你的会话 / 历史文件到底在哪
+
+| 内容 | 真实路径 | 说明 |
+|---|---|---|
+| **会话正文(核心)** | `~/.codex/sessions/`(含按日期分的子目录,递归) | 每个会话一个 `.jsonl` 文本文件,**这就是你的对话内容** |
+| **归档会话** | `~/.codex/archived_sessions/` | 同为 `.jsonl` |
+| **会话索引数据库** | `~/.codex/state_5.sqlite` | `threads` 表的 `model_provider` 列就是"抽屉标签",**它才是续聊列表真正读取的归类来源** |
+| **迁移备份**(开启迁移时自动产生) | `~/.cc-switch/backups/codex-official-history-unify-v1/<时间戳>/` | 内含 `jsonl/`、`state/`、`meta.json` |
+| **还原备份**(点还原时自动产生) | `~/.cc-switch/backups/codex-official-history-unify-restore-v1/<时间戳>/` | 还原前的安全副本 |
+
+> **注意**:如果你在 CC Switch 里改过 Codex 目录,或在 `config.toml` 里设了 `sqlite_home`,请把上面的 `~/.codex` 换成你的实际目录。下文 `~` = 你的用户主目录。
+
+### macOS / Linux 命令
+
+**1. 数会话文件总数(这才是"没丢"的硬证据)**
+
+```bash
+# 统计会话文件总数 —— 只要这个数字符合你的预期,数据就都在
+find ~/.codex/sessions ~/.codex/archived_sessions -name '*.jsonl' 2>/dev/null | wc -l
+
+# 看最近修改的 10 个会话文件
+find ~/.codex/sessions -name '*.jsonl' 2>/dev/null -print0 \
+ | xargs -0 ls -lt 2>/dev/null | head -10
+```
+
+**2. (辅助)看每个"抽屉"各有多少会话**
+
+```bash
+# 官方抽屉(openai)会话文件数
+grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"openai"' ~/.codex/sessions 2>/dev/null | wc -l
+
+# 统一抽屉(custom)会话文件数
+grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"custom"' ~/.codex/sessions 2>/dev/null | wc -l
+
+# 看各标签分布一目了然
+grep -rhoE '"model_provider"[[:space:]]*:[[:space:]]*"[^"]*"' ~/.codex/sessions 2>/dev/null | sort | uniq -c
+```
+
+> **重要提示,别被这一步吓到**:**早期版本的 Codex 不在 `.jsonl` 里写 `model_provider` 字段**,这些旧官方会话用上面的 grep 是**数不到**的,但它们在索引库 `state_5.sqlite` 里仍然归类为 `openai`、续聊列表照样能看到。所以**判断"会话没丢"请以第 1 步的文件总数为准**——分桶 grep 只是帮你理解归类,数出来比文件总数少**完全正常**,绝不代表"丢了一批"。
+
+**3. (进阶)查索引库 `state_5.sqlite`——续聊列表真正读的归类**
+
+```bash
+# 需要已安装 sqlite3;没装可跳过
+sqlite3 ~/.codex/state_5.sqlite \
+ "SELECT COALESCE(model_provider,'<空>'), COUNT(*) FROM threads GROUP BY 1;"
+```
+
+> 这张 `threads` 表才是 Codex 续聊列表真正读取的归类来源,`openai` 行数 ≈ 你官方抽屉里能看到的会话数。它和第 2 步的 jsonl grep 可能对不上数——原因就是上面说的"旧会话不写 jsonl 字段,但索引库里仍是 openai"。两边对不上不是异常。
+
+**4. 直接读某条会话的内容(确认对话文字还在)**
+
+```bash
+# 把 <文件名> 换成上面 ls 列出的某个 .jsonl 路径
+python3 -m json.tool < "<文件名>.jsonl" 2>/dev/null | head -50
+
+# 或者直接用编辑器打开看(纯文本)
+open -e "<文件名>.jsonl" # macOS
+```
+
+**5. 看 CC Switch 的备份目录(证明迁移 / 还原前都留了副本)**
+
+```bash
+ls -la ~/.cc-switch/backups/codex-official-history-unify-v1/ 2>/dev/null
+ls -la ~/.cc-switch/backups/codex-official-history-unify-restore-v1/ 2>/dev/null
+```
+
+### Windows 命令(PowerShell)
+
+会话目录通常在 `C:\Users\<你的用户名>\.codex\`,备份在 `C:\Users\<你的用户名>\.cc-switch\backups\`。
+
+```powershell
+# 1. 会话文件总数("没丢"的硬证据)
+(Get-ChildItem "$env:USERPROFILE\.codex\sessions","$env:USERPROFILE\.codex\archived_sessions" -Recurse -Filter *.jsonl -ErrorAction SilentlyContinue).Count
+
+# 2. 最近修改的 10 个会话
+Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
+ Sort-Object LastWriteTime -Descending | Select-Object -First 10 FullName,LastWriteTime
+
+# 3. (辅助)官方(openai) / 统一(custom) 抽屉各多少会话文件
+(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
+ Select-String -Pattern 'model_provider"\s*:\s*"openai"' -List).Count
+(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
+ Select-String -Pattern 'model_provider"\s*:\s*"custom"' -List).Count
+
+# 4. 看备份目录
+Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-v1" -ErrorAction SilentlyContinue
+Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-restore-v1" -ErrorAction SilentlyContinue
+```
+
+> 同样提醒:第 3 步的 grep 数会**少于**文件总数属正常(旧会话不写该字段),请以第 1 步的**文件总数**作为"会话没丢"的判断依据。
+
+---
+
+## 进阶原理附录(给想真正搞懂机制的用户)
+
+### 1. 分桶机制(抽屉的本质)
+
+Codex 的续聊 / 历史列表按当前激活的 `model_provider` id **精确字符串过滤**。会话文件 `.jsonl` 的**第一行**是一条 `type:"session_meta"` 记录,其 `payload.model_provider` 即该会话所属抽屉(`grep -rl` 只要文件里出现一次该标签就计入该文件,因此无需逐行解析;旧版本未写该字段的会话则数不到)。真正驱动续聊列表的是索引库 `state_5.sqlite` 的 `threads.model_provider` 列。官方订阅在 `config.toml` 没有显式 `model_provider` 时落进内建默认 id `openai`;CC Switch 的所有第三方供应商统一用 `custom`。
+
+### 2. 开关做的事(注入,只活在 live)
+
+开启后,CC Switch 对官方 live `config.toml` 注入如下内容:
+
+```toml
+model_provider = "custom"
+
+[model_providers.custom]
+name = "OpenAI"
+requires_openai_auth = true
+supports_websockets = true
+wire_api = "responses"
+```
+
+每个字段都有作用:`requires_openai_auth = true` 让认证继续走 `auth.json` 里的 ChatGPT 登录、base_url 缺省回落官方 Codex 后端;`name = "OpenAI"` 让 Codex 的官方特性门控(web search、远程压缩等)继续命中;`supports_websockets = true` 补回 custom 条目默认丢失的能力;`wire_api = "responses"` 用官方 responses 协议。**净效果是:认证没变,只是桶名变了。**
+
+**关键不变量:这段注入只能存在于 live `config.toml`,绝不写进数据库的存储配置。** 切换离开官方供应商、把 live 回写数据库时,CC Switch 会把这段注入精确剥离(只在形态与注入产物完全一致时才剥,第三方自定义的 `custom` 表原样保留)。正因如此,"关掉开关 + 切换一次"就能彻底还原 live,数据库里始终是你原本干净的官方配置——这是整个开关可逆性的基石。
+
+### 3. 注入的两道拒绝闸(对应场景 C)
+
+- `config.toml` 已有显式 `model_provider` → 不覆盖用户路由;
+- 已存在形态不同的 `[model_providers.custom]` 表(可能带第三方 `base_url`)→ 拒绝注入,否则会把 ChatGPT OAuth 流量路由到错误后端。
+
+拒绝注入时 live 不统一,迁移闸门(检查 live 的 `model_provider` 是否 trim 后等于 `custom`)判定 `live_not_unified` → 跳过迁移、保留意愿、等下次启动重试时再做。这是"安全延后",不是"失败丢数据"。
+
+### 4. 会话三分类(决定迁移 / 还原边界)
+
+- **A 类**:开启时迁入的存量官方会话——备份即账本,可精确还原回 `openai`;
+- **B 类**:开启期间新建——不在任何备份、官方 / 第三方不可分,**永不自动搬动**(留 `custom`);
+- **C 类**:开启前的纯第三方历史——绝不触碰。
+
+### 5. 迁移 / 还原的安全性(数据不会被真正删除,保障来自哪里)
+
+四层设计共同保证:在**正常与异常的所有路径**下,原始会话数据都不会被真正删除。
+
+- **只改字段,不动正文**:迁移 / 还原只把会话元数据里的 `model_provider` 值在 `openai` 与 `custom` 之间切换,对话内容、`response_item`、`encrypted_content` 一律原样保留。
+- **改写前必先复制备份**:jsonl 用文件复制、state DB 用 SQLite 完整副本,存进时间戳代际目录。迁移备份在 `codex-official-history-unify-v1/`,还原备份在独立的 `codex-official-history-unify-restore-v1/`,两者分开以保持账本纯净。
+- **只移不删 + 原子写**:所有 jsonl 改写走"临时文件 + 整体替换",state DB 走事务化 `UPDATE`,全程没有任何删除会话或索引的动作。文件在任一时刻都是完整的。
+- **悲观跳过 + 幂等可重试**:桶不一致时(`live_not_unified`)宁可不迁;一把进程锁串行化迁移与还原,避免"启动重试 / 保存后台任务 / 关闭还原"并发对同批文件双向改写;完成标记按 Codex 目录绑定、条件写入,防漏迁;还原用"在账本 + 当前仍 custom"双重条件,防误改。还原扫描全部备份代际取并集,多次开关循环后仍能还原早期迁入的会话;重复还原返回 `nothing_to_restore`,是幂等保护而非失败。
+
+### 6. 跨后端 encrypted_content(对应场景 B)
+
+会话内的推理密文只能被生成它的后端解密,上游 Codex by design 不支持跨后端解密。这是"续聊失败"的根因,与文件完整性无关——会话 `.jsonl` 完整躺在磁盘上、`encrypted_content` 也完好无损。换回原供应商续聊,或开新会话,都正常。
+
+---
+
+## 参考链接
+
+- [使用第三方 API 时保留 Codex 远程操作和官方插件:CC Switch 配置攻略](./codex-official-auth-preservation-guide-zh.md)
+- [在 Codex 中使用 DeepSeek 这类 Chat 格式 API:CC Switch 路由攻略](./codex-deepseek-routing-guide-zh.md)
+- CC Switch 用户手册中「Codex 应用增强」相关章节
+
+---
+
+**给你的最后一句话**:你看到的"会话不见了 / 续聊失败",本质是**会话被换到了另一个历史列表(抽屉)里、或对方后端无法解密旧推理内容**,文件始终原封不动地躺在 `~/.codex/sessions/`(及 `state_5.sqlite`)里。关闭开关时勾选"按备份还原"即可把当初迁入的官方会话精确翻回官方列表;即便不还原,原始 `.jsonl` 文件和 `~/.cc-switch/backups/codex-official-history-unify-*/` 下的备份副本也都在——**数据绝不会真正丢失。**
diff --git a/docs/release-notes/v3.16.1-en.md b/docs/release-notes/v3.16.1-en.md
index ab81e1cb0..ca796c3cb 100644
--- a/docs/release-notes/v3.16.1-en.md
+++ b/docs/release-notes/v3.16.1-en.md
@@ -105,7 +105,7 @@ Fixed multiple preserve-mode takeover paths that could clear or overwrite offici
Fixed cases where `modelCatalog` could be cleared during live backfill, active-provider editing, provider switching, and takeover shutdown restore. Snapshot backups preserve existing `model_catalog_json` pointers; backups rebuilt from providers regenerate catalog projections from the database source of truth; editing the active provider now prefers the database model catalog instead of trusting a live reverse-parse result that may have lost its projection.
-Provider switching also now always refreshes the generated Codex model catalog JSON ([#3360](https://github.com/farion1231/cc-switch/pull/3360), thanks [@Postroggy](https://github.com/Postroggy)).
+Provider switching also now always refreshes the generated Codex model catalog JSON ([#3360](https://github.com/farion1231/cc-switch/pull/3360), thanks @Postroggy).
### Codex Chat Tools, Plugins, and Custom Tools Restored
@@ -117,19 +117,19 @@ When Codex forwarding fails, CC Switch now returns JSON errors that include prov
### Codex Native Balance / Coding Plan Credential Lookup
-Fixed native balance and Coding Plan queries using credentials from the wrong app. Each app now resolves its own provider credentials instead of carrying authentication assumptions from another app surface into the query flow ([#3355](https://github.com/farion1231/cc-switch/pull/3355), thanks [@SiskonEmilia](https://github.com/SiskonEmilia)).
+Fixed native balance and Coding Plan queries using credentials from the wrong app. Each app now resolves its own provider credentials instead of carrying authentication assumptions from another app surface into the query flow ([#3355](https://github.com/farion1231/cc-switch/pull/3355), thanks @SiskonEmilia).
### Codex CLI Discovery and Model Catalog Template Fallback
-Fixed a too-narrow Codex CLI discovery path for third-party Codex model catalog projection. The backend now searches common Codex CLI install locations across platforms, and falls back to a built-in GPT-5.5 model catalog template if no template can be found ([#3382](https://github.com/farion1231/cc-switch/pull/3382), thanks [@chofuhoyu](https://github.com/chofuhoyu)).
+Fixed a too-narrow Codex CLI discovery path for third-party Codex model catalog projection. The backend now searches common Codex CLI install locations across platforms, and falls back to a built-in GPT-5.5 model catalog template if no template can be found ([#3382](https://github.com/farion1231/cc-switch/pull/3382), thanks @chofuhoyu).
### Claude Desktop Official Provider Add Failure
-Fixed an error when adding the Claude Desktop Official provider ([#3405](https://github.com/farion1231/cc-switch/pull/3405), thanks [@Eunknight](https://github.com/Eunknight)).
+Fixed an error when adding the Claude Desktop Official provider ([#3405](https://github.com/farion1231/cc-switch/pull/3405), thanks @Eunknight).
### Kimi / Moonshot Tool-Thinking History Normalization
-Added Kimi / Moonshot to the Anthropic-compatible tool-thinking history normalizer. Later turns can now correctly replay reasoning and tool-call context, avoiding failures caused by history messages that do not match upstream requirements ([#3377](https://github.com/farion1231/cc-switch/pull/3377), thanks [@Neon-Wang](https://github.com/Neon-Wang)).
+Added Kimi / Moonshot to the Anthropic-compatible tool-thinking history normalizer. Later turns can now correctly replay reasoning and tool-call context, avoiding failures caused by history messages that do not match upstream requirements ([#3377](https://github.com/farion1231/cc-switch/pull/3377), thanks @Neon-Wang).
### Windows Tool Version Detection
@@ -171,11 +171,11 @@ By enabling these features, users accept the related risks. CC Switch is not res
Thanks to the following contributors for fixes in v3.16.1:
-- [#3360](https://github.com/farion1231/cc-switch/pull/3360): always update Codex model catalog JSON when switching providers, thanks [@Postroggy](https://github.com/Postroggy).
-- [#3355](https://github.com/farion1231/cc-switch/pull/3355): resolve native balance / Coding Plan credentials per app, thanks [@SiskonEmilia](https://github.com/SiskonEmilia).
-- [#3405](https://github.com/farion1231/cc-switch/pull/3405): fix Claude Desktop Official provider add failure, thanks [@Eunknight](https://github.com/Eunknight).
-- [#3382](https://github.com/farion1231/cc-switch/pull/3382): Codex CLI multi-platform discovery and GPT-5.5 model template fallback, thanks [@chofuhoyu](https://github.com/chofuhoyu).
-- [#3377](https://github.com/farion1231/cc-switch/pull/3377): Kimi / Moonshot tool-thinking history normalization, thanks [@Neon-Wang](https://github.com/Neon-Wang).
+- [#3360](https://github.com/farion1231/cc-switch/pull/3360): always update Codex model catalog JSON when switching providers, thanks @Postroggy.
+- [#3355](https://github.com/farion1231/cc-switch/pull/3355): resolve native balance / Coding Plan credentials per app, thanks @SiskonEmilia.
+- [#3405](https://github.com/farion1231/cc-switch/pull/3405): fix Claude Desktop Official provider add failure, thanks @Eunknight.
+- [#3382](https://github.com/farion1231/cc-switch/pull/3382): Codex CLI multi-platform discovery and GPT-5.5 model template fallback, thanks @chofuhoyu.
+- [#3377](https://github.com/farion1231/cc-switch/pull/3377): Kimi / Moonshot tool-thinking history normalization, thanks @Neon-Wang.
Thanks also to everyone who reported Codex OAuth, model catalog, local routing takeover, and Chat Completions tool-call issues after v3.16.0. Many of these fixes came directly from real-world reproduction details.
diff --git a/docs/release-notes/v3.16.1-ja.md b/docs/release-notes/v3.16.1-ja.md
index 748af4afd..8e461e49c 100644
--- a/docs/release-notes/v3.16.1-ja.md
+++ b/docs/release-notes/v3.16.1-ja.md
@@ -105,7 +105,7 @@ Codex がローカルルーティングのテイクオーバー状態にある
live バックフィル、現在のプロバイダー編集、プロバイダー切り替え、テイクオーバー解除時の復元などで `modelCatalog` が空になる問題を修正しました。スナップショットバックアップは既存の `model_catalog_json` ポインターを保持します。プロバイダーから再構築されるバックアップは、データベースの信頼できる情報源からカタログ投影を再生成します。現在のプロバイダー編集時は、投影を失っている可能性のある live の逆解析結果ではなく、データベース内のモデルカタログを優先します。
-また、プロバイダー切り替え時には生成済みの Codex モデルカタログ JSON を常に更新するようになりました([#3360](https://github.com/farion1231/cc-switch/pull/3360)、[@Postroggy](https://github.com/Postroggy) に感謝)。
+また、プロバイダー切り替え時には生成済みの Codex モデルカタログ JSON を常に更新するようになりました([#3360](https://github.com/farion1231/cc-switch/pull/3360)、@Postroggy に感謝)。
### Codex Chat ツール、プラグイン、カスタムツールの復元
@@ -117,19 +117,19 @@ Codex の転送に失敗したとき、provider、model、endpoint、上流 HTTP
### Codex ネイティブ残高 / Coding Plan の認証情報検索
-ネイティブ残高と Coding Plan の照会時に、別アプリの認証情報を誤って使う問題を修正しました。各 app は自分自身のプロバイダー認証情報を解析し、別のアプリ面の認証前提を照会フローへ持ち込まなくなりました([#3355](https://github.com/farion1231/cc-switch/pull/3355)、[@SiskonEmilia](https://github.com/SiskonEmilia) に感謝)。
+ネイティブ残高と Coding Plan の照会時に、別アプリの認証情報を誤って使う問題を修正しました。各 app は自分自身のプロバイダー認証情報を解析し、別のアプリ面の認証前提を照会フローへ持ち込まなくなりました([#3355](https://github.com/farion1231/cc-switch/pull/3355)、@SiskonEmilia に感謝)。
### Codex CLI 探索とモデルカタログテンプレートのフォールバック
-サードパーティ Codex モデルカタログ投影における Codex CLI の探索パスが狭すぎる問題を修正しました。バックエンドは複数プラットフォームの一般的な Codex CLI インストール場所を探し、それでもテンプレートが見つからない場合は内蔵の GPT-5.5 モデルカタログテンプレートへフォールバックします([#3382](https://github.com/farion1231/cc-switch/pull/3382)、[@chofuhoyu](https://github.com/chofuhoyu) に感謝)。
+サードパーティ Codex モデルカタログ投影における Codex CLI の探索パスが狭すぎる問題を修正しました。バックエンドは複数プラットフォームの一般的な Codex CLI インストール場所を探し、それでもテンプレートが見つからない場合は内蔵の GPT-5.5 モデルカタログテンプレートへフォールバックします([#3382](https://github.com/farion1231/cc-switch/pull/3382)、@chofuhoyu に感謝)。
### Claude Desktop Official プロバイダー追加失敗
-Claude Desktop Official プロバイダー追加時のエラーを修正しました([#3405](https://github.com/farion1231/cc-switch/pull/3405)、[@Eunknight](https://github.com/Eunknight) に感謝)。
+Claude Desktop Official プロバイダー追加時のエラーを修正しました([#3405](https://github.com/farion1231/cc-switch/pull/3405)、@Eunknight に感謝)。
### Kimi / Moonshot ツール思考履歴の正規化
-Kimi / Moonshot を Anthropic 互換ツール思考履歴 normalizer に追加しました。後続ターンで reasoning と tool-call コンテキストを正しく再生できるようになり、履歴メッセージの形が上流要件に合わず失敗する問題を避けます([#3377](https://github.com/farion1231/cc-switch/pull/3377)、[@Neon-Wang](https://github.com/Neon-Wang) に感謝)。
+Kimi / Moonshot を Anthropic 互換ツール思考履歴 normalizer に追加しました。後続ターンで reasoning と tool-call コンテキストを正しく再生できるようになり、履歴メッセージの形が上流要件に合わず失敗する問題を避けます([#3377](https://github.com/farion1231/cc-switch/pull/3377)、@Neon-Wang に感謝)。
### Windows ツールバージョン検出
@@ -171,11 +171,11 @@ Codex は起動時に `model_catalog_json` を読み込みます。v3.16.1 で
v3.16.1 で修正を届けてくださった以下のコントリビューターに感謝します:
-- [#3360](https://github.com/farion1231/cc-switch/pull/3360): Codex プロバイダー切り替え時にモデルカタログ JSON を常に更新、[@Postroggy](https://github.com/Postroggy) に感謝。
-- [#3355](https://github.com/farion1231/cc-switch/pull/3355): ネイティブ残高 / Coding Plan 照会の認証情報を app ごとに解析、[@SiskonEmilia](https://github.com/SiskonEmilia) に感謝。
-- [#3405](https://github.com/farion1231/cc-switch/pull/3405): Claude Desktop Official プロバイダー追加エラーを修正、[@Eunknight](https://github.com/Eunknight) に感謝。
-- [#3382](https://github.com/farion1231/cc-switch/pull/3382): Codex CLI の複数プラットフォーム探索と GPT-5.5 モデルテンプレートフォールバック、[@chofuhoyu](https://github.com/chofuhoyu) に感謝。
-- [#3377](https://github.com/farion1231/cc-switch/pull/3377): Kimi / Moonshot ツール思考履歴の正規化、[@Neon-Wang](https://github.com/Neon-Wang) に感謝。
+- [#3360](https://github.com/farion1231/cc-switch/pull/3360): Codex プロバイダー切り替え時にモデルカタログ JSON を常に更新、@Postroggy に感謝。
+- [#3355](https://github.com/farion1231/cc-switch/pull/3355): ネイティブ残高 / Coding Plan 照会の認証情報を app ごとに解析、@SiskonEmilia に感謝。
+- [#3405](https://github.com/farion1231/cc-switch/pull/3405): Claude Desktop Official プロバイダー追加エラーを修正、@Eunknight に感謝。
+- [#3382](https://github.com/farion1231/cc-switch/pull/3382): Codex CLI の複数プラットフォーム探索と GPT-5.5 モデルテンプレートフォールバック、@chofuhoyu に感謝。
+- [#3377](https://github.com/farion1231/cc-switch/pull/3377): Kimi / Moonshot ツール思考履歴の正規化、@Neon-Wang に感謝。
v3.16.0 リリース後に Codex OAuth、モデルカタログ、ローカルルーティングのテイクオーバー、Chat Completions ツール呼び出しの問題を報告してくださったすべてのユーザーにも感謝します。今回の多くの修正は、実際の利用シーンから得られた再現情報に基づいています。
diff --git a/docs/release-notes/v3.16.1-zh.md b/docs/release-notes/v3.16.1-zh.md
index effdc1076..05752d355 100644
--- a/docs/release-notes/v3.16.1-zh.md
+++ b/docs/release-notes/v3.16.1-zh.md
@@ -105,7 +105,7 @@ Codex / Claude / Gemini 的供应商切换与本地路由接管开关现在共
修复 `modelCatalog` 在 live 回填、当前供应商编辑弹窗、供应商切换、关闭接管恢复等场景被清空的问题。快照备份会保留已有 `model_catalog_json` 指针;由供应商重建的备份会从数据库真相来源重新生成目录投影;编辑当前供应商时会优先使用数据库里的模型目录,而不是信任可能已经丢失投影的 live 反解结果。
-同时,供应商切换现在会始终刷新生成的 Codex 模型目录 JSON([#3360](https://github.com/farion1231/cc-switch/pull/3360),感谢 [@Postroggy](https://github.com/Postroggy))。
+同时,供应商切换现在会始终刷新生成的 Codex 模型目录 JSON([#3360](https://github.com/farion1231/cc-switch/pull/3360),感谢 @Postroggy)。
### Codex Chat 工具、插件和自定义工具恢复
@@ -117,19 +117,19 @@ Codex 转发失败时,现在返回包含 provider、model、endpoint、上游
### Codex 原生余额 / Coding Plan 查询凭据
-修复原生余额与 Coding Plan 查询时跨 app 错用凭据的问题。现在每个 app 会解析自己的供应商凭据,不再把其他应用面的认证假设带进查询流程([#3355](https://github.com/farion1231/cc-switch/pull/3355),感谢 [@SiskonEmilia](https://github.com/SiskonEmilia))。
+修复原生余额与 Coding Plan 查询时跨 app 错用凭据的问题。现在每个 app 会解析自己的供应商凭据,不再把其他应用面的认证假设带进查询流程([#3355](https://github.com/farion1231/cc-switch/pull/3355),感谢 @SiskonEmilia)。
### Codex CLI 发现与模型目录模板兜底
-修复第三方 Codex 模型目录投影对 Codex CLI 发现路径过窄的问题。现在后端会在多平台常见安装位置寻找 Codex CLI,并在仍找不到模板时使用内置 GPT-5.5 模型目录模板兜底([#3382](https://github.com/farion1231/cc-switch/pull/3382),感谢 [@chofuhoyu](https://github.com/chofuhoyu))。
+修复第三方 Codex 模型目录投影对 Codex CLI 发现路径过窄的问题。现在后端会在多平台常见安装位置寻找 Codex CLI,并在仍找不到模板时使用内置 GPT-5.5 模型目录模板兜底([#3382](https://github.com/farion1231/cc-switch/pull/3382),感谢 @chofuhoyu)。
### Claude Desktop 官方供应商添加失败
-修复添加 Claude Desktop 官方供应商时报错的问题([#3405](https://github.com/farion1231/cc-switch/pull/3405),感谢 [@Eunknight](https://github.com/Eunknight))。
+修复添加 Claude Desktop 官方供应商时报错的问题([#3405](https://github.com/farion1231/cc-switch/pull/3405),感谢 @Eunknight)。
### Kimi / Moonshot 工具思考历史规范化
-把 Kimi / Moonshot 加入 Anthropic 兼容工具思考历史 normalizer。后续轮次现在能正确重放 reasoning 与 tool-call 上下文,避免因为历史消息形态不符合上游要求而失败([#3377](https://github.com/farion1231/cc-switch/pull/3377),感谢 [@Neon-Wang](https://github.com/Neon-Wang))。
+把 Kimi / Moonshot 加入 Anthropic 兼容工具思考历史 normalizer。后续轮次现在能正确重放 reasoning 与 tool-call 上下文,避免因为历史消息形态不符合上游要求而失败([#3377](https://github.com/farion1231/cc-switch/pull/3377),感谢 @Neon-Wang)。
### Windows 工具版本探测
@@ -171,11 +171,11 @@ Codex 在启动时读取 `model_catalog_json`。因此即使 v3.16.1 已修复
感谢以下贡献者在 v3.16.1 中提交修复:
-- [#3360](https://github.com/farion1231/cc-switch/pull/3360):Codex 供应商切换时始终更新模型目录 JSON,感谢 [@Postroggy](https://github.com/Postroggy)。
-- [#3355](https://github.com/farion1231/cc-switch/pull/3355):原生余额 / Coding Plan 查询按 app 解析凭据,感谢 [@SiskonEmilia](https://github.com/SiskonEmilia)。
-- [#3405](https://github.com/farion1231/cc-switch/pull/3405):修复 Claude Desktop 官方供应商添加报错,感谢 [@Eunknight](https://github.com/Eunknight)。
-- [#3382](https://github.com/farion1231/cc-switch/pull/3382):Codex CLI 多平台发现与 GPT-5.5 模型模板兜底,感谢 [@chofuhoyu](https://github.com/chofuhoyu)。
-- [#3377](https://github.com/farion1231/cc-switch/pull/3377):Kimi / Moonshot 工具思考历史规范化,感谢 [@Neon-Wang](https://github.com/Neon-Wang)。
+- [#3360](https://github.com/farion1231/cc-switch/pull/3360):Codex 供应商切换时始终更新模型目录 JSON,感谢 @Postroggy。
+- [#3355](https://github.com/farion1231/cc-switch/pull/3355):原生余额 / Coding Plan 查询按 app 解析凭据,感谢 @SiskonEmilia。
+- [#3405](https://github.com/farion1231/cc-switch/pull/3405):修复 Claude Desktop 官方供应商添加报错,感谢 @Eunknight。
+- [#3382](https://github.com/farion1231/cc-switch/pull/3382):Codex CLI 多平台发现与 GPT-5.5 模型模板兜底,感谢 @chofuhoyu。
+- [#3377](https://github.com/farion1231/cc-switch/pull/3377):Kimi / Moonshot 工具思考历史规范化,感谢 @Neon-Wang。
也感谢所有在 v3.16.0 发布后反馈 Codex OAuth、模型目录、本地路由接管和 Chat Completions 工具调用问题的用户。很多补丁都来自这些真实使用场景里的复现线索。
diff --git a/docs/release-notes/v3.16.2-en.md b/docs/release-notes/v3.16.2-en.md
new file mode 100644
index 000000000..df5e3105d
--- /dev/null
+++ b/docs/release-notes/v3.16.2-en.md
@@ -0,0 +1,347 @@
+# CC Switch v3.16.2
+
+> Following the v3.16.1 Codex stability patch, this release mainly broadens data portability and usage observability — adding S3-compatible cloud sync, OpenCode session usage sync, and an official-subscription quota template — while continuing to harden Codex's Chat Completions routing for third-party providers, fixing a batch of Windows / macOS platform issues, adding the CherryIN and ZenMux providers, and fully refreshing the trilingual user manual.
+
+**[中文版 →](v3.16.2-zh.md) | [日本語版 →](v3.16.2-ja.md)**
+
+---
+
+## Usage Guides
+
+This release adds an S3 backend for cloud sync and more usage data sources. If you want to use them, start with these docs:
+
+- **[Settings](../user-manual/en/1-getting-started/1.5-settings.md)**: configure cloud sync (WebDAV / S3-compatible storage) on the settings page to back up and restore providers, MCP, prompts, skills, and other config across multiple devices.
+- **[Usage Statistics](../user-manual/en/4-proxy/4.4-usage.md)**: understand the Usage Dashboard's data sources (proxy logs, Codex / Gemini / OpenCode session sync) and how the statistics are counted.
+
+---
+
+> [!WARNING]
+>
+> ## Only Official Channels (Please Read)
+>
+> CC Switch is a **fully free and open-source** desktop app, and we **do not charge users any fees**. Please only obtain the software through the official channels listed below:
+>
+> | Channel | Only Official |
+> | ------------------ | ------------------------------------------------------------------------------ |
+> | Website | **[ccswitch.io](https://ccswitch.io)** |
+> | Source | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
+> | Downloads | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
+> | Author | **[@farion1231](https://github.com/farion1231)** |
+> | Report an Imposter | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
+>
+> **Any "CC Switch" website or client that asks you for payment, top-ups, or login credentials is fake.** If you have been tricked into paying, stop the transaction immediately and file a report through GitHub Issues.
+
+---
+
+## Overview
+
+CC Switch v3.16.2 is a maintenance update following v3.16.1. After the previous release focused on the security of Codex official authentication and local routing takeover, this release concentrates on two things. First, broadening data portability and usage observability — adding S3-compatible cloud sync (a second cloud-backup backend alongside WebDAV), OpenCode session usage sync, and a quota-statistics template for official subscriptions. Second, continuing to polish the edges exposed when Codex routes third-party providers through Chat Completions — stream-truncation detection, `tool_choice` when tools is empty, custom-tool metadata, reasoning-token statistics, file / audio attachment conversion, and more.
+
+This release also fixes a batch of local proxy robustness issues (ephemeral port resolution, the takeover placeholder restore loop, Anthropic `system` message normalization, the upstream 413 message, and Claude Desktop's `[1m]` model routing), addresses several Windows / macOS platform experience issues, adds the CherryIN and ZenMux providers, and fully refreshes the trilingual user manual.
+
+**Release date**: 2026-06-07
+
+**Stats**: 41 commits | 132 files changed | +11,116 / -1,636 lines
+
+---
+
+## Highlights
+
+- **S3-compatible cloud sync**: adds S3-compatible object storage as a second cloud-backup backend alongside WebDAV, with one-click presets for AWS S3, MinIO, Cloudflare R2, Alibaba Cloud OSS, Tencent Cloud COS, Huawei OBS, and more.
+- **More usage data sources**: added OpenCode session usage sync, plus an official-subscription quota template for Claude / Codex / Gemini official providers (explicit toggle, off by default).
+- **Continued Codex Chat Completions routing hardening**: fixed stream-truncation misdetection, `tool_choice` rejection when tools is empty, custom-tool metadata loss, and missing reasoning-token stats, and added file / audio attachment conversion plus a `/v1/models` reachability endpoint.
+- **A more robust local proxy**: fixed ephemeral port (port 0) resolution, the takeover placeholder restore loop, Anthropic `system` message normalization, the upstream 413 message, and Claude Desktop 1M-context model routing.
+- **Platform and providers**: fixed Windows tray / taskbar icons, subdirectory skill updates, and macOS input auto-capitalization, and added the CherryIN and ZenMux providers.
+
+---
+
+## Added
+
+### S3-Compatible Cloud Sync
+
+Cloud Sync now supports S3-compatible object storage as a second backend alongside WebDAV, signing requests with a self-implemented AWS Signature V4 for the broadest possible compatibility. The settings page offers one-click presets for AWS S3, MinIO, Cloudflare R2, Alibaba Cloud OSS, Tencent Cloud COS, Huawei OBS, and a custom endpoint, with connection testing, manual upload / download, and auto-sync on configuration changes (the providers, endpoint, MCP, prompt, skill, settings, and proxy tables — **not** high-frequency data like usage logs). Enabling S3 sync disables a running WebDAV sync and vice versa (#1351).
+
+### OpenCode Session Usage Sync
+
+Added OpenCode as a usage-statistics source that reads per-message token, cost, and model data from OpenCode's local SQLite database and imports it into the usage records, with a dedicated "OpenCode" app filter tab and an "OpenCode Session" data-source label. The database path respects `OPENCODE_DB` and `XDG_DATA_HOME` (defaulting to `~/.local/share/opencode` on all platforms), only finalized messages are imported, and the freshness check includes the WAL file so just-written sessions are not skipped (#3215).
+
+### Official Subscription Quota Template
+
+Because some users were concerned that the IP issuing the usage query could differ from the IP issuing in-app requests, risking an account ban, the official-subscription usage template for Claude / Codex / Gemini official providers is now an explicit, opt-in template that queries plan quota via CLI / OAuth credentials, replacing the previous implicit auto-query for official providers. The template is off by default, is enabled from the usage-script modal, and supports a configurable refresh interval. When using this feature, enabling the proxy's TUN mode is recommended.
+
+### Text-Only Model Image Fallback Rectifier
+
+Added a proxy rectifier that replaces Anthropic image blocks with an `[Unsupported Image]` placeholder when the routed model is text-only (declared, or detected by a built-in model-name heuristic) or the upstream rejects image input, so conversations are not interrupted. The settings page provides a toggle for this fallback, plus a separate toggle for the heuristic detection (which can be turned off to avoid misjudging multimodal models).
+
+### ZenMux Token Plan Provider
+
+Added ZenMux as a Token Plan Coding Plan provider. You can manually enter its API key and base URL in the usage-script modal, and it renders used / quota in USD (#2709).
+
+### CherryIN Preset
+
+Added the CherryIN aggregator gateway as a quick-config preset across all 7 managed apps — Claude Code / Claude Desktop / OpenClaw / Hermes use the Anthropic-format endpoint (open.cherryin.net), OpenCode uses `@ai-sdk/anthropic` (`/v1`), Codex uses the OpenAI-compatible endpoint, and Gemini CLI uses the Gemini-compatible endpoint — with the official brand icon, placed next to AiHubMix (#3643).
+
+### Codex CLI Reachability Endpoint `/v1/models`
+
+The local proxy now responds to `GET /v1/models`, which Codex CLI probes at startup, returning the CC Switch-managed Codex model catalog. A stale-catalog guard was added: it parses the live `config.toml` and only serves the catalog when `model_catalog_json` still points at the CC Switch-owned catalog file, avoiding exposing a previous provider's leftover catalog to Codex (#3818).
+
+### Codex Chat File and Audio Attachments
+
+Codex's Responses→Chat conversion now maps `input_file` parts (carrying `file_id` or inline `file_data`) and `input_audio` parts into their Chat Completions equivalents, and emits top-level `input_*` items that were previously dropped, so file and audio attachments reach Chat-only Codex upstreams.
+
+---
+
+## Changed
+
+### Usage Dashboard Hero Redesign
+
+Rearranged the Usage Dashboard hero and summary cards into a more compact layout, consolidating the real-token total, request count, and cost into a single top row (#3426).
+
+### SSSAiCode Endpoint Refresh
+
+Updated the SSSAiCode preset's website, signup, and API base URLs to the `sssaicodeapi.com` domain, and refreshed its candidate endpoint nodes (default `node-hk.sssaicodeapi.com`, plus `node-hk.sssaiapi.com` and `node-cf.sssaicodeapi.com`) across all 7 app presets.
+
+---
+
+## Fixed
+
+### Codex Chat Stream Truncation Detection
+
+When a Chat Completions upstream ends a stream without a `finish_reason` or `[DONE]`, CC Switch no longer treats it as a normal completion: it finalizes normally only when the stream truly ended; emits an incomplete (`max_output_tokens`) response when partial output was produced; and emits a failed `stream_truncated` event when nothing was produced. Late-arriving reasoning is also backfilled onto still-active streaming tool calls.
+
+### Codex Chat `tool_choice` Without Tools
+
+The Responses→Chat conversion now drops `tool_choice` and `parallel_tool_calls` when the final tools array is missing or empty (including when all tools are filtered out), avoiding 503/400 errors from strict OpenAI-compatible upstreams (vLLM, enterprise gateways) with "When using `tool_choice`, `tools` must be set." (#3640).
+
+### Codex Custom Tool Metadata Preserved
+
+Custom Codex tools (such as the freeform `apply_patch` tool) now embed their full original definition — including format and grammar metadata — as a compact, order-stable JSON block in the generated Chat function description, instead of being replaced with a generic placeholder, so they remain usable on Chat Completions upstreams (#3644).
+
+### Codex Chat Usage Missing `reasoning_tokens`
+
+The Chat→Responses usage conversion now always includes `output_tokens_details.reasoning_tokens` (defaulting to 0), even when a provider omits `completion_tokens_details` or returns a non-object, satisfying Codex CLI's strict requirement and avoiding repeated response-parse failures and retries (#3514).
+
+### Cross-Turn Reasoning for Codex Custom / Search Tools
+
+The cross-turn reasoning cache in Codex Chat history now covers the full tool-call set (`function_call`, `custom_tool_call`, `tool_search_call`) and their outputs, not just plain function calls, so `apply_patch` and tool-search calls keep their own `reasoning_content` when restored via `previous_response_id`.
+
+### Ephemeral Port (port 0) Resolution
+
+When the proxy is configured to listen on port 0 (OS-assigned), takeover now starts the proxy first to obtain the real port before writing live configs and the database, avoiding client URLs pointing at an invalid `:0` address; if no concrete port has been resolved yet, the Claude Desktop gateway URL is rejected outright.
+
+### Proxy Placeholder Backup / Restore Loop
+
+If a previous proxy stop failed to restore the original live config and left proxy placeholders in live, taking over again no longer overwrites the good backup with the proxy config, and restore no longer writes the placeholder back to live: both paths detect the placeholder state and rebuild live from the current provider as the source of truth, fixing cases where the proxy toggle became a no-op and the client was pinned to the local proxy address (#3689).
+
+### Provider Switching Wrongly Blocked During Proxy Takeover
+
+During local routing takeover, only providers explicitly classified as official are now blocked from switching, instead of also disabling custom providers whose endpoint lives in meta or whose fields are simply unfilled. The disabled "Enable" button now shows a lighter hint tooltip instead of the previous red "Blocked" badge.
+
+### localhost Listen Address Normalization
+
+When saving the proxy with a listen address of `localhost`, it is now normalized to `127.0.0.1` before persisting, avoiding binding inconsistencies (#3016).
+
+### Anthropic `system` Message Normalization
+
+For Anthropic-format providers, system-role entries inside the `messages` array are now collapsed and merged into the top-level `system` field (preserving original order and any existing top-level system), avoiding strict upstreams rejecting non-leading system messages; OpenAI Chat routing is unaffected (#3775).
+
+### Claude Desktop 1M-Context Model Routing
+
+Claude Desktop appends a `[1m]` marker to the model name when the 1M-context beta is active (e.g. `claude-opus-4-8[1m]`). The proxy now strips that suffix before route matching so exact, alias, legacy, and role-keyword matching all resolve correctly, fixing `route_unknown` (HTTP 400) failures when switching to a 1M model mid-conversation; the original model name is still kept in the `route_unknown` error for diagnostics.
+
+### Codex 413 Error Message
+
+When a Codex upstream gateway rejects an oversized request body with HTTP 413, the proxy now returns a dedicated message explaining that this is the provider's server-side body-size limit (not a CC Switch local limit), with actionable recovery steps (run `/compact`, remove large logs or inline images, or ask the provider to raise the limit), instead of echoing the upstream's raw HTML error page.
+
+### Proxy Panel Error Detail
+
+When toggling proxy takeover fails, the proxy panel toast now includes the specific error detail returned by the backend, instead of only a generic failure message (#3656).
+
+### Copilot Infinite-Whitespace Threshold
+
+Raised the streaming infinite-whitespace abort threshold from 20 to 500 consecutive whitespace characters, avoiding false aborts of legitimate tool calls whose arguments contain deeply indented code (Python, YAML, Rust, Markdown), while still catching the real Copilot infinite-whitespace bug (#2647).
+
+### Subscription Tier Tray Rendering
+
+Via a unified tier-to-label mapping, fixed rendering of official subscription tiers in the tray and quota display: Claude / Codex no longer drop the 7-day window, Gemini Pro / Flash / Flash-Lite tiers no longer leak raw machine names, and multi-window plans (e.g. Opus + Sonnet) now show the worst utilization instead of the first match.
+
+### Inflated Claude Stream input_tokens
+
+Some Anthropic-compatible streaming providers (e.g. Qwen, MiniMax) report the full context as `input_tokens` in `message_start`, double-counting the cached portion already reported separately and artificially lowering the displayed cache hit rate. The parser now prefers the smaller positive `input_tokens` from `message_delta` and adopts the paired cache counts from the same usage block; native Claude and OpenRouter-converted paths are unchanged.
+
+### Zhipu Quota Query Endpoint Routing
+
+The Zhipu Coding Plan quota query was hard-coded to `api.z.ai`, so users on the mainland preset (`open.bigmodel.cn`) could not retrieve usage when the international endpoint was unreachable. The quota request now routes to the host matching the user's configured base URL (#3702).
+
+### MiniMax Balance API and Pricing
+
+Adapted MiniMax Coding Plan quota to its new balance API (which returns remaining-percent fields instead of the usage counts the old parser relied on, which left tiers empty and the tray showing no usage), filtered out non-coding models (such as video), handled plans without a weekly limit, and added default pricing for the MiniMax M3 model (#3518).
+
+### GLM Coding Plan Endpoints and Model Fetch
+
+Fixed the Zhipu / Z.AI GLM Coding Plan presets to the `/api/coding/paas/v4` endpoints (covering Codex, OpenCode, OpenClaw, Hermes), and made the model-list probe query `{base}/models` first for base URLs that already end in a `/v{N}` version segment (keeping `/v1/models` as a fallback), so the "Fetch models" button no longer 404s on versioned endpoints (#3524).
+
+### Codex Model Catalog Path Portability
+
+Codex now writes only the relative filename `cc-switch-model-catalog.json` to `config.toml` instead of an absolute path (Codex CLI resolves it from the config directory), fixing the model catalog breaking on WSL and symlinked setups where the absolute path could not be translated (#3614).
+
+### APINebula's OpenCode SDK
+
+The APINebula OpenCode preset now loads `@ai-sdk/openai-compatible` instead of `@ai-sdk/openai`, so requests use the OpenAI Chat Completions format the relay expects, rather than the Responses API that fails against chat-completions-only upstreams.
+
+### Windows Tray Icon Residue After Exit
+
+On Windows, quitting CC Switch could leave a dead tray icon behind until the mouse passed over it. The app now explicitly removes the tray icon before exiting, so it disappears cleanly when the process ends (#3797).
+
+### Windows Taskbar Icon
+
+Sets an explicit Windows AppUserModelID at runtime and writes the same ID and product icon onto the installer's desktop and start-menu shortcuts, so CC Switch shows the correct icon and groups properly in the taskbar (#3457).
+
+### Windows Update Check for Subdirectory Skills
+
+When scanning installed skills on Windows, backslash path separators are now normalized to forward slashes, so skills nested in subdirectories (e.g. `skills/my-skill`) are matched by the update check instead of being silently skipped (#3430).
+
+### macOS Input Auto-Capitalization
+
+Disabled autocomplete, autocorrect, autocapitalize, and spellcheck on the shared text Input component, so macOS no longer auto-capitalizes or auto-corrects the first letter typed into configuration fields (#3626).
+
+### Codex VS Code Session Previews
+
+For Codex requests sent from VS Code, the session preview could show selection or open-file content instead of the real prompt when a markdown heading preceded the injected request. The backend title and frontend preview now both match the last "## My request for Codex:" heading (the IDE injects the real request as the final section), so the preview reflects the user's prompt (#3593).
+
+### VS Code Wording in the Chinese UI
+
+Corrected the "Apply to Claude Code plugin" description in Simplified and Traditional Chinese to write "VS Code" properly instead of "Vscode", aligning with the English and Japanese strings (#3228).
+
+---
+
+## Documentation
+
+### User Manual Refresh
+
+Refreshed the README localizations and the en / zh / ja user manuals to reflect all 7 managed apps (adding Claude Desktop and Hermes to the intro and overview copy), corrected the OpenCode config path to `~/.config/opencode/` (`opencode.json`), documented Hermes config files, updated the language docs to four languages, corrected per-app MCP / prompt / skill support, noted that export now produces a timestamped SQL backup that includes usage logs, and documented the pricing model-ID matching rules (#3411).
+
+### Codex Official Auth Preservation Guide
+
+Added a Chinese / English / Japanese guide explaining how to keep Codex official remote control and official plugins working while routing model traffic to third-party APIs, and linked it from the v3.16.1 release notes.
+
+### README Links and Sponsor Markup
+
+Updated the Release Notes links in each language README to v3.16.1, and fixed broken curly-quote characters in the README_ZH sponsor blocks so their HTML attributes render correctly (#3772).
+
+---
+
+## Upgrade Notes
+
+### S3 and WebDAV Cloud Sync Are Mutually Exclusive
+
+Cloud Sync runs only one backend at a time. Enabling S3 auto-sync disables a running WebDAV auto-sync and vice versa. If you previously used WebDAV, make sure both ends are aligned before switching to S3, so you don't assume the old backend is still backing up.
+
+### Restart Codex After Editing Model Mappings
+
+Codex reads `model_catalog_json` at startup. Even though this release rewrites the model catalog to a relative path and adds the `/v1/models` reachability endpoint, you still need to restart Codex after editing the model mapping table for the `/model` menu to refresh.
+
+---
+
+## Risk Notice
+
+This release continues the risk notices from previous versions for reverse-proxy-style features.
+
+**Codex OAuth reverse proxy**: using a ChatGPT subscription's Codex OAuth through a reverse proxy may violate OpenAI's terms of service. See the [v3.13.0 release notes](v3.13.0-en.md#️-risk-notice) for details.
+
+**Codex third-party provider Chat routing**: when CC Switch local proxy converts and forwards Codex requests to third-party providers, each provider may have different requirements for billing, compliance, and data retention. Read the target provider's terms before use.
+
+**Claude Desktop third-party provider proxy switching**: when CC Switch's built-in proxy gateway forwards Claude Desktop requests to third-party providers, you must also follow the target provider's billing, compliance, and data-retention terms.
+
+By enabling these features, users accept the related risks. CC Switch is not responsible for account restrictions, warnings, or service suspensions caused by using these features.
+
+---
+
+## Thanks
+
+Thanks to the following contributors for the features and fixes in v3.16.2:
+
+- [#1351](https://github.com/farion1231/cc-switch/pull/1351): add S3-compatible cloud storage sync, thanks @keithyt06.
+- [#3215](https://github.com/farion1231/cc-switch/pull/3215): add OpenCode session usage sync, thanks @nothingness0db.
+- [#2709](https://github.com/farion1231/cc-switch/pull/2709): add the ZenMux Token Plan provider, thanks @Eter365.
+- [#3643](https://github.com/farion1231/cc-switch/pull/3643): add the CherryIN preset provider, thanks @zhibisora.
+- [#3818](https://github.com/farion1231/cc-switch/pull/3818): add the Codex CLI reachability `GET /v1/models` endpoint, thanks @CSberlin.
+- [#3426](https://github.com/farion1231/cc-switch/pull/3426): Usage Dashboard hero redesign, thanks @allenxu09.
+- [#3640](https://github.com/farion1231/cc-switch/pull/3640): drop `tool_choice` when tools is empty, thanks @Postroggy.
+- [#3644](https://github.com/farion1231/cc-switch/pull/3644): preserve Codex custom tool metadata in chat routing, thanks @LanternCX.
+- [#3514](https://github.com/farion1231/cc-switch/pull/3514): always include `reasoning_tokens` in Chat→Responses, thanks @yeeyzy.
+- [#3689](https://github.com/farion1231/cc-switch/pull/3689): skip backup / restore when live is already a proxy placeholder, thanks @YongmaoLuo.
+- [#3016](https://github.com/farion1231/cc-switch/pull/3016): normalize the localhost listen address, thanks @Alexlangl.
+- [#3775](https://github.com/farion1231/cc-switch/pull/3775): normalize Anthropic `system` messages, thanks @Dearli666.
+- [#3656](https://github.com/farion1231/cc-switch/pull/3656): improve error message display in the proxy panel, thanks @lzcndm.
+- [#2647](https://github.com/farion1231/cc-switch/pull/2647): raise the infinite-whitespace threshold 20 → 500, thanks @NiuBlibing.
+- [#3702](https://github.com/farion1231/cc-switch/pull/3702): route the Zhipu quota query to the configured base URL, thanks @YongmaoLuo.
+- [#3518](https://github.com/farion1231/cc-switch/pull/3518): adapt to the MiniMax new balance API and default pricing, thanks @LaoYueHanNi.
+- [#3524](https://github.com/farion1231/cc-switch/pull/3524): fix the Zhipu Coding Plan presets and model probing for versioned endpoints, thanks @makoMakoGo.
+- [#3614](https://github.com/farion1231/cc-switch/pull/3614): use a relative filename for the model catalog, thanks @steponeerror.
+- [#3797](https://github.com/farion1231/cc-switch/pull/3797): fix the Windows tray icon residue after exit, thanks @iAJue.
+- [#3457](https://github.com/farion1231/cc-switch/pull/3457): fix the Windows taskbar icon, thanks @ZhangNanNan1018.
+- [#3430](https://github.com/farion1231/cc-switch/pull/3430): normalize Windows path separators to match subdirectory skill updates, thanks @Ninthless.
+- [#3626](https://github.com/farion1231/cc-switch/pull/3626): disable macOS input auto-capitalization, thanks @ZHLHZHU.
+- [#3593](https://github.com/farion1231/cc-switch/pull/3593): fix Codex VS Code session previews, thanks @xwil1.
+- [#3228](https://github.com/farion1231/cc-switch/pull/3228): align the VS Code wording in the Chinese UI, thanks @Games55k.
+- [#3411](https://github.com/farion1231/cc-switch/pull/3411): refresh the user manual to reflect current app support, thanks @makoMakoGo.
+- [#3772](https://github.com/farion1231/cc-switch/pull/3772): fix README release-note links and sponsor markup, thanks @null-easy.
+
+Thanks also to everyone who reported Codex Chat routing, local proxy takeover, usage statistics, and platform compatibility issues after v3.16.1. Many of these fixes came directly from real-world reproduction details.
+
+---
+
+## Download & Install
+
+Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) and download the build for your system.
+
+### System Requirements
+
+| System | Minimum Version | Architecture |
+| ------- | ------------------------ | ----------------------------------- |
+| Windows | Windows 10 and later | x64 |
+| macOS | macOS 12 (Monterey)+ | Intel (x64) / Apple Silicon (arm64) |
+| Linux | See table below | x64 / ARM64 |
+
+### Windows
+
+| File | Description |
+| ---------------------------------------- | ------------------------------------------------ |
+| `CC-Switch-v3.16.2-Windows.msi` | **Recommended** - MSI installer with auto-update |
+| `CC-Switch-v3.16.2-Windows-Portable.zip` | Portable build, unzip and run |
+
+### macOS
+
+| File | Description |
+| -------------------------------- | ----------------------------------------------------- |
+| `CC-Switch-v3.16.2-macOS.dmg` | **Recommended** - DMG installer, drag to Applications |
+| `CC-Switch-v3.16.2-macOS.zip` | Unzip and drag to Applications, Universal Binary |
+| `CC-Switch-v3.16.2-macOS.tar.gz` | For Homebrew install and auto-update |
+
+Homebrew install:
+
+```bash
+brew install --cask cc-switch
+```
+
+Upgrade:
+
+```bash
+brew upgrade --cask cc-switch
+```
+
+### Linux
+
+Linux assets are available for both **x86_64** and **ARM64** (`aarch64`). Choose the file whose architecture tag matches your machine's `uname -m` output:
+
+- `CC-Switch-v3.16.2-Linux-x86_64.AppImage` / `.deb` / `.rpm`
+- `CC-Switch-v3.16.2-Linux-arm64.AppImage` / `.deb` / `.rpm`
+
+| Distribution | Recommended Format | Install Command |
+| --------------------------------------- | ------------------ | --------------------------------------------------------------------- |
+| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
+| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
+| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
+| Arch Linux / Manjaro | `.AppImage` | Make executable and run directly, or use AUR |
+| Other distributions / unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
diff --git a/docs/release-notes/v3.16.2-ja.md b/docs/release-notes/v3.16.2-ja.md
new file mode 100644
index 000000000..095c26f98
--- /dev/null
+++ b/docs/release-notes/v3.16.2-ja.md
@@ -0,0 +1,347 @@
+# CC Switch v3.16.2
+
+> v3.16.1 の Codex 安定性パッチに続き、本リリースはデータの可搬性と用量の可観測性の拡張を主眼としています。S3 互換クラウド同期、OpenCode セッション用量同期、公式サブスクリプション残量テンプレートを追加し、Codex がサードパーティプロバイダーを Chat Completions ルーティングする際の堅牢性を引き続き強化しました。あわせて Windows / macOS のプラットフォーム問題を一括修正し、CherryIN・ZenMux プロバイダーを追加し、3 言語のユーザーマニュアルを全面的に刷新しました。
+
+**[English →](v3.16.2-en.md) | [中文 →](v3.16.2-zh.md)**
+
+---
+
+## 利用ガイド
+
+本リリースではクラウド同期の S3 バックエンドと、より多くの用量統計ソースを追加しました。利用したい場合は、まず以下のドキュメントをご覧ください:
+
+- **[設定](../user-manual/ja/1-getting-started/1.5-settings.md)**: 設定ページでクラウド同期(WebDAV / S3 互換ストレージ)を構成し、プロバイダー、MCP、プロンプト、スキルなどの設定を複数デバイス間でバックアップ・復元します。
+- **[用量統計](../user-manual/ja/4-proxy/4.4-usage.md)**: 用量ダッシュボードのデータソース(プロキシログ、Codex / Gemini / OpenCode セッション同期)と統計の数え方を確認できます。
+
+---
+
+> [!WARNING]
+>
+> ## 唯一の公式チャネル(必ずお読みください)
+>
+> CC Switch は**完全に無料・オープンソース**のデスクトップアプリで、**ユーザーから料金を徴収することはありません**。本ソフトウェアは下記の公式チャネルからのみ入手してください:
+>
+> | チャネル | 唯一の公式 |
+> | ------------ | ------------------------------------------------------------------------------ |
+> | 公式サイト | **[ccswitch.io](https://ccswitch.io)** |
+> | ソースコード | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
+> | ダウンロード | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
+> | 作者 | **[@farion1231](https://github.com/farion1231)** |
+> | 偽サイト通報 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
+>
+> **料金請求・チャージ・認証情報の提供を求める「CC Switch」サイトやクライアントはすべて偽物です。** 支払いを誘導された場合は直ちに操作を中止し、GitHub Issues からご報告ください。
+
+---
+
+## 概要
+
+CC Switch v3.16.2 は v3.16.1 に続くメンテナンスアップデートです。前リリースでは Codex 公式認証とローカルルーティングのテイクオーバーのセキュリティ問題に集中しましたが、本リリースは 2 点に重きを置いています。1 つ目はデータの可搬性と用量の可観測性の拡張で、S3 互換クラウド同期(WebDAV に並ぶ 2 つ目のクラウドバックアップバックエンド)、OpenCode セッション用量同期、公式サブスクリプション向けの残量統計テンプレートを追加しました。2 つ目は、Codex がサードパーティプロバイダーを Chat Completions ルーティングする際に露呈したエッジケースの継続的な改善で、ストリーム切断の判定、tools が空のときの `tool_choice`、カスタムツールのメタデータ、推論トークン統計、ファイル / 音声添付の変換などです。
+
+本リリースではローカルプロキシの堅牢性に関する問題(一時ポートの解決、テイクオーバーのプレースホルダー復元ループ、Anthropic `system` メッセージの正規化、上流 413 の文言、Claude Desktop の `[1m]` モデルルーティング)を一括修正し、いくつかの Windows / macOS のプラットフォーム体験の問題に対処し、CherryIN・ZenMux の 2 プロバイダーを追加し、3 言語のユーザーマニュアルを全面的に刷新しました。
+
+**リリース日**: 2026-06-07
+
+**Stats**: 41 commits | 132 files changed | +11,116 / -1,636 lines
+
+---
+
+## ハイライト
+
+- **S3 互換クラウド同期**: WebDAV に並ぶ 2 つ目のクラウドバックアップバックエンドとして S3 互換オブジェクトストレージを追加。AWS S3、MinIO、Cloudflare R2、Alibaba Cloud OSS、Tencent Cloud COS、Huawei OBS などのワンクリックプリセットを内蔵します。
+- **より多くの用量データソース**: OpenCode セッション用量同期と、Claude / Codex / Gemini 公式プロバイダー向けの公式サブスクリプション残量テンプレート(明示的なトグル、デフォルトでオフ)を追加しました。
+- **Codex Chat Completions ルーティングの継続的な強化**: ストリーム切断の誤判定、tools が空のときの `tool_choice` 拒否、カスタムツールメタデータの欠落、推論トークン統計の欠落を修正し、ファイル / 音声添付の変換と `/v1/models` 到達性エンドポイントを追加しました。
+- **より堅牢なローカルプロキシ**: 一時ポート(port 0)の解決、テイクオーバーのプレースホルダー復元ループ、Anthropic `system` メッセージの正規化、上流 413 の文言、Claude Desktop の 1M コンテキストモデルルーティングを修正しました。
+- **プラットフォームとプロバイダー**: Windows のトレイ / タスクバーアイコン、サブディレクトリスキルの更新、macOS の入力自動大文字化を修正し、CherryIN・ZenMux プロバイダーを追加しました。
+
+---
+
+## 追加機能
+
+### S3 互換クラウド同期
+
+クラウド同期は WebDAV に並ぶ 2 つ目のバックエンドとして S3 互換オブジェクトストレージに対応しました。署名は自前実装の AWS Signature V4 を用い、できるだけ多くのサービスと互換性を持たせています。設定ページでは AWS S3、MinIO、Cloudflare R2、Alibaba Cloud OSS、Tencent Cloud COS、Huawei OBS、およびカスタム endpoint のワンクリックプリセットを提供し、接続テスト、手動アップロード / ダウンロード、設定変更時の自動同期(providers、endpoint、MCP、プロンプト、スキル、設定、プロキシなどの設定テーブル。用量ログのような高頻度書き込みデータは**含みません**)に対応します。S3 同期を有効化すると、実行中の WebDAV 同期は停止し、その逆も同様です(#1351)。
+
+### OpenCode セッション用量同期
+
+OpenCode を用量統計のソースとして追加しました。OpenCode のローカル SQLite データベースからメッセージごとの token、コスト、モデルのデータを読み取り、用量レコードへインポートします。専用の「OpenCode」アプリフィルタタブと「OpenCode Session」データソースラベルを備えます。データベースパスは `OPENCODE_DB` と `XDG_DATA_HOME` を尊重し(全プラットフォームで既定は `~/.local/share/opencode`)、完了済みのメッセージのみをインポートし、新鮮度判定で WAL ファイルも含めるため、書き込み直後のセッションがスキップされません(#3215)。
+
+### 公式サブスクリプション残量テンプレート
+
+用量照会を発行する IP とアプリ内リクエストを発行する IP が異なるとアカウント停止のリスクがある、という一部ユーザーの懸念を受けて、Claude / Codex / Gemini 公式プロバイダー向けに、CLI / OAuth 認証情報でプラン残量を照会する明示的・任意の「公式サブスクリプション」用量テンプレートを追加し、これまでの公式プロバイダーに対する暗黙の自動照会を置き換えました。このテンプレートはデフォルトでオフで、用量スクリプトのモーダルから有効化でき、更新間隔を設定できます。本機能を利用する際は、プロキシの TUN モードを有効化することを推奨します。
+
+### テキスト専用モデルの画像フォールバック整流器
+
+ルーティング先のモデルがテキスト専用(明示的な宣言、または内蔵のモデル名ヒューリスティックで判定)の場合、または上流が画像入力を拒否する場合に、Anthropic の画像ブロックを `[Unsupported Image]` プレースホルダーへ置き換えるプロキシ整流器を追加し、会話の中断を防ぎます。設定ページにこのフォールバックのトグルを用意し、さらにヒューリスティック検出を制御する別のトグル(マルチモーダルモデルの誤判定を避けるためオフにできます)を用意しました。
+
+### ZenMux Token Plan プロバイダー
+
+ZenMux を Token Plan 系の Coding Plan プロバイダーとして追加しました。用量スクリプトのモーダルで API key と base URL を手動入力でき、使用量 / 残量を米ドル建てでリッチに表示します(#2709)。
+
+### CherryIN プリセット
+
+CherryIN アグリゲーターゲートウェイをクイック設定プリセットとして、受管 7 アプリすべてに追加しました。Claude Code / Claude Desktop / OpenClaw / Hermes は Anthropic 形式の endpoint(open.cherryin.net)、OpenCode は `@ai-sdk/anthropic`(`/v1`)、Codex は OpenAI 互換 endpoint、Gemini CLI は Gemini 互換 endpoint を使用します。公式ブランドアイコン付きで、AiHubMix の隣に配置されます(#3643)。
+
+### Codex CLI 到達性エンドポイント `/v1/models`
+
+ローカルプロキシは、Codex CLI が起動時にプローブする `GET /v1/models` に応答し、CC Switch が管理する Codex モデルカタログを返すようになりました。あわせて古いカタログのガードを追加: live の `config.toml` を解析し、`model_catalog_json` が CC Switch 所有のカタログファイルを指している場合のみ提供することで、前のプロバイダーが残したカタログを Codex に見せてしまうことを防ぎます(#3818)。
+
+### Codex Chat のファイル・音声添付
+
+Codex の Responses→Chat 変換は、`input_file`(`file_id` またはインライン `file_data` を持つ)と `input_audio` のコンテンツ部分を Chat Completions の対応形態へマッピングし、これまで破棄されていたトップレベルの `input_*` 項目も出力するようになりました。これにより、ファイルと音声の添付が Chat のみ対応の Codex 上流へ届きます。
+
+---
+
+## 変更
+
+### 用量ダッシュボードのヒーロー再設計
+
+用量ダッシュボードのヒーロー領域とサマリーカードをよりコンパクトなレイアウトに再構成し、実トークン総量、リクエスト数、コストを最上部の 1 行にまとめました(#3426)。
+
+### SSSAiCode エンドポイント刷新
+
+SSSAiCode プリセットの公式サイト、登録、API base URL を `sssaicodeapi.com` ドメインへ更新し、endpoint 候補ノード(既定 `node-hk.sssaicodeapi.com`、ほかに `node-hk.sssaiapi.com` と `node-cf.sssaicodeapi.com`)を全 7 アプリのプリセットで刷新しました。
+
+---
+
+## 修正
+
+### Codex Chat ストリーム切断の判定
+
+Chat Completions 上流が `finish_reason` も `[DONE]` もなくストリームを終了した場合、CC Switch はこれを正常完了として扱わなくなりました: 本当に終了したときのみ正常に締め、部分的な出力があった場合は incomplete(`max_output_tokens`)レスポンスを、何も出力されなかった場合は失敗 `stream_truncated` イベントを発行します。遅れて届いた推論も、まだアクティブなストリーミングのツール呼び出しへバックフィルされます。
+
+### tools が空のときの Codex Chat `tool_choice`
+
+Responses→Chat 変換は、最終的な tools 配列が欠落または空(すべてのツールがフィルタで除外された場合を含む)のときに `tool_choice` と `parallel_tool_calls` を破棄するようになりました。これにより、厳格な OpenAI 互換上流(vLLM、エンタープライズゲートウェイ)が「When using `tool_choice`, `tools` must be set.」で 503/400 を返すことを避けます(#3640)。
+
+### Codex カスタムツールメタデータの保持
+
+カスタム Codex ツール(自由形式の `apply_patch` ツールなど)は、汎用プレースホルダーへ置き換えられる代わりに、format と grammar のメタデータを含む完全な元定義を、生成される Chat 関数の説明にコンパクトで順序の安定した JSON ブロックとして埋め込むようになりました。これにより Chat Completions 上流でも引き続き利用できます(#3644)。
+
+### Codex Chat 用量の `reasoning_tokens` 欠落
+
+Chat→Responses の用量変換は、プロバイダーが `completion_tokens_details` を省略したり非オブジェクトを返したりしても、常に `output_tokens_details.reasoning_tokens`(既定 0)を含めるようになりました。これにより Codex CLI の厳格な要件を満たし、レスポンス解析の失敗と再試行の繰り返しを避けます(#3514)。
+
+### Codex カスタム / 検索ツールのターン跨ぎ推論
+
+Codex Chat 履歴のターン跨ぎ推論キャッシュが、通常の関数呼び出しだけでなく、ツール呼び出しの全集合(`function_call`、`custom_tool_call`、`tool_search_call`)とその出力をカバーするようになりました。これにより `apply_patch` とツール検索の呼び出しは、`previous_response_id` で復元されるときにそれぞれの `reasoning_content` を保持します。
+
+### 一時ポート(port 0)の解決
+
+プロキシが port 0(OS 割り当て)でリッスンするよう構成されている場合、テイクオーバーはまずプロキシを起動して実際のポートを取得してから live 設定とデータベースへ書き込むようになり、クライアント URL が無効な `:0` アドレスを指すことを避けます。具体的なポートがまだ解決されていない場合、Claude Desktop のゲートウェイ URL は拒否されます。
+
+### プロキシプレースホルダーのバックアップ / 復元ループ
+
+前回プロキシ停止時に元の live 設定の復元に失敗し、プロキシプレースホルダーが live に残ってしまった場合でも、再度テイクオーバーする際に正常なバックアップをプロキシ設定で上書きすることはなくなり、復元時にプレースホルダーを live へ書き戻すこともなくなりました: いずれの経路もプレースホルダー状態を検知し、現在のプロバイダーを信頼できる情報源として live を再構築します。これにより、プロキシのトグルが何もしない状態になり、クライアントがローカルプロキシアドレスに固定されてしまう問題を修正しました(#3689)。
+
+### プロキシテイクオーバー中のプロバイダー切り替え誤ブロック
+
+ローカルルーティングのテイクオーバー中、明示的に official と分類されたプロバイダーのみが切り替えをブロックされるようになり、endpoint が meta に存在する、またはフィールドが未入力なだけのカスタムプロバイダーまで無効化することはなくなりました。無効化された「有効化」ボタンは、以前の赤い「ブロック済み」バッジの代わりに、より軽いヒントのツールチップを表示します。
+
+### localhost リッスンアドレスの正規化
+
+プロキシのリッスンアドレスを `localhost` で保存した場合、永続化前に `127.0.0.1` へ正規化されるようになり、バインドの不整合を避けます(#3016)。
+
+### Anthropic `system` メッセージの正規化
+
+Anthropic 形式のプロバイダーでは、`messages` 配列内の system ロールのエントリを折りたたんでトップレベルの `system` フィールドへマージするようになり(元の順序と既存のトップレベル system を保持)、厳格な上流が先頭以外の system メッセージを拒否することを避けます。OpenAI Chat ルーティングは影響を受けません(#3775)。
+
+### Claude Desktop 1M コンテキストモデルルーティング
+
+Claude Desktop は 1M コンテキスト beta が有効なとき、モデル名に `[1m]` マーカーを付加します(例: `claude-opus-4-8[1m]`)。プロキシはルーティング照合の前にこの接尾辞を除去するようになり、完全一致・エイリアス・旧名・ロールキーワードの照合がすべて正しく解決されます。これにより、会話の途中で 1M モデルへ切り替えたときの `route_unknown`(HTTP 400)の失敗を修正しました。診断用に、`route_unknown` エラーには元のモデル名を引き続き保持します。
+
+### Codex 413 エラーの文言
+
+Codex 上流ゲートウェイが過大なリクエストボディを HTTP 413 で拒否したとき、プロキシはこれが CC Switch のローカル制限ではなくプロバイダーのサーバー側ボディサイズ制限であることを説明する専用メッセージを返し、実行可能な回復手順(`/compact` の実行、大きなログやインライン画像の削除、プロバイダーへの上限引き上げ依頼)を提示するようになりました。上流の生の HTML エラーページをそのまま返すことはなくなりました。
+
+### プロキシパネルのエラー詳細
+
+プロキシのテイクオーバー切り替えに失敗したとき、プロキシパネルのトーストは、汎用の失敗メッセージだけでなく、バックエンドが返す具体的なエラー詳細を含めるようになりました(#3656)。
+
+### Copilot 無限空白検出のしきい値
+
+ストリーミングの無限空白の中断しきい値を、連続する空白文字 20 から 500 へ引き上げました。これにより、引数に深くインデントされたコード(Python、YAML、Rust、Markdown)を含む正当なツール呼び出しが誤って中断されることを避けつつ、本物の Copilot 無限空白バグは引き続き捕捉します(#2647)。
+
+### サブスクリプション階層のトレイ表示
+
+統一された階層→ラベルのマッピングにより、トレイと残量表示における公式サブスクリプション階層の表示を修正しました: Claude / Codex は 7 日ウィンドウを取りこぼさなくなり、Gemini Pro / Flash / Flash-Lite の階層は生のマシン名を漏らさなくなり、複数ウィンドウのプラン(Opus + Sonnet など)は最初の一致ではなく最悪の利用率を表示するようになりました。
+
+### Claude ストリームの input_tokens 過大計上
+
+一部の Anthropic 互換ストリーミングプロバイダー(Qwen、MiniMax など)は `message_start` で完全なコンテキストを `input_tokens` として報告し、別途報告済みのキャッシュ分を二重計上して、表示上のキャッシュヒット率を不当に低下させていました。パーサーは `message_delta` のより小さい正の `input_tokens` を優先し、同じ usage ブロックのキャッシュカウントを採用するようになりました。ネイティブ Claude と OpenRouter 変換の経路は変更ありません。
+
+### 智譜(Zhipu)残量照会の endpoint ルーティング
+
+智譜 Coding Plan の残量照会は `api.z.ai` にハードコードされていたため、本土プリセット(`open.bigmodel.cn`)のユーザーは国際 endpoint が到達不能なときに用量を取得できませんでした。残量リクエストは、ユーザーが構成した base URL に一致するホストへルーティングされるようになりました(#3702)。
+
+### MiniMax 残量 API と価格
+
+MiniMax Coding Plan の残量を新しい残量 API に対応させました(新 API は、旧パーサーが依存していた用量カウント(階層が空になりトレイに用量が表示されなくなる)の代わりに、残り割合のフィールドを返します)。非コーディングモデル(動画など)を除外し、週次上限のないプランに対応し、MiniMax M3 モデルの既定価格を追加しました(#3518)。
+
+### GLM Coding Plan の endpoint とモデル取得
+
+智譜 / Z.AI の GLM Coding Plan プリセットを `/api/coding/paas/v4` endpoint に修正し(Codex、OpenCode、OpenClaw、Hermes をカバー)、すでに `/v{N}` のバージョンセグメントで終わる base URL については、モデル一覧プローブが `{base}/models` を先に照会するようにしました(`/v1/models` はフォールバックとして保持)。これにより「モデル取得」ボタンがバージョン付き endpoint で 404 にならなくなりました(#3524)。
+
+### Codex モデルカタログパスの可搬性
+
+Codex は `config.toml` に絶対パスではなく相対ファイル名 `cc-switch-model-catalog.json` のみを書き込むようになりました(Codex CLI は設定ディレクトリから解決します)。これにより、絶対パスを変換できない WSL やシンボリックリンク環境でモデルカタログが壊れる問題を修正しました(#3614)。
+
+### APINebula の OpenCode SDK
+
+APINebula の OpenCode プリセットは `@ai-sdk/openai` ではなく `@ai-sdk/openai-compatible` を読み込むようになり、chat-completions のみ対応の上流で失敗する Responses API ではなく、このリレーが期待する OpenAI Chat Completions 形式でリクエストを行います。
+
+### Windows 終了後のトレイアイコン残留
+
+Windows では CC Switch を終了すると、マウスを重ねるまで無効なトレイアイコンが残ることがありました。アプリは終了前にトレイアイコンを明示的に削除するようになり、プロセス終了とともにきれいに消えます(#3797)。
+
+### Windows タスクバーアイコン
+
+実行時に Windows AppUserModelID を明示的に設定し、インストーラーが生成するデスクトップとスタートメニューのショートカットに同じ ID と製品アイコンを書き込みます。これにより CC Switch がタスクバーで正しいアイコンを表示し、正しくグループ化されます(#3457)。
+
+### Windows サブディレクトリスキルの更新チェック
+
+Windows でインストール済みスキルをスキャンする際、バックスラッシュのパス区切りをスラッシュへ正規化するようになり、サブディレクトリにネストされたスキル(`skills/my-skill` など)が静かにスキップされず、更新チェックで一致するようになりました(#3430)。
+
+### macOS の入力自動大文字化
+
+共有のテキスト Input コンポーネントで autocomplete、autocorrect、autocapitalize、spellcheck を無効化し、macOS が設定フィールドに入力された最初の文字を自動で大文字化・自動修正しないようにしました(#3626)。
+
+### Codex VS Code セッションプレビュー
+
+VS Code から送信された Codex リクエストでは、注入されたリクエストの前に markdown 見出しがあると、セッションプレビューが本当のプロンプトではなく選択範囲や開いているファイルの内容を表示することがありました。バックエンドのタイトルとフロントエンドのプレビューはいずれも、最後の「## My request for Codex:」見出しに一致するようになり(IDE は本当のリクエストを最後のセクションとして注入します)、プレビューがユーザーのプロンプトを反映します(#3593)。
+
+### 中国語 UI の VS Code 表記
+
+簡体字・繁体字中国語の「Claude Code プラグインに適用」の説明を、「Vscode」ではなく正しく「VS Code」と表記するよう修正し、英語・日本語の文言と揃えました(#3228)。
+
+---
+
+## ドキュメント
+
+### ユーザーマニュアル刷新
+
+README の各言語版と en / zh / ja のユーザーマニュアルを刷新し、受管 7 アプリすべてを反映(紹介と概要の文面に Claude Desktop と Hermes を追加)、OpenCode の設定パスを `~/.config/opencode/`(`opencode.json`)に修正、Hermes の設定ファイルの説明を追加、言語ドキュメントを 4 言語に更新、アプリごとの MCP / プロンプト / スキルの対応状況を訂正、エクスポートがタイムスタンプ付きで用量ログを含む SQL バックアップを生成することを記載、価格モデル ID のマッチングルールを追記しました(#3411)。
+
+### Codex 公式認証保持ガイド
+
+モデル通信をサードパーティ API へ切り替えつつ、Codex の公式リモート操作と公式プラグインを動作させ続ける方法を説明する中国語 / 英語 / 日本語のガイドを追加し、v3.16.1 のリリースノートからリンクしました。
+
+### README リンクとスポンサー表記
+
+各言語の README のリリースノートリンクを v3.16.1 に更新し、README_ZH のスポンサーブロックで壊れていた曲線引用符文字を修正して、HTML 属性が正しくレンダリングされるようにしました(#3772)。
+
+---
+
+## アップグレード時の注意
+
+### S3 と WebDAV のクラウド同期は排他
+
+クラウド同期は同時に 1 つのバックエンドのみを実行します。S3 自動同期を有効化すると、実行中の WebDAV 自動同期は停止し、その逆も同様です。以前 WebDAV を使っていた場合は、S3 へ切り替える前に両端のデータが揃っていることを確認し、旧バックエンドがまだバックアップしていると誤解しないようにしてください。
+
+### モデルマッピング変更後は Codex の再起動が必要
+
+Codex は起動時に `model_catalog_json` を読み込みます。本リリースでモデルカタログを相対パスへ書き換え、`/v1/models` 到達性エンドポイントを追加しましたが、モデルマッピングテーブルを変更した後は、`/model` メニューを更新するために Codex の再起動が必要です。
+
+---
+
+## リスク通知
+
+本リリースは、リバースプロキシ系機能に関する以前のリスク通知を引き続き適用します。
+
+**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションの Codex OAuth をリバースプロキシ経由で使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 release notes](v3.13.0-ja.md#️-リスクに関する注意事項) を参照してください。
+
+**Codex サードパーティプロバイダー Chat ルーティング**: CC Switch ローカルプロキシで Codex リクエストを変換し、サードパーティプロバイダーへ転送する場合、課金、コンプライアンス、データ保持に関する制約はプロバイダーごとに異なります。利用前に対象プロバイダーの利用規約を確認してください。
+
+**Claude Desktop サードパーティプロバイダープロキシ切り替え**: CC Switch 内蔵のプロキシゲートウェイで Claude Desktop のリクエストをサードパーティプロバイダーへ転送する場合も、対象プロバイダーの課金、コンプライアンス、データ保持に関する規約に従う必要があります。
+
+上記機能を有効化したユーザーは、関連するリスクを自ら負うものとします。CC Switch は、これらの機能の利用によって発生したアカウント制限、警告、サービス停止について責任を負いません。
+
+---
+
+## 謝辞
+
+v3.16.2 で機能と修正を届けてくださった以下のコントリビューターに感謝します:
+
+- [#1351](https://github.com/farion1231/cc-switch/pull/1351): S3 互換クラウドストレージ同期を追加、@keithyt06 に感謝。
+- [#3215](https://github.com/farion1231/cc-switch/pull/3215): OpenCode セッション用量同期を追加、@nothingness0db に感謝。
+- [#2709](https://github.com/farion1231/cc-switch/pull/2709): ZenMux Token Plan プロバイダーを追加、@Eter365 に感謝。
+- [#3643](https://github.com/farion1231/cc-switch/pull/3643): CherryIN プリセットプロバイダーを追加、@zhibisora に感謝。
+- [#3818](https://github.com/farion1231/cc-switch/pull/3818): Codex CLI 到達性確認用の `GET /v1/models` エンドポイントを追加、@CSberlin に感謝。
+- [#3426](https://github.com/farion1231/cc-switch/pull/3426): 用量ダッシュボードのヒーロー再設計、@allenxu09 に感謝。
+- [#3640](https://github.com/farion1231/cc-switch/pull/3640): tools が空のとき `tool_choice` を破棄、@Postroggy に感謝。
+- [#3644](https://github.com/farion1231/cc-switch/pull/3644): Chat ルーティングで Codex カスタムツールメタデータを保持、@LanternCX に感謝。
+- [#3514](https://github.com/farion1231/cc-switch/pull/3514): Chat→Responses で常に `reasoning_tokens` を含める、@yeeyzy に感謝。
+- [#3689](https://github.com/farion1231/cc-switch/pull/3689): live がすでにプロキシプレースホルダーのときバックアップ / 復元をスキップ、@YongmaoLuo に感謝。
+- [#3016](https://github.com/farion1231/cc-switch/pull/3016): localhost リッスンアドレスを正規化、@Alexlangl に感謝。
+- [#3775](https://github.com/farion1231/cc-switch/pull/3775): Anthropic `system` メッセージを正規化、@Dearli666 に感謝。
+- [#3656](https://github.com/farion1231/cc-switch/pull/3656): プロキシパネルのエラー表示を改善、@lzcndm に感謝。
+- [#2647](https://github.com/farion1231/cc-switch/pull/2647): 無限空白検出のしきい値を 20 → 500 へ引き上げ、@NiuBlibing に感謝。
+- [#3702](https://github.com/farion1231/cc-switch/pull/3702): 智譜の残量照会を構成済み base URL へルーティング、@YongmaoLuo に感謝。
+- [#3518](https://github.com/farion1231/cc-switch/pull/3518): MiniMax の新残量 API と既定価格に対応、@LaoYueHanNi に感謝。
+- [#3524](https://github.com/farion1231/cc-switch/pull/3524): 智譜 Coding Plan プリセットとバージョン付き endpoint のモデル探索を修正、@makoMakoGo に感謝。
+- [#3614](https://github.com/farion1231/cc-switch/pull/3614): モデルカタログを相対ファイル名に変更、@steponeerror に感謝。
+- [#3797](https://github.com/farion1231/cc-switch/pull/3797): Windows 終了後のトレイアイコン残留を修正、@iAJue に感謝。
+- [#3457](https://github.com/farion1231/cc-switch/pull/3457): Windows タスクバーアイコンを修正、@ZhangNanNan1018 に感謝。
+- [#3430](https://github.com/farion1231/cc-switch/pull/3430): Windows のパス区切りを正規化してサブディレクトリスキルの更新に対応、@Ninthless に感謝。
+- [#3626](https://github.com/farion1231/cc-switch/pull/3626): macOS の入力自動大文字化を無効化、@ZHLHZHU に感謝。
+- [#3593](https://github.com/farion1231/cc-switch/pull/3593): Codex VS Code セッションプレビューを修正、@xwil1 に感謝。
+- [#3228](https://github.com/farion1231/cc-switch/pull/3228): 中国語 UI の VS Code 表記を揃える、@Games55k に感謝。
+- [#3411](https://github.com/farion1231/cc-switch/pull/3411): 現行のアプリ対応を反映してユーザーマニュアルを刷新、@makoMakoGo に感謝。
+- [#3772](https://github.com/farion1231/cc-switch/pull/3772): README のリリースノートリンクとスポンサー表記を修正、@null-easy に感謝。
+
+v3.16.1 リリース後に Codex Chat ルーティング、ローカルプロキシのテイクオーバー、用量統計、プラットフォーム互換性の問題を報告してくださったすべてのユーザーにも感謝します。今回の多くの修正は、実際の利用シーンから得られた再現情報に基づいています。
+
+---
+
+## ダウンロードとインストール
+
+[Releases](https://github.com/farion1231/cc-switch/releases/latest) から、お使いのシステムに対応するビルドをダウンロードしてください。
+
+### システム要件
+
+| システム | 最低バージョン | アーキテクチャ |
+| -------- | ------------------------ | ----------------------------------- |
+| Windows | Windows 10 以降 | x64 |
+| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
+| Linux | 下表を参照 | x64 / ARM64 |
+
+### Windows
+
+| ファイル | 説明 |
+| ---------------------------------------- | ------------------------------------------ |
+| `CC-Switch-v3.16.2-Windows.msi` | **推奨** - 自動更新対応の MSI インストーラー |
+| `CC-Switch-v3.16.2-Windows-Portable.zip` | ポータブル版、展開してそのまま実行できます |
+
+### macOS
+
+| ファイル | 説明 |
+| -------------------------------- | ------------------------------------------------------ |
+| `CC-Switch-v3.16.2-macOS.dmg` | **推奨** - DMG インストーラー、Applications へドラッグ |
+| `CC-Switch-v3.16.2-macOS.zip` | 展開して Applications へドラッグ、Universal Binary |
+| `CC-Switch-v3.16.2-macOS.tar.gz` | Homebrew インストールと自動更新用 |
+
+Homebrew インストール:
+
+```bash
+brew install --cask cc-switch
+```
+
+更新:
+
+```bash
+brew upgrade --cask cc-switch
+```
+
+### Linux
+
+Linux アセットは **x86_64** と **ARM64**(`aarch64`)の両方を提供します。ファイル名にアーキテクチャ識別子が含まれているため、マシンの `uname -m` 出力に合わせて選択してください:
+
+- `CC-Switch-v3.16.2-Linux-x86_64.AppImage` / `.deb` / `.rpm`
+- `CC-Switch-v3.16.2-Linux-arm64.AppImage` / `.deb` / `.rpm`
+
+| ディストリビューション | 推奨形式 | インストール方法 |
+| --------------------------------------- | ----------- | ------------------------------------------------------------------------- |
+| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
+| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
+| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
+| Arch Linux / Manjaro | `.AppImage` | 実行権限を付与して直接起動、または AUR を使用 |
+| その他 / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
diff --git a/docs/release-notes/v3.16.2-zh.md b/docs/release-notes/v3.16.2-zh.md
new file mode 100644
index 000000000..81fcb667f
--- /dev/null
+++ b/docs/release-notes/v3.16.2-zh.md
@@ -0,0 +1,347 @@
+# CC Switch v3.16.2
+
+> 在 v3.16.1 的 Codex 稳定性补丁之后,这一版主要拓宽了数据的可携带性与用量观测能力——新增 S3 兼容云同步、OpenCode 会话用量同步、官方订阅额度模板——并继续加固 Codex 通过 Chat Completions 路由第三方供应商的稳健性,同时修复了一批 Windows / macOS 平台问题,新增 CherryIN、ZenMux 供应商,并全面刷新了三语用户手册。
+
+**[English →](v3.16.2-en.md) | [日本語版 →](v3.16.2-ja.md)**
+
+---
+
+## 使用攻略
+
+这一版新增了云同步的 S3 后端和更多用量统计来源,如果你想用上,可以先看这些文档:
+
+- **[设置](../user-manual/zh/1-getting-started/1.5-settings.md)**:在设置页配置云同步(WebDAV / S3 兼容存储),用于在多台设备间备份和恢复供应商、MCP、提示词、技能等配置。
+- **[用量统计](../user-manual/zh/4-proxy/4.4-usage.md)**:了解用量看板的数据来源(代理日志、Codex / Gemini / OpenCode 会话同步)与统计口径。
+
+---
+
+> [!WARNING]
+>
+> ## 唯一官方渠道声明(请务必阅读)
+>
+> CC Switch 是**完全免费、开源**的桌面应用,**不会向用户收取任何费用**。请仅通过下列官方渠道获取本软件:
+>
+> | 类别 | 唯一官方 |
+> | -------- | ------------------------------------------------------------------------------ |
+> | 官网 | **[ccswitch.io](https://ccswitch.io)** |
+> | 源码 | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
+> | 下载 | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
+> | 作者 | **[@farion1231](https://github.com/farion1231)** |
+> | 举报山寨 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
+>
+> **任何向你收费、要求充值、或索取登录凭据的"CC Switch"网站或客户端均为假冒**。如果你被诱导支付了费用,请立即停止操作并通过 GitHub Issues 反馈。
+
+---
+
+## 概览
+
+CC Switch v3.16.2 是 v3.16.1 之后的一版维护更新。在上一版集中处理 Codex 官方鉴权与本地路由接管的安全问题之后,这一版把重心放在两件事上:一是拓宽数据的可携带性和用量观测——新增 S3 兼容云同步(WebDAV 之外的第二套云备份后端)、OpenCode 会话用量同步,以及面向官方订阅的额度统计模板;二是继续打磨 Codex 通过 Chat Completions 路由第三方供应商时暴露出来的边角问题——流式截断判定、空 tools 下的 `tool_choice`、自定义工具元数据、推理 token 统计、文件 / 音频附件转换等。
+
+此外,本版还修复了一批本地代理的稳健性问题(临时端口解析、接管占位符还原死循环、Anthropic `system` 消息归一化、上游 413 文案、Claude Desktop 的 `[1m]` 模型路由),处理了若干 Windows / macOS 平台体验问题,并新增 CherryIN、ZenMux 两个供应商,同时全面刷新了三语用户手册。
+
+**发布日期**:2026-06-07
+
+**更新规模**:41 commits | 132 files changed | +11,116 / -1,636 lines
+
+---
+
+## 重点内容
+
+- **S3 兼容云同步**:在 WebDAV 之外新增 S3 兼容对象存储作为第二套云备份后端,内置 AWS S3、MinIO、Cloudflare R2、阿里云 OSS、腾讯云 COS、华为 OBS 等一键预设。
+- **更多用量统计来源**:新增 OpenCode 会话用量同步,以及面向 Claude / Codex / Gemini 官方订阅的额度统计模板(显式开关、默认关闭)。
+- **Codex Chat Completions 路由继续加固**:修复流式截断误判、空 tools 下 `tool_choice` 被拒、自定义工具元数据丢失、推理 token 统计缺失,并支持文件 / 音频附件转换与 `/v1/models` 探活端点。
+- **本地代理更稳**:修复临时端口(port 0)解析、接管占位符还原死循环、Anthropic `system` 消息归一化、上游 413 文案,以及 Claude Desktop 1M 上下文模型路由。
+- **平台与供应商**:修复 Windows 托盘 / 任务栏图标、子目录技能更新、macOS 输入自动大写等问题,并新增 CherryIN、ZenMux 供应商。
+
+---
+
+## 新功能
+
+### S3 兼容云同步
+
+云同步现在支持 S3 兼容对象存储作为 WebDAV 之外的第二套后端,签名采用自实现的 AWS Signature V4,以兼容尽可能多的服务。设置页提供 AWS S3、MinIO、Cloudflare R2、阿里云 OSS、腾讯云 COS、华为 OBS 以及自定义 endpoint 的一键预设,支持连接测试、手动上传 / 下载,以及在配置变更时自动同步(providers、endpoint、MCP、提示词、技能、设置、代理等配置表,**不含**用量日志这类高频写入数据)。开启 S3 同步会停用正在运行的 WebDAV 同步,反之亦然([#1351](https://github.com/farion1231/cc-switch/pull/1351))。
+
+### OpenCode 会话用量同步
+
+新增 OpenCode 作为用量统计来源,从 OpenCode 本地 SQLite 数据库读取每条消息的 token、成本和模型数据并导入用量记录,并提供独立的「OpenCode」应用筛选页签和「OpenCode Session」数据来源标签。数据库路径会遵循 `OPENCODE_DB` 和 `XDG_DATA_HOME`(在所有平台默认 `~/.local/share/opencode`),只导入已完成的消息,并在判断新鲜度时把 WAL 文件一并计入,避免刚写入的会话被跳过([#3215](https://github.com/farion1231/cc-switch/pull/3215))。
+
+### 官方订阅额度模板
+
+由于部分用户担心发起用量查询的 IP 和发起应用内请求的不一致导致封号风险,因此为 Claude / Codex / Gemini 官方供应商新增一个显式、可选的「官方订阅」用量模板,通过 CLI / OAuth 凭据查询套餐额度,替代此前对官方供应商的隐式自动查询。该模板默认关闭,需要在用量脚本弹窗里开启,并可配置刷新间隔。使用此功能建议开启代理的 TUN 模式。
+
+### 文本模型图片回退整流器
+
+新增一个代理整流器:当路由到的模型仅支持文本(显式声明,或由内置的模型名启发式判定),或上游拒绝图片输入时,会把 Anthropic 图片块替换为 `[Unsupported Image]` 占位标记,避免对话被中断。设置页提供该回退功能的开关,并单独提供一个开关控制启发式检测(可关闭以避免误判多模态模型)。
+
+### ZenMux Token Plan 供应商
+
+新增 ZenMux 作为 Token Plan 类的 Coding Plan 供应商,可在用量脚本弹窗里手动填写 API key 和 base URL,并以美元口径富展示已用 / 额度([#2709](https://github.com/farion1231/cc-switch/pull/2709))。
+
+### CherryIN 预设
+
+新增 CherryIN 聚合网关作为快捷配置预设,覆盖全部 7 个受管应用——Claude Code / Claude Desktop / OpenClaw / Hermes 使用 Anthropic 格式端点(open.cherryin.net),OpenCode 使用 `@ai-sdk/anthropic`(`/v1`),Codex 使用 OpenAI 兼容端点,Gemini CLI 使用 Gemini 兼容端点,附带官方品牌图标,位置紧挨 AiHubMix([#3643](https://github.com/farion1231/cc-switch/pull/3643))。
+
+### Codex CLI 模型探活端点 `/v1/models`
+
+本地代理现在会响应 Codex CLI 启动时探测的 `GET /v1/models`,返回 CC Switch 托管的 Codex 模型目录。同时加入了过期目录守卫:解析 live 的 `config.toml`,仅当 `model_catalog_json` 仍指向 CC Switch 持有的目录文件时才提供,避免把上一个供应商遗留的目录暴露给 Codex([#3818](https://github.com/farion1231/cc-switch/pull/3818))。
+
+### Codex Chat 文件与音频附件
+
+Codex 的 Responses→Chat 转换现在会把 `input_file`(携带 `file_id` 或内联 `file_data`)和 `input_audio` 内容部分映射为 Chat Completions 的对应形态,并补发此前会被丢弃的顶层 `input_*` 项,让文件和音频附件能够送达只支持 Chat 的 Codex 上游。
+
+---
+
+## 变更
+
+### 用量看板 Hero 重新设计
+
+把用量看板的 Hero 区与汇总卡片重排为更紧凑的布局,将真实 token 总量、请求数和成本合并到顶部一行展示([#3426](https://github.com/farion1231/cc-switch/pull/3426))。
+
+### SSSAiCode 端点刷新
+
+把 SSSAiCode 预设的官网、注册和 API base URL 更新到 `sssaicodeapi.com` 域名,并刷新其端点候选节点(默认 `node-hk.sssaicodeapi.com`,另含 `node-hk.sssaiapi.com` 和 `node-cf.sssaicodeapi.com`),覆盖全部 7 个应用预设。
+
+---
+
+## 修复
+
+### Codex Chat 流式截断判定
+
+当 Chat Completions 上游在没有 `finish_reason` 或 `[DONE]` 的情况下结束流时,CC Switch 不再把它当作正常完成:只有流真正结束才正常收尾;已产出部分内容时发出 incomplete(`max_output_tokens`)响应;完全没有产出时发出失败的 `stream_truncated` 事件。晚到的推理内容也会回填到仍在进行的流式工具调用上。
+
+### Codex Chat 空 tools 下的 `tool_choice`
+
+Responses→Chat 转换现在会在最终 tools 数组缺失或为空(包括所有工具被过滤掉)时一并丢弃 `tool_choice` 和 `parallel_tool_calls`,避免严格的 OpenAI 兼容上游(vLLM、企业网关)以"When using `tool_choice`, `tools` must be set."报 503/400([#3640](https://github.com/farion1231/cc-switch/pull/3640))。
+
+### Codex 自定义工具元数据保留
+
+自定义 Codex 工具(如自由格式的 `apply_patch` 工具)现在会把完整的原始定义——包括 format 和 grammar 元数据——以紧凑、顺序稳定的 JSON 块嵌入生成的 Chat 函数描述中,而不是替换成通用占位符,从而在 Chat Completions 上游上仍可正常使用([#3644](https://github.com/farion1231/cc-switch/pull/3644))。
+
+### Codex Chat 用量缺少 `reasoning_tokens`
+
+Chat→Responses 的用量转换现在总会包含 `output_tokens_details.reasoning_tokens`(默认 0),即使供应商省略 `completion_tokens_details` 或返回非对象也是如此,满足 Codex CLI 的严格要求,避免反复的响应解析失败和重试([#3514](https://github.com/farion1231/cc-switch/pull/3514))。
+
+### Codex 自定义工具 / 搜索工具的跨轮推理
+
+Codex Chat 历史里的跨轮推理缓存现在覆盖完整的工具调用集合(`function_call`、`custom_tool_call`、`tool_search_call`)及其输出,而不再仅限普通函数调用,因此 `apply_patch` 和工具搜索调用在通过 `previous_response_id` 恢复时能保留各自的 `reasoning_content`。
+
+### 临时端口(port 0)解析
+
+当代理被配置为监听 0 端口(由系统分配)时,接管流程现在会先启动代理以拿到真实端口,再写入 live 配置和数据库,避免客户端 URL 指向无效的 `:0` 地址;若还没解析出具体端口,Claude Desktop 的网关 URL 会被直接拒绝。
+
+### 代理占位符备份 / 恢复死循环
+
+如果上一次停止代理时未能还原原始 live 配置、把代理占位符遗留在了 live 中,再次接管时不会再用代理配置覆盖掉正常备份,恢复时也不会把占位符写回 live:两条路径都会识别占位符状态并以当前供应商为真相来源重建 live,修复了代理开关变成空操作、客户端被钉死在本地代理地址的问题([#3689](https://github.com/farion1231/cc-switch/pull/3689))。
+
+### 代理接管期间误拦截供应商切换
+
+在本地路由接管期间,现在只有显式归类为官方的供应商会被禁止切换,而不会再把端点存在 meta 里、或字段尚未填写的自定义供应商一并禁用。被禁用的「启用」按钮现在以更轻量的提示气泡替代原先的红色「已拦截」标记。
+
+### localhost 监听地址归一化
+
+保存代理时如果监听地址填的是 `localhost`,现在会先归一化为 `127.0.0.1` 再持久化,避免绑定不一致([#3016](https://github.com/farion1231/cc-switch/pull/3016))。
+
+### Anthropic `system` 消息归一化
+
+对 Anthropic 格式的供应商,`messages` 数组里的 system 角色条目现在会被折叠并合并到顶层 `system` 字段(保留原顺序以及已有的顶层 system),避免严格上游拒绝非首位的 system 消息;OpenAI Chat 路由不受影响([#3775](https://github.com/farion1231/cc-switch/pull/3775))。
+
+### Claude Desktop 1M 上下文模型路由
+
+Claude Desktop 在 1M 上下文 beta 激活时会给模型名追加 `[1m]` 标记(如 `claude-opus-4-8[1m]`)。代理现在会在路由匹配前先剥掉该后缀,让精确、别名、旧名和角色关键词匹配都能正确命中,修复了对话中途切换到 1M 模型时的 `route_unknown`(HTTP 400)失败;诊断用的 `route_unknown` 错误里仍保留原始模型名。
+
+### Codex 413 错误文案
+
+当 Codex 上游网关以 HTTP 413 拒绝过大的请求体时,代理现在返回专门的提示,说明这是供应商服务端的请求体大小限制(而非 CC Switch 本地限制),并给出可操作的恢复步骤(运行 `/compact`、移除大段日志或内联图片,或请供应商调高限制),不再原样回显上游的 HTML 错误页。
+
+### 代理面板错误详情
+
+切换代理接管失败时,代理面板的提示现在会带上后端返回的具体错误详情,而不是只显示一句笼统的失败信息([#3656](https://github.com/farion1231/cc-switch/pull/3656))。
+
+### Copilot 无限空白检测阈值
+
+把流式无限空白的中断阈值从 20 调高到 500 个连续空白字符,避免参数里含深层缩进代码(Python、YAML、Rust、Markdown)的正常工具调用被误判中断,同时仍能捕获真正的 Copilot 无限空白 bug([#2647](https://github.com/farion1231/cc-switch/pull/2647))。
+
+### 订阅档位托盘渲染
+
+通过统一的档位到标签映射,修复官方订阅档位在托盘和额度展示上的渲染问题:Claude / Codex 不再漏掉 7 天窗口,Gemini Pro / Flash / Flash-Lite 档位不再泄露原始机器名,多窗口套餐(如 Opus + Sonnet)现在按最差利用率展示而非取第一个匹配。
+
+### Claude 流式 input_tokens 虚高
+
+部分 Anthropic 兼容的流式供应商(如 Qwen、MiniMax)会在 `message_start` 里把完整上下文当作 `input_tokens` 上报,重复计入了已经单独统计的缓存部分,导致显示的缓存命中率被人为拉低。现在解析器会优先采用 `message_delta` 中更小的正 `input_tokens`,并采用同一 usage 块里配套的缓存计数;原生 Claude 和 OpenRouter 转换路径不变。
+
+### 智谱配额查询端点路由
+
+智谱 Coding Plan 的配额查询此前被硬编码到 `api.z.ai`,导致使用大陆预设(`open.bigmodel.cn`)的用户在国际端点不可达时查不到用量。现在配额请求会路由到与用户所配 base URL 匹配的主机([#3702](https://github.com/farion1231/cc-switch/pull/3702))。
+
+### MiniMax 余额接口与定价
+
+适配 MiniMax Coding Plan 配额的新余额接口(新接口返回剩余百分比字段,而非旧解析器依赖、会导致档位为空、托盘不再显示用量的用量计数),过滤掉非编程模型(如视频),兼容无周限额的套餐,并为 MiniMax M3 模型补充了默认定价([#3518](https://github.com/farion1231/cc-switch/pull/3518))。
+
+### GLM Coding Plan 端点与模型拉取
+
+把智谱 / Z.AI 的 GLM Coding Plan 预设修正到 `/api/coding/paas/v4` 端点(覆盖 Codex、OpenCode、OpenClaw、Hermes),并让模型列表探测对已经以 `/v{N}` 版本段结尾的 base URL 改为先查 `{base}/models`(保留 `/v1/models` 作为兜底),让「拉取模型」按钮不再在带版本号的端点上 404([#3524](https://github.com/farion1231/cc-switch/pull/3524))。
+
+### Codex 模型目录路径可移植性
+
+Codex 现在只把相对文件名 `cc-switch-model-catalog.json` 写入 `config.toml`,而不是绝对路径(Codex CLI 会从配置目录解析它),修复了在 WSL 和符号链接环境下绝对路径无法转换、导致模型目录失效的问题([#3614](https://github.com/farion1231/cc-switch/pull/3614))。
+
+### APINebula 的 OpenCode SDK
+
+APINebula 的 OpenCode 预设现在加载 `@ai-sdk/openai-compatible` 而非 `@ai-sdk/openai`,让请求使用该中转期望的 OpenAI Chat Completions 格式,而不是只支持 chat-completions 的上游会失败的 Responses API。
+
+### Windows 退出后托盘图标残留
+
+在 Windows 上退出 CC Switch 可能会留下一个失效的托盘图标,直到鼠标划过才消失。现在应用会在退出前显式移除托盘图标,让它随进程结束干净消失([#3797](https://github.com/farion1231/cc-switch/pull/3797))。
+
+### Windows 任务栏图标
+
+在运行时显式设置 Windows AppUserModelID,并给安装器生成的桌面和开始菜单快捷方式写入相同的 ID 和产品图标,让 CC Switch 在任务栏上显示正确图标并正确归组([#3457](https://github.com/farion1231/cc-switch/pull/3457))。
+
+### Windows 子目录技能的更新检查
+
+在 Windows 上扫描已安装技能时,把反斜杠路径分隔符归一化为正斜杠,让嵌套在子目录里的技能(如 `skills/my-skill`)能被更新检查匹配到,而不是被静默跳过([#3430](https://github.com/farion1231/cc-switch/pull/3430))。
+
+### macOS 输入自动大写
+
+为共享的文本 Input 组件关闭自动完成、自动纠错、自动大写和拼写检查,让 macOS 不再对配置字段里输入的首字母自动大写或自动纠正([#3626](https://github.com/farion1231/cc-switch/pull/3626))。
+
+### Codex VS Code 会话预览
+
+从 VS Code 发起的 Codex 请求,其会话预览在注入请求前存在 markdown 标题时,可能显示选区或打开文件的内容而非真实提示。现在后端标题和前端预览都会匹配最后一个「## My request for Codex:」标题(IDE 把真实请求作为最后一节注入),让预览反映用户的提示([#3593](https://github.com/farion1231/cc-switch/pull/3593))。
+
+### 中文界面 VS Code 文案
+
+把简体和繁体中文里「应用到 Claude Code 插件」的描述改为正确书写「VS Code」而非「Vscode」,与英文、日文文案对齐([#3228](https://github.com/farion1231/cc-switch/pull/3228))。
+
+---
+
+## 文档
+
+### 用户手册刷新
+
+刷新了 README 各语言版本以及 en / zh / ja 用户手册,使其反映全部 7 个受管应用(在介绍和总览文案里补上 Claude Desktop 与 Hermes),把 OpenCode 配置路径修正为 `~/.config/opencode/`(`opencode.json`),补充了 Hermes 配置文件说明,把语言文档更新为四种语言,订正各应用 MCP / 提示词 / 技能的支持情况,说明导出现在会生成带时间戳、含用量日志的 SQL 备份,并补充了定价模型 ID 匹配规则([#3411](https://github.com/farion1231/cc-switch/pull/3411))。
+
+### Codex 官方认证保留指南
+
+新增中 / 英 / 日三语指南,说明如何在把模型流量切到第三方 API 的同时,保留 Codex 官方远程操作和官方插件的可用性,并从 v3.16.1 release notes 链接到该指南。
+
+### README 链接与赞助商标记
+
+把各语言 README 里的 Release Notes 链接更新到 v3.16.1,并修复 README_ZH 赞助商区块里损坏的弯引号字符,让其 HTML 属性能正确渲染([#3772](https://github.com/farion1231/cc-switch/pull/3772))。
+
+---
+
+## 升级提醒
+
+### S3 与 WebDAV 云同步互斥
+
+云同步同一时间只会运行一套后端。开启 S3 自动同步会停用正在运行的 WebDAV 自动同步,反之亦然。如果你之前用的是 WebDAV,切到 S3 前请确认两端数据已对齐,避免误以为旧后端仍在备份。
+
+### 修改模型映射后仍需重启 Codex
+
+Codex 在启动时读取 `model_catalog_json`。即使本版已把模型目录改写为相对路径并新增了 `/v1/models` 探活端点,只要你修改了模型映射表,仍然需要重启 Codex 才能让 `/model` 菜单刷新。
+
+---
+
+## 风险提示
+
+本版本继续沿用此前版本对反向代理类功能的风险提示。
+
+**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#️-风险提示)。
+
+**Codex 第三方供应商 Chat 路由**:通过 CC Switch 本地代理把 Codex 请求转换并转发到第三方供应商时,各供应商对计费、合规与数据留存的约束不同,请在使用前阅读目标供应商的服务条款。
+
+**Claude Desktop 第三方供应商代理切换**:通过 CC Switch 内置代理网关把 Claude Desktop 的请求转到第三方供应商时,同样需要遵守目标供应商的计费、合规与数据留存约束。
+
+用户启用上述功能即表示自行承担相关风险。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
+
+---
+
+## 致谢
+
+感谢以下贡献者在 v3.16.2 中提交的功能与修复:
+
+- [#1351](https://github.com/farion1231/cc-switch/pull/1351):新增 S3 兼容云存储同步,感谢 @keithyt06。
+- [#3215](https://github.com/farion1231/cc-switch/pull/3215):新增 OpenCode 会话用量同步,感谢 @nothingness0db。
+- [#2709](https://github.com/farion1231/cc-switch/pull/2709):新增 ZenMux Token Plan 供应商,感谢 @Eter365。
+- [#3643](https://github.com/farion1231/cc-switch/pull/3643):新增 CherryIN 预设供应商,感谢 @zhibisora。
+- [#3818](https://github.com/farion1231/cc-switch/pull/3818):新增 Codex CLI 探活用的 `GET /v1/models` 端点,感谢 @CSberlin。
+- [#3426](https://github.com/farion1231/cc-switch/pull/3426):用量看板 Hero 重新设计,感谢 @allenxu09。
+- [#3640](https://github.com/farion1231/cc-switch/pull/3640):空 tools 时丢弃 `tool_choice`,感谢 @Postroggy。
+- [#3644](https://github.com/farion1231/cc-switch/pull/3644):Chat 路由保留 Codex 自定义工具元数据,感谢 @LanternCX。
+- [#3514](https://github.com/farion1231/cc-switch/pull/3514):Chat→Responses 始终包含 `reasoning_tokens`,感谢 @yeeyzy。
+- [#3689](https://github.com/farion1231/cc-switch/pull/3689):live 已是代理占位符时跳过备份 / 恢复,感谢 @YongmaoLuo。
+- [#3016](https://github.com/farion1231/cc-switch/pull/3016):归一化 localhost 监听地址,感谢 @Alexlangl。
+- [#3775](https://github.com/farion1231/cc-switch/pull/3775):规范化 Anthropic `system` 消息,感谢 @Dearli666。
+- [#3656](https://github.com/farion1231/cc-switch/pull/3656):改进代理面板错误信息展示,感谢 @lzcndm。
+- [#2647](https://github.com/farion1231/cc-switch/pull/2647):调高无限空白检测阈值 20 → 500,感谢 @NiuBlibing。
+- [#3702](https://github.com/farion1231/cc-switch/pull/3702):智谱配额查询按所配 base URL 路由,感谢 @YongmaoLuo。
+- [#3518](https://github.com/farion1231/cc-switch/pull/3518):适配 MiniMax 余额查询新接口与默认定价,感谢 @LaoYueHanNi。
+- [#3524](https://github.com/farion1231/cc-switch/pull/3524):修复智谱 Coding Plan 预设与带版本号端点的模型探测,感谢 @makoMakoGo。
+- [#3614](https://github.com/farion1231/cc-switch/pull/3614):模型目录改用相对文件名,感谢 @steponeerror。
+- [#3797](https://github.com/farion1231/cc-switch/pull/3797):修复 Windows 退出后托盘图标残留,感谢 @iAJue。
+- [#3457](https://github.com/farion1231/cc-switch/pull/3457):修复 Windows 任务栏图标,感谢 @ZhangNanNan1018。
+- [#3430](https://github.com/farion1231/cc-switch/pull/3430):归一化 Windows 路径分隔符以匹配子目录技能更新,感谢 @Ninthless。
+- [#3626](https://github.com/farion1231/cc-switch/pull/3626):关闭 macOS 输入框自动大写,感谢 @ZHLHZHU。
+- [#3593](https://github.com/farion1231/cc-switch/pull/3593):修复 Codex VS Code 会话预览,感谢 @xwil1。
+- [#3228](https://github.com/farion1231/cc-switch/pull/3228):对齐中文界面 VS Code 文案,感谢 @Games55k。
+- [#3411](https://github.com/farion1231/cc-switch/pull/3411):刷新用户手册以反映当前应用支持,感谢 @makoMakoGo。
+- [#3772](https://github.com/farion1231/cc-switch/pull/3772):修复 README release note 链接与赞助商标记,感谢 @null-easy。
+
+也感谢所有在 v3.16.1 发布后反馈 Codex Chat 路由、本地代理接管、用量统计和平台兼容性问题的用户,很多补丁都来自这些真实使用场景里的复现线索。
+
+---
+
+## 下载与安装
+
+访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
+
+### 系统要求
+
+| 系统 | 最低版本 | 架构 |
+| ------- | -------------------------- | ----------------------------------- |
+| Windows | Windows 10 及以上 | x64 |
+| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
+| Linux | 见下表 | x64 / ARM64 |
+
+### Windows
+
+| 文件 | 说明 |
+| ---------------------------------------- | ----------------------------------- |
+| `CC-Switch-v3.16.2-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
+| `CC-Switch-v3.16.2-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
+
+### macOS
+
+| 文件 | 说明 |
+| -------------------------------- | --------------------------------------------- |
+| `CC-Switch-v3.16.2-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
+| `CC-Switch-v3.16.2-macOS.zip` | 解压后拖入 Applications,Universal Binary |
+| `CC-Switch-v3.16.2-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
+
+Homebrew 安装:
+
+```bash
+brew install --cask cc-switch
+```
+
+更新:
+
+```bash
+brew upgrade --cask cc-switch
+```
+
+### Linux
+
+Linux 资产同时提供 **x86_64** 和 **ARM64**(`aarch64`)两种架构。资产文件名中包含架构标识,请按你机器的 `uname -m` 输出选择对应版本:
+
+- `CC-Switch-v3.16.2-Linux-x86_64.AppImage` / `.deb` / `.rpm`
+- `CC-Switch-v3.16.2-Linux-arm64.AppImage` / `.deb` / `.rpm`
+
+| 发行版 | 推荐格式 | 安装方式 |
+| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
+| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` 或 `sudo apt install ./CC-Switch-*.deb` |
+| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` 或 `sudo dnf install ./CC-Switch-*.rpm` |
+| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
+| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
+| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
diff --git a/docs/release-notes/v3.16.3-en.md b/docs/release-notes/v3.16.3-en.md
new file mode 100644
index 000000000..f68aef427
--- /dev/null
+++ b/docs/release-notes/v3.16.3-en.md
@@ -0,0 +1,340 @@
+# CC Switch v3.16.3
+
+> 🎉 **CC Switch has passed 100,000 Stars!**
+> Thank you to every user, contributor, and Star — you are the reason it has come this far. 🙏
+
+> 💎 **This release was developed with help from the Claude Fable 5 model** — it helped untangle several critical, error-prone pieces of logic: the attribution chain that bills route-takeover traffic by the real upstream model, the metering and de-duplication of cache tokens on format-conversion paths, the in-app update restart deadlock, and the migration / restore invariants of Codex unified session history. This is also why this release adds a **Fable 5 Verified** badge to the About page.
+
+> After v3.16.2 broadened data portability and usage observability, this release puts the focus on "making usage billing truly accurate" — billing by the real upstream model, fixing cache double-counting on format-conversion paths, counting Claude Code Workflow sub-agent usage (schema v11), and a round of redesign for the usage dashboard (dashboard-wide provider / model filters, a brand-icon toolbar, and more resilient quota queries) — while also hardening a batch of local proxy and platform issues, adding a custom User-Agent override, a Codex unified session history toggle, and a Claude Fable 5 tier.
+
+**[中文版 →](v3.16.3-zh.md) | [日本語版 →](v3.16.3-ja.md)**
+
+---
+
+## Usage Guides
+
+This release adds a **Codex unified session history** toggle — it migrates / restores sessions, and if used without care it can make you think sessions were "lost," so it is well worth reading its guide first. This release also changes how usage is counted and reworks the dashboard quite a bit, so both are worth starting with:
+
+- **[Codex Unified Session History: Feature Overview and Usage Guide](../guides/codex-unified-session-history-guide-en.md)**: what "unify / migrate / restore" actually changes, why your data is never truly lost, and how to verify and precisely restore sessions when you can't see them. **If you used this toggle or worry a session is gone, read this first.**
+- **[Usage Statistics](../user-manual/en/4-proxy/4.4-usage.md)**: understand the Usage Dashboard's data sources (proxy logs, session sync) and how the statistics are counted. This release adds dashboard-wide provider / model filters and surfaces the real pricing model for route-takeover traffic.
+- **[Settings](../user-manual/en/1-getting-started/1.5-settings.md)**: the custom User-Agent override, the Codex unified session history toggle, and other switches live in the provider form's advanced options and on the settings page.
+
+---
+
+> [!WARNING]
+>
+> ## Only Official Channels (Please Read)
+>
+> CC Switch is a **fully free and open-source** desktop app, and we **do not charge users any fees**. Please only obtain the software through the official channels listed below:
+>
+> | Channel | Only Official |
+> | ------------------ | ------------------------------------------------------------------------------ |
+> | Website | **[ccswitch.io](https://ccswitch.io)** |
+> | Source | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
+> | Downloads | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
+> | Author | **[@farion1231](https://github.com/farion1231)** |
+> | Report an Imposter | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
+>
+> **Any "CC Switch" website or client that asks you for payment, top-ups, or login credentials is fake.** If you have been tricked into paying, stop the transaction immediately and file a report through GitHub Issues.
+
+---
+
+## Overview
+
+CC Switch v3.16.3 is a maintenance update following v3.16.2. After the previous release concentrated on broadening data portability and usage observability, this release puts the focus on "making usage billing truly accurate" — billing by the real upstream model rather than whatever the upstream echoes back, fixing the cache-token double-counting on format-conversion paths (Chat / Responses / Gemini converted to Anthropic), folding Claude Code Workflow sub-agent usage into the local statistics, and persisting the actual pricing basis used by each record as schema v11. The usage dashboard was reworked along with it, adding dashboard-wide provider / model filters, a brand-icon toolbar, and more resilient quota queries (retry on failure plus keeping the last successful result).
+
+In addition, this release hardens a batch of local proxy robustness issues (aggregating SSE responses returned under a mislabeled Content-Type, Codex `/responses` image rectification for text-only models, recovery of Codex OAuth credentials and takeover residue, duplicate YAML keys in Hermes config), reworks the provider configuration experience (a custom User-Agent override, a unified Codex advanced section, searchable and sortable presets, a Claude Fable 5 tier), adds a Codex unified session history toggle, and fixes the in-app update hang, the Codex upgrade that broke the install, duplicate macOS terminal windows, and more.
+
+**Release date**: 2026-06-14
+
+**Stats**: 59 commits | 130 files changed | +10,223 / -4,232 lines
+
+---
+
+## Highlights
+
+- **More accurate usage billing**: route-takeover traffic is now billed by the real upstream model (not the alias the upstream echoes back), format-conversion paths no longer count cache tokens into input twice, and Claude Code Workflow sub-agent usage is now counted — with the pricing basis persisted as schema v11.
+- **Usage dashboard redesign**: provider / model filters are promoted from inside the request-log table up to dashboard-wide filters, the app filter switches to brand icons, and quota queries gain retry-on-failure plus "keep the last successful result" so a single network blip no longer turns cards red.
+- **Custom User-Agent override**: providers can set a custom UA that applies consistently across forwarding, connectivity detection, and model listing, getting past coding-plan upstreams that gate on a UA whitelist (which is how the Codex "Kimi For Coding" preset was restored).
+- **Codex unified session history**: a new opt-in toggle lets official Codex sessions share a single resume-history bucket with third-party sessions, with optional migration of existing sessions and precise ledger-based restore.
+- **Proxy and platform hardening**: aggregating mislabeled SSE responses, Codex image rectification, takeover-residue recovery, Hermes YAML de-duplication; in-app updates no longer hang on "restarting", and Codex upgrades no longer break the install.
+
+---
+
+## Added
+
+### Custom User-Agent Override
+
+Provider configs can now set a custom User-Agent that the proxy applies consistently across request forwarding, stream check, and model listing (`GET /v1/models`), so coding-plan upstreams that gate on UA no longer fail detection or return 403 while the proxy itself works. The Claude and Codex forms expose it in advanced settings with a curated presets dropdown (Claude Code / Kilo Code families that pass UA whitelists) and live non-blocking validation; stale custom UAs are dropped when switching to an official preset to avoid silently altering headers (#3671).
+
+### Unified Codex Session History
+
+Official Codex sessions can now share a single resume-history bucket with cc-switch third-party sessions via an opt-in toggle under Settings → Codex App Enhancements, so the resume picker no longer hides them from each other. When enabled, the live `config.toml` routes official runs through a shared `custom` model_provider that mirrors the built-in OpenAI provider (`auth.json` is untouched); the toggle is forward-only by default but the enable dialog offers a checkbox to migrate existing official sessions (with per-generation backups), and the disable dialog offers a precise ledger-based restore that only reverts sessions originally recorded as `openai` while leaving sessions created during the toggle untouched.
+
+### Dashboard-Wide Provider / Model Filters
+
+The provider and model filters move from inside the request-log table up to the top bar, applying globally to the hero summary, trend chart, request logs, and both stats tabs so you can scope the whole dashboard to a given source and model. Sources match by exact display name (so session placeholder rows like "Claude (Session)" are selectable) and models match by effective pricing model, with the model dropdown cascading from the selected source and both lists showing only options that have data in the current range.
+
+### Refreshed Model Pricing Seed
+
+Added pricing for 9 models including Claude Fable 5, Grok 4.3, Mistral Medium 3.5 / Small 4, and Qwen 3.7 Max/Plus, and corrected 28 existing prices against current official vendor list pricing (GLM, Grok, MiMo, Doubao, Kimi, MiniMax, Mistral, Qwen) so usage cost estimates are accurate. Each change updates the seed for fresh installs and adds a guarded repair for existing databases without clobbering user-edited rows.
+
+### Claude Fable 5 Model Tier
+
+Provider forms now expose `claude-fable-5` as a fourth model-mapping tier on both the Claude Code and Claude Desktop proxy paths, with a fable → opus → default fallback mirroring the official downgrade and the `fable-` prefix whitelisted for the Desktop 1.12603.1+ validator. A clarified four-language fallback hint warns that leaving a tier blank on third-party endpoints forwards the literal model name and 404s (#3980, #4026, #4049).
+
+### Unity2.ai Partner Provider
+
+Added Unity2.ai, an AI API relay partner, as a preset across all seven managed apps (Claude Code, Codex, Gemini, OpenCode, OpenClaw, Claude Desktop, Hermes), each carrying the referral signup link and partner promotion copy in all four locales. Codex uses the bare base URL (the gateway exposes `/responses` at root) while OpenCode / OpenClaw / Hermes use the `/v1` chat-completions endpoint with `gpt-5.5`.
+
+### Kimi K2.7 Code Model
+
+Added the `kimi-k2.7-code` model (in $0.95 / out $4.00 / cache-read $0.19 per 1M tokens, 256K context) and pointed all six official Moonshot Kimi presets (Claude Code, Codex, Claude Desktop, Hermes, OpenCode, OpenClaw) at it, renaming the OpenCode / OpenClaw presets to "Kimi K2.7 Code". The pricing seed applies on startup via the idempotent insert path, so existing users pick up the new pricing without a migration.
+
+### Codex "Kimi For Coding" Preset Restored
+
+Re-added the Codex "Kimi For Coding" preset (`openai_chat`, `kimi-for-coding`, 256K context) with thinking mode enabled by default; it was previously removed because the coding endpoint rejects Codex's default `codex-cli` User-Agent with 403. It now works via proxy takeover combined with the custom User-Agent override (set to a whitelisted UA such as `claude-cli/*`).
+
+### Pricing-Model Audit in Request Detail
+
+The request detail panel now shows the requested model and the pricing model when they differ from the response model, making route-takeover bills auditable directly from the usage UI.
+
+### Preset Provider Search & Sorting
+
+The provider preset selector gains a searchable, sorted list with an inline search box (toggled via a magnifier icon, dismissed on ESC or outside click). Buttons use a responsive grid with consistent sizing and default icons, and search matches only provider display/raw names so URL fragments and shared category labels no longer produce noisy matches (#3975, #4183).
+
+### Claude Mythos 5 Pricing
+
+Registered the `claude-mythos-5` model in the bundled model/pricing table (in $10 / out $50 per 1M tokens, cache read $1.00, cache write $12.50), so usage metering prices and displays it correctly (#4077).
+
+### Fable 5 Verified Banner
+
+The Settings About page now displays a Fable 5 Verified banner beside the app name and version, marking this as a special build, with the version badge centered under the app name.
+
+---
+
+## Changed
+
+### Claude Desktop Usage Folded Into Claude
+
+The dashboard no longer shows a standalone "Claude Desktop" bucket, which only ever displayed a partial number (Desktop chat usage never passes through the proxy and its Code-tab sessions write into the shared `~/.claude/projects` tree). Desktop proxy traffic is now folded into the `claude` view for display while still recorded under its own `app_type` for route-takeover billing audit, with the real value visible in the request detail panel.
+
+### Lightweight Provider Health Check
+
+The provider health check no longer sends a real streaming model request (which many third-party providers blocked with 401/403/WAF, causing false negatives); it now performs a lightweight HTTP reachability probe of the provider `base_url`, treating any HTTP response as reachable and counting only DNS/connect/TLS/timeout as failure. The connectivity button is hidden for official providers (which use OAuth with an empty base URL and no reliable reachability target), the real-request confirmation dialog and test model/prompt fields are removed, and the degraded-latency threshold is set to 6s with an 8s timeout. The reachability check never resets the circuit breaker, so failover detection stays driven solely by real proxy traffic.
+
+### Codex Advanced Options Section
+
+The Codex provider form now folds local routing, model mapping, reasoning overrides, and custom User-Agent into a single collapsible advanced section mirroring the Claude form (auto-expanding when a UA is set or local routing is on). Custom User-Agent is now also configurable for native Responses providers, where it was previously reachable only with `openai_chat` routing enabled.
+
+### Usage Toolbar Refresh and Layout
+
+The app filter now renders brand icons (via ProviderIcon, with a grid icon for "All") instead of text tabs that wrapped awkwardly in narrow windows, and the usage hero shows the selected app's brand icon with Codex recolored to a neutral gray matching OpenAI's monochrome branding. The click-to-cycle refresh button becomes a Select with a localized "off" label, and the top-bar controls are compacted and aligned into consistent width groups with truncated long date-range labels.
+
+### Faster About Panel Loading
+
+The Settings About panel now loads progressively: the app version badge appears the instant it resolves instead of waiting for tool probes, each tool card updates the moment its own version check finishes (probes run concurrently rather than sequentially), and results are cached for the app session with a 10-minute TTL so reopening the About tab reuses cached values and revalidates stale ones in the background instead of re-probing all six tools every time.
+
+### Volcengine Ark Coding Plan Promo
+
+Updated the Volcengine Ark preset across all six apps with the new Coding Plan invite link (replacing the old Agent Plan / activity links) and refreshed the partner promotion copy in all four locales (two-month 75% off plus invite code 6J6FV5N2), correcting the product name from Agent Plan to Coding Plan.
+
+### MiniMax Demoted to Regular Provider
+
+Removed the gold partner star badge and the API-key promotion banner for MiniMax by dropping the `isPartner` flag from all its presets; it stays as a regular `cn_official` provider keeping its icon and theme. The promotion copy is kept dormant so the partnership can be re-enabled with a single line.
+
+### LemonData Removed, SudoCode Demoted
+
+Removed the LemonData provider preset entirely from all apps along with its promotion copy, icons, and sponsor listings, and demoted SudoCode from a partner to a regular `third_party` provider by dropping its `isPartner` flag and promotion copy (it keeps its icon).
+
+### AtlasCloud Codex GLM 5.1 Context Window
+
+Declared the 200,000-token context window for the `zai-org/glm-5.1` model in the AtlasCloud Codex preset, matching the other GLM 5.1 preset entries.
+
+---
+
+## Fixed
+
+### Route-Takeover Traffic Billed by the Real Upstream Model
+
+When a request was routed to a different upstream (env model mapping, Claude Desktop routes, Copilot normalization, Codex chat override), the proxy used to attribute and price usage by whatever model the upstream echoed back, recording kimi/glm tokens as `claude-*` and overstating cost roughly 5–25×. The forwarder now captures the real outbound model, attributes usage by upstream-echo then outbound then client alias, persists the actual pricing basis on every row (schema v11), and keeps that basis through cost backfill and 30-day rollup pruning; Claude Desktop traffic is now logged under its own `app_type` so its pricing overrides apply.
+
+### Usage Metering on Format-Conversion Proxy Paths
+
+Audited and fixed token/cache accounting across the proxy's format-conversion paths (Chat, Responses, and Gemini converted to Anthropic). The proxy now records the actually returned model, injects `stream_options.include_usage` so OpenAI-compatible upstreams emit usage in streaming, excludes `cache_read` and `cache_creation` from input on Claude←OpenAI paths to stop double-billing cache tokens, subtracts cached Gemini prompt tokens, still records fully-cached requests, and skips synthetic all-zero usage that previously inflated request counts (#2774).
+
+### In-App Update No Longer Hangs on Restart
+
+Installing an update from within the app no longer freezes on the "restarting" screen, leaving the new version installed but requiring a manual force-quit. The download-install-restart chain now runs entirely in the backend (a new `install_update_and_restart` command) with platform-aware install ordering and single-instance-lock teardown before re-exec, instead of depending on the old WebView to keep running JS after the app bundle was already swapped; exit requests are also classified so restart requests fall through to Tauri's default flow rather than deadlocking on the window-state plugin mutex (#4069, #4074).
+
+### Codex Upgrade No Longer Breaks the Install
+
+Upgrading Codex from the Settings "About" tab no longer leaves it throwing "Missing optional dependency @openai/codex-…" errors. The upgrade chain previously ran `codex update` first, which on an npm install is a bare reinstall that reports success even when the per-platform binary fails to land; Codex is now removed from the self-update-first path and a runnable check triggers an uninstall+reinstall self-heal (scoped to npm-managed installs) that actually re-lands the missing platform binary.
+
+### Codex OAuth Auth Token Preserved on Proxy Takeover
+
+Enabling proxy takeover for a Codex provider no longer strips the `ANTHROPIC_AUTH_TOKEN` placeholder, which previously broke Claude Code's login on hot-switches, fresh installs, and configs already stripped by older releases. The placeholder is now injected unconditionally for managed (non-Copilot) Codex providers, including URL-only ones; GitHub Copilot behavior (API_KEY only) is unchanged (#3789, #3784).
+
+### Takeover-Residue Recovery Across Config-Dir Switches
+
+Restarting the app after changing the config directory while proxy takeover is active no longer leaves Claude/Codex/Gemini pointed at a dead local proxy. The old instance now restores the taken-over live files before restarting, the first-run import refuses to persist a takeover placeholder as a provider, and SSOT restore validates that the current provider's config is free of placeholders before writing it back (#4076).
+
+### Mislabeled SSE Bodies in Format-Transform Fallback
+
+Requests routed through Claude/Codex format conversion no longer fail with an opaque 422 "Failed to parse upstream response" when a MaaS gateway force-streams a `stream:false` request and returns an SSE body under a non-SSE Content-Type. The proxy now sniffs for SSE on parse failure, aggregates the chunks into a single JSON, and runs the existing converter so clients still get a valid non-stream response; remaining parse failures are enriched with content-type, encoding, and body-snippet diagnostics, and deflate decoding now tries zlib before raw (#2234).
+
+### Duplicate YAML Keys in Hermes Config
+
+Hermes config writes no longer accumulate duplicate top-level keys (e.g. `mcp_servers`) that caused "Failed to parse Hermes config as YAML: duplicate entry with key" errors. Section replacement now strips all stale occurrences from the remainder instead of degrading into appends, the dedup safety net handles both LF and CRLF line endings, and healing keeps the last (newest) occurrence to match Hermes's own last-wins PyYAML semantics (#3267, #3633, #2973, #2529, #3310, #3762).
+
+### Usage Query Resilience and Error Clarity
+
+Usage cards no longer flip to red on a single transient blip: queries now retry once and keep showing the last successful result for up to 10 minutes on network/timeout/5xx failures, while deterministic failures (auth, empty key, unknown provider, 4xx) surface immediately and clear the snapshot so a stale quota can't resurface after credentials change. Native balance/coding-plan/subscription timeouts were raised from 10s to 15s for slow cross-border endpoints, and coding-plan now returns explicit "API key is empty" / "Unknown coding plan provider" errors instead of a blank failure.
+
+### Usage Script Provider Credential Resolution
+
+Custom JS-script usage queries resolved `{{apiKey}}` / `{{baseUrl}}` by guessing env fields only, so providers that store credentials elsewhere (e.g. Codex's `auth.OPENAI_API_KEY` plus `config.toml` base_url) always got empty values and failed despite being fully configured. Script queries and the test/preview now reuse the same per-app credential resolver as the native balance path, with explicit non-empty script values still taking precedence (#1479).
+
+### Claude Code Workflow Sub-Agent Usage Counted
+
+Local (no-proxy) session-log usage accounting missed Claude Code Workflow sub-agent traffic, under-counting overall usage by roughly 4.1% (concentrated in workflow/subagent transcripts). The scanner now descends into the deeper `subagents/workflows/wf_*/` transcript directories, and the parser no longer drops billable assistant messages that lack a `stop_reason` but already incurred input/cache token cost; dedup is unchanged so no usage is double-counted.
+
+### Codex Image Rectifier for /responses Text-Only Upstreams
+
+Codex `/responses` requests carrying images and routed to text-only OpenAI-chat models (e.g. DeepSeek `deepseek-v4-flash`) no longer fail with HTTP 400 "unknown variant `image_url`". The media rectifier now also covers the Codex adapter, scanning the responses `input` for `input_image` blocks so it can proactively strip images for known text-only models and reactively retry with images replaced on upstream image-unsupported errors.
+
+### Zhipu Coding-Plan Quota Window Mislabeling
+
+The Zhipu coding-plan view no longer swaps the 5-hour and weekly quota buckets in the final hours of each weekly cycle. The two windows are now classified by the explicit `unit` field (3 = 5-hour, 6 = weekly) instead of by sorting reset-time ascending, which mislabeled them exactly when users check their weekly quota most; the old reset-time heuristic remains as a fallback (#3036).
+
+### Duplicate Provider Terminal Sessions on macOS
+
+Launching a provider terminal on macOS no longer opens an extra empty window alongside the command session; Terminal.app uses `launch` (not `activate`) on cold start and Ghostty uses an initial-command so a single session opens, with a fallback retained if the AppleScript path fails (#4156).
+
+### Claude Desktop Model-Mapping Placeholders
+
+The Claude Desktop model-mapping form previously showed mismatched example brands across the menu display name and request model columns (DeepSeek vs Kimi), implying a display name maps to an unrelated model. Both placeholders are now derived from each row's role so they stay brand-consistent, with the lightweight Haiku tier using a flash example.
+
+### Popovers Behind Fullscreen Panels
+
+Popovers and tooltips such as the provider preset search no longer render behind fullscreen panels and appear unresponsive on click; their z-index is raised above the fullscreen overlay while staying below modal dialogs.
+
+### ToggleRow Icon Shrinking
+
+Toggle row icons no longer shrink or distort when paired with long descriptions, keeping the icon at a fixed size next to multi-line text.
+
+---
+
+## Documentation
+
+### Release Notes Contributor Mentions
+
+Restored contributor mentions in the v3.16.1 and v3.16.2 release notes across all three locales.
+
+---
+
+## Upgrade Notes
+
+### Pricing Database schema v11 Auto-Migration
+
+This release adds a `pricing_model` column to `proxy_request_logs` and rebuilds the rollup by `request_model` + `pricing_model`, migrating automatically on startup with no manual action required. Historical rows have their cost frozen at write time and are not recalculated (rows with `app_type="claude"` mix native and converted sources); only real but previously un-priced takeover rows stay at zero cost until pricing is supplied and then backfilled.
+
+### Model Mapping Adds a Fourth Tier (Fable 5)
+
+The Claude Code and Claude Desktop model mappings now have four tiers (Sonnet / Opus / Fable / Haiku). Older three-tier providers pick up the `claude-fable-5` tier after being reopened and saved; leaving that tier blank means it inherits Sonnet. Note: leaving any tier blank on third-party endpoints forwards the literal model name of that tier and may 404, so fill it in as needed.
+
+### The "Kimi For Coding" Preset Needs Proxy Takeover + a Whitelisted UA
+
+The restored Codex "Kimi For Coding" preset is still rejected with 403 if used with the default `codex-cli` User-Agent. To use it, enable proxy takeover and set the custom User-Agent in the provider's advanced options to a whitelisted UA (such as `claude-cli/*`).
+
+### Provider Health Check Semantics Changed
+
+The health check changed from "send a real model request" to "HTTP reachability probe". Note that reachable ≠ usable: a host that returns 403 is reachable but may be broken for real traffic. Failover decisions remain driven solely by real proxy traffic and are unaffected by the health check.
+
+---
+
+## Risk Notice
+
+This release continues the risk notices from previous versions for reverse-proxy-style features.
+
+**Codex OAuth reverse proxy**: using a ChatGPT subscription's Codex OAuth through a reverse proxy may violate OpenAI's terms of service. See the [v3.13.0 release notes](v3.13.0-en.md#️-risk-notice) for details.
+
+**Codex third-party provider Chat routing**: when CC Switch local proxy converts and forwards Codex requests to third-party providers, each provider may have different requirements for billing, compliance, and data retention. Read the target provider's terms before use.
+
+**Claude Desktop third-party provider proxy switching**: when CC Switch's built-in proxy gateway forwards Claude Desktop requests to third-party providers, you must also follow the target provider's billing, compliance, and data-retention terms.
+
+By enabling these features, users accept the related risks. CC Switch is not responsible for account restrictions, warnings, or service suspensions caused by using these features.
+
+---
+
+## Thanks
+
+Thanks to the following contributors for the features and fixes in v3.16.3:
+
+- [#3789](https://github.com/farion1231/cc-switch/pull/3789): preserve Codex OAuth auth token on takeover, thanks @codeasier.
+- [#2774](https://github.com/farion1231/cc-switch/pull/2774): fix model / input-token recording on Completions→Anthropic, thanks @LaoYueHanNi.
+- [#4069](https://github.com/farion1231/cc-switch/pull/4069): fix the deadlock on relaunch after an in-app update, thanks @thisTom.
+- [#4156](https://github.com/farion1231/cc-switch/pull/4156): fix duplicate provider terminal sessions on macOS, thanks @thisTom.
+- [#3267](https://github.com/farion1231/cc-switch/pull/3267): fix duplicate YAML keys in the Hermes config, thanks @que3sui.
+- [#1479](https://github.com/farion1231/cc-switch/pull/1479): fix usage script provider credential resolution, thanks @pa001024.
+- [#3975](https://github.com/farion1231/cc-switch/pull/3975): add preset search and sorting, thanks @Nastem.
+- [#4183](https://github.com/farion1231/cc-switch/pull/4183): adjust the preset-provider button appearance and search-box position, thanks @WangJiati.
+- [#4077](https://github.com/farion1231/cc-switch/pull/4077): add claude-mythos-5 model pricing, thanks @osscv.
+
+Thanks also to everyone who reported usage billing, local proxy robustness, Codex upgrade, and platform compatibility issues after v3.16.2. Many of these fixes came directly from real-world reproduction details.
+
+---
+
+## Download & Install
+
+Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) and download the build for your system.
+
+### System Requirements
+
+| System | Minimum Version | Architecture |
+| ------- | ------------------------ | ----------------------------------- |
+| Windows | Windows 10 and later | x64 |
+| macOS | macOS 12 (Monterey)+ | Intel (x64) / Apple Silicon (arm64) |
+| Linux | See table below | x64 / ARM64 |
+
+### Windows
+
+| File | Description |
+| ---------------------------------------- | ------------------------------------------------ |
+| `CC-Switch-v3.16.3-Windows.msi` | **Recommended** - MSI installer with auto-update |
+| `CC-Switch-v3.16.3-Windows-Portable.zip` | Portable build, unzip and run |
+
+### macOS
+
+| File | Description |
+| -------------------------------- | ----------------------------------------------------- |
+| `CC-Switch-v3.16.3-macOS.dmg` | **Recommended** - DMG installer, drag to Applications |
+| `CC-Switch-v3.16.3-macOS.zip` | Unzip and drag to Applications, Universal Binary |
+| `CC-Switch-v3.16.3-macOS.tar.gz` | For Homebrew install and auto-update |
+
+Homebrew install:
+
+```bash
+brew install --cask cc-switch
+```
+
+Upgrade:
+
+```bash
+brew upgrade --cask cc-switch
+```
+
+### Linux
+
+Linux assets are available for both **x86_64** and **ARM64** (`aarch64`). Choose the file whose architecture tag matches your machine's `uname -m` output:
+
+- `CC-Switch-v3.16.3-Linux-x86_64.AppImage` / `.deb` / `.rpm`
+- `CC-Switch-v3.16.3-Linux-arm64.AppImage` / `.deb` / `.rpm`
+
+| Distribution | Recommended Format | Install Command |
+| --------------------------------------- | ------------------ | --------------------------------------------------------------------- |
+| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
+| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
+| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
+| Arch Linux / Manjaro | `.AppImage` | Make executable and run directly, or use AUR |
+| Other distributions / unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
diff --git a/docs/release-notes/v3.16.3-ja.md b/docs/release-notes/v3.16.3-ja.md
new file mode 100644
index 000000000..95f655463
--- /dev/null
+++ b/docs/release-notes/v3.16.3-ja.md
@@ -0,0 +1,340 @@
+# CC Switch v3.16.3
+
+> 🎉 **CC Switch が 100,000 Star を突破しました!**
+> すべてのユーザー・コントリビューター・Star をくださった方々に感謝します —— 皆さんのおかげでここまで来ました。🙏
+
+> 💎 **本リリースは Claude Fable 5 モデルの協力のもとで開発されました**——重要かつ間違えやすいロジックの整理を手伝ってくれました: ルーティングテイクオーバー時に本物の上流モデルで課金する帰属チェーン、形式変換経路でのキャッシュ token の計上と重複排除、アプリ内更新の再起動デッドロック、そして Codex 統一セッション履歴の移行 / 復元の不変条件です。本リリースの「バージョン情報」ページに **Fable 5 Verified** バッジを新設したのもこのためです。
+
+> v3.16.2 でデータの可搬性と使用量の可観測性を広げたのに続き、本リリースは「使用量の課金を本当に正確にする」ことに重きを置いています——本物の上流モデルで課金し、形式変換経路でのキャッシュの二重計上を修正し、Claude Code Workflow のサブ agent の使用量を統計に取り込み(schema v11)、使用量ダッシュボードを一通り刷新しました(全体に効くプロバイダー / モデルフィルタ、ブランドアイコンのツールバー、より安定した残量照会)。あわせて一連のローカルプロキシとプラットフォームの問題を補強し、カスタム User-Agent オーバーライド、Codex 統一セッション履歴のトグル、Claude Fable 5 階層を新設しました。
+
+**[English →](v3.16.3-en.md) | [中文版 →](v3.16.3-zh.md)**
+
+---
+
+## 利用ガイド
+
+本リリースでは **Codex 統一セッション履歴** のトグルを新設しました——セッションの移行 / 復元を伴い、操作を誤ると「セッションが消えた」と誤解しやすいため、まずこのガイドを読むことを強くおすすめします。また使用量統計の数え方とダッシュボードにも多くの調整を加えたので、あわせて以下をご覧ください:
+
+- **[Codex セッション履歴の統一: 機能紹介と利用ガイド](../guides/codex-unified-session-history-guide-ja.md)**: 「統一 / 移行 / 復元」が実際に何を変えるのか、なぜデータが本当に失われないのか、そしてセッションが見えないときの自己点検と正確な復元の方法を解説します。**このトグルを使った、またはセッションが消えたと心配な方は、まずこちらをお読みください。**
+- **[使用量統計](../user-manual/ja/4-proxy/4.4-usage.md)**: 使用量ダッシュボードのデータソース(プロキシログ、セッション同期)と集計の仕組みを確認できます。本リリースで全体に効くプロバイダー / モデルフィルタを追加し、ルーティングテイクオーバー時の本物の課金モデルを表示するようにしました。
+- **[設定](../user-manual/ja/1-getting-started/1.5-settings.md)**: カスタム User-Agent オーバーライド、Codex 統一セッション履歴などのトグルは、プロバイダーフォームの高度なオプションと設定ページにあります。
+
+---
+
+> [!WARNING]
+>
+> ## 唯一の公式チャネル(必ずお読みください)
+>
+> CC Switch は**完全に無料・オープンソース**のデスクトップアプリで、**ユーザーから料金を徴収することはありません**。本ソフトウェアは下記の公式チャネルからのみ入手してください:
+>
+> | チャネル | 唯一の公式 |
+> | ------------ | ------------------------------------------------------------------------------ |
+> | 公式サイト | **[ccswitch.io](https://ccswitch.io)** |
+> | ソースコード | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
+> | ダウンロード | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
+> | 作者 | **[@farion1231](https://github.com/farion1231)** |
+> | 偽サイト通報 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
+>
+> **料金請求・チャージ・認証情報の提供を求める「CC Switch」サイトやクライアントはすべて偽物です。** 支払いを誘導された場合は直ちに操作を中止し、GitHub Issues からご報告ください。
+
+---
+
+## 概要
+
+CC Switch v3.16.3 は v3.16.2 に続くメンテナンスアップデートです。前リリースではデータの可搬性と使用量の可観測性の拡張に集中しましたが、本リリースは「使用量の課金を本当に正確にする」ことに重きを置いています——上流が返すエイリアスではなく本物の上流モデルで課金し、形式変換(Chat / Responses / Gemini を Anthropic へ)経路でのキャッシュ token の二重計上を修正し、Claude Code Workflow のサブ agent の使用量をローカル統計に取り込み、schema v11 で各レコードが実際に使用した課金根拠を永続化しました。使用量ダッシュボードもこれにあわせて一通り刷新し、全体に効くプロバイダー / モデルフィルタ、ブランドアイコンのツールバー、より安定した残量照会(失敗時の再試行 + 前回成功した結果の保持)を追加しました。
+
+さらに本リリースでは、一連のローカルプロキシの堅牢性に関する問題(Content-Type が誤ってラベル付けされた SSE レスポンスの集約、Codex `/responses` のテキスト専用モデル向け画像整流、Codex OAuth 認証情報とテイクオーバー残留の復元、Hermes 設定の重複 YAML キー)を補強し、プロバイダー設定まわりを作り直し(カスタム User-Agent オーバーライド、Codex フォームの高度なオプションへの統合、プリセット検索とソート、Claude Fable 5 階層)、Codex 統一セッション履歴のトグルを新設し、アプリ内更新のハング、Codex のアップグレードによるインストール破損、macOS の重複ターミナルウィンドウなどの問題を修正しました。
+
+**リリース日**: 2026-06-14
+
+**Stats**: 59 commits | 130 files changed | +10,223 / -4,232 lines
+
+---
+
+## ハイライト
+
+- **使用量の課金がより正確に**: ルーティングテイクオーバーのトラフィックを本物の上流モデルで課金するようになり(上流が返すエイリアスではなく)、形式変換経路でキャッシュ token を input に二重計上しなくなり、Claude Code Workflow のサブ agent の使用量も統計に取り込みました——schema v11 で課金根拠を永続化します。
+- **使用量ダッシュボードの刷新**: プロバイダー / モデルフィルタをリクエストログテーブルから全体フィルタへ引き上げ、アプリフィルタをブランドアイコンに変更し、残量照会に失敗時の再試行と「前回成功した結果の保持」を追加して、一度のネットワークのゆらぎでカードが赤くならないようにしました。
+- **カスタム User-Agent オーバーライド**: プロバイダーにカスタム UA を設定でき、転送・接続性チェック・モデル一覧の 3 か所で一貫して有効になり、UA ホワイトリストで制限する Coding Plan 上流を通過できます(これにより Codex「Kimi For Coding」プリセットを復活させました)。
+- **Codex 統一セッション履歴**: 公式 Codex セッションとサードパーティセッションが同じ resume 履歴バケットを共有できる任意のトグルを新設し、既存セッションの任意移行と台帳に基づく精密な復元を備えます。
+- **プロキシとプラットフォームの補強**: 誤ラベルの SSE レスポンスの集約、Codex 画像整流、テイクオーバー残留の復元、Hermes YAML 重複排除。アプリ内更新が「再起動中」でハングしなくなり、Codex のアップグレードでインストールを壊さなくなりました。
+
+---
+
+## 追加機能
+
+### カスタム User-Agent オーバーライド
+
+プロバイダー設定でカスタム User-Agent を設定できるようになり、プロキシがリクエスト転送、接続性チェック、モデル一覧(`GET /v1/models`)の 3 つの経路で一貫して適用します。これにより、UA ホワイトリストで制限する Coding Plan 上流で「検出は失敗 / モデル一覧は 403 なのにプロキシ本体は正常に動く」という不整合が起きなくなります。Claude と Codex のフォームはいずれも高度なオプションでこのフィールドを公開し、厳選した UA プリセットのドロップダウン(Claude Code / Kilo Code など UA ホワイトリストを通過できるファミリー)とリアルタイムで非ブロッキングな形式検証を備えます。公式プリセットへ切り替えると残っていたカスタム UA は破棄され、リクエストヘッダーを密かに変更しないようにします([#3671](https://github.com/farion1231/cc-switch/pull/3671))。
+
+### Codex 統一セッション履歴
+
+任意のトグル(設定 → Codex アプリ拡張)を新設し、公式 Codex セッションと CC Switch のサードパーティセッションが同じ resume 履歴バケットを共有できるようにしました。resume セレクタが両者を互いに隠さなくなります。有効化すると、live の `config.toml` は公式の実行を、内蔵 OpenAI プロバイダーをミラーした共有 `custom` model_provider へルーティングします(`auth.json` は変更しません)。デフォルトでは今後のセッションにのみ有効です。有効化ダイアログには既存の公式セッションを共有バケットへ移行できるチェックボックスがあり(世代ごとのバックアップ付き)、無効化ダイアログにはバックアップ台帳に基づく精密な復元が用意されています——バックアップ内で `openai` として記録されたセッションのみを巻き戻し、有効化中に新規作成されたセッションは決して変更しません。
+
+### 使用量ダッシュボードの全体プロバイダー / モデルフィルタ
+
+プロバイダーフィルタとモデルフィルタを、リクエストログテーブルの内部からトップバーへ引き上げ、Hero サマリー、トレンドグラフ、リクエストログ、2 つの統計タブ全体に効くようにしました。ダッシュボード全体を特定のソースとモデルで絞り込めます。ソースは表示名で厳密に一致するため「Claude (Session)」のようなセッションのプレースホルダー行も選択でき、モデルは有効な課金モデルで一致し、モデルのドロップダウンは選択したソースに応じてカスケードし、どちらの一覧も現在の期間にデータがある選択肢のみを表示します。
+
+### モデル価格シードの刷新
+
+`seed_model_pricing` の全件価格点検を実施しました: 9 個のモデルの価格を新規追加し(Claude Fable 5、Grok 4.3、Mistral Medium 3.5 / Small 4、Qwen 3.7 Max/Plus などを含む)、各ベンダー公式の定価に合わせて既存価格 28 か所を訂正し(GLM、Grok、MiMo、Doubao、Kimi、MiniMax、Mistral、Qwen)、使用量コストの見積りをより正確にしました。各変更はシード(新規インストールに影響)を更新すると同時に、`repair_current_model_pricing` に旧→新のガードを 1 件追加します(既存データベースを修復し、ユーザーが手動で編集した行は上書きしません)。
+
+### Claude Fable 5 モデル階層
+
+プロバイダーフォームは、Claude Code と Claude Desktop の両プロキシ経路で `claude-fable-5` を 4 つ目のモデルマッピング階層として公開するようになりました。フォールバックチェーンは fable → opus → default で、公式の降格と一致し、Claude Desktop 1.12603.1+ の検証器で `fable-` プレフィックスを許可しました。4 言語のフォールバックヒントも明確化しました: サードパーティの endpoint である階層を空のままにすると、その階層のモデル名がそのまま透過されて 404 になります([#3980](https://github.com/farion1231/cc-switch/issues/3980)、[#4026](https://github.com/farion1231/cc-switch/issues/4026)、[#4049](https://github.com/farion1231/cc-switch/issues/4049))。
+
+### Unity2.ai パートナープロバイダー
+
+Unity2.ai(AI API 中継のパートナー)をプリセットとして追加し、管理対象の 7 アプリすべて(Claude Code、Codex、Gemini、OpenCode、OpenClaw、Claude Desktop、Hermes)をカバーしました。各プリセットには紹介登録リンクを付け、4 言語でパートナー宣伝文を補いました。Codex は素の base URL を使用し(このゲートウェイはルートパスに `/responses` を公開)、OpenCode / OpenClaw / Hermes は `/v1` chat-completions の endpoint を使用し、`gpt-5.5` を既定モデルとします。
+
+### Kimi K2.7 Code モデル
+
+`kimi-k2.7-code` モデル(入力 $0.95 / 出力 $4.00 / キャッシュ読み取り $0.19、100 万 token あたり、256K コンテキスト)を新規追加し、6 つの公式 Moonshot Kimi プリセットすべて(Claude Code、Codex、Claude Desktop、Hermes、OpenCode、OpenClaw)をこれに向けました。OpenCode / OpenClaw のプリセットは「Kimi K2.7 Code」へ改名しました。価格シードは起動時の冪等な挿入経路で有効になるため、既存ユーザーは移行なしで新価格を取得できます。
+
+### Codex「Kimi For Coding」プリセットの復活
+
+Codex「Kimi For Coding」プリセット(`openai_chat`、`kimi-for-coding`、256K コンテキスト)を再追加し、思考モードをデフォルトで有効にしました。以前これを削除したのは、このコーディング endpoint が Codex 既定の `codex-cli` User-Agent を 403 で拒否するためでしたが、現在はプロキシテイクオーバー + カスタム User-Agent オーバーライド(ホワイトリストの UA、例 `claude-cli/*` に設定)を使えば正常に使えます。
+
+### リクエスト詳細での課金モデル監査
+
+リクエスト詳細パネルは、「リクエストされたモデル」「課金モデル」がレスポンスのモデルと一致しないときにそれらをすべて表示するようになり、ルーティングテイクオーバーが生む請求を使用量画面から直接照合できます。
+
+### プリセットプロバイダーの検索とソート
+
+プリセットプロバイダーのセレクタが、検索・ソート可能な一覧になり、インライン検索ボックスを備えました(虫眼鏡アイコンで切り替え、ESC または外側クリックで畳む)。ボタンはレスポンシブグリッドに変わってサイズが統一され、既定アイコンを表示します。検索はプロバイダーの表示名 / 生の名前のみに一致するため、URL の断片や共有のカテゴリラベルがノイズ一致を生まなくなります([#3975](https://github.com/farion1231/cc-switch/pull/3975)、[#4183](https://github.com/farion1231/cc-switch/pull/4183))。
+
+### Claude Mythos 5 の価格
+
+内蔵のモデル / 価格表に `claude-mythos-5` モデル(入力 $10 / 出力 $50、100 万 token あたり;キャッシュ読み取り $1.00、キャッシュ書き込み $12.50)を登録し、使用量統計が正しく課金・表示できるようにしました([#4077](https://github.com/farion1231/cc-switch/pull/4077))。
+
+### Fable 5 Verified バッジ
+
+設定の「バージョン情報」ページが、アプリ名とバージョンの隣に Fable 5 Verified バッジを表示し、これが特別ビルドであることを示すようになりました。バージョンバッジもアプリ名の下に中央揃えしました。
+
+---
+
+## 変更
+
+### Claude Desktop の使用量を Claude に折りたたみ
+
+ダッシュボードは独立した「Claude Desktop」バケットを表示しなくなりました——これは常に不完全な数字しか表示できませんでした(Desktop のチャット使用量はそもそもプロキシを経由せず、その Code タブのセッションは内蔵の Claude Code ランタイムが共有の `~/.claude/projects` ディレクトリへ書き込んでいるだけです)。Desktop のプロキシトラフィックは表示上 `claude` に折りたたまれますが、記帳層はルーティングテイクオーバー課金の監査のために引き続き自身の `app_type` で記録し、本物の値はリクエスト詳細パネルで確認できます。
+
+### 軽量化したプロバイダーヘルスチェック
+
+プロバイダーヘルスチェックは、本物のストリーミングモデルリクエストを送らなくなりました(多くのサードパーティプロバイダーが 401/403/WAF でブロックし、利用不可の誤検知を生むため)。代わりにプロバイダーの `base_url` へ軽量な HTTP 到達性プローブを 1 回行います: あらゆる HTTP レスポンスを到達可能とみなし、DNS / 接続 / TLS / タイムアウトのみを失敗とします。公式プロバイダー(OAuth を使用し、base_url が意図的に空で、信頼できる到達性ターゲットがない)は接続性チェックのボタンを隠します。従来の「本物のリクエストを送る」確認ダイアログ、テストモデル / プロンプトのフィールドは削除し、劣化レイテンシのしきい値を 6s、タイムアウトを 8s としました。この到達性チェックは決してサーキットブレーカーをリセットしません——到達可能 ≠ 利用可能(403 を返す host は到達可能でも、本物のトラフィックには壊れています)。フェイルオーバーの判定は引き続き本物のプロキシトラフィックのみで駆動されます。
+
+### Codex の高度なオプション領域の統合
+
+Codex プロバイダーフォームは、ローカルルーティング、モデルマッピング、推論オーバーライド、カスタム User-Agent を展開可能な高度なオプション領域に折りたたみ、Claude フォームと揃えました(UA が設定されているか、ローカルルーティングが有効なときは自動展開)。カスタム User-Agent はネイティブ Responses プロバイダーでも設定できるようになりました。以前は `openai_chat` ルーティングを有効にしたときにしか触れられませんでした。
+
+### 使用量ツールバーとレイアウトの刷新
+
+アプリフィルタはブランドアイコン(ProviderIcon 経由、「すべて」はグリッドアイコン)で描画するように変更し、狭いウィンドウで折り返すと見栄えの悪かったテキストタブを置き換えました。使用量 Hero も選択したアプリのブランドアイコンを表示し、Codex のテーマ色をエメラルドからニュートラルグレーへ変更して、OpenAI のモノクロブランドに合わせました。クリックで循環切り替えしていた更新ボタンは、ローカライズした「オフ」ラベルを持つドロップダウン選択に変更し、トップバーのコントロールも圧縮して幅のグループを揃え、長すぎる日付範囲のラベルは省略表示するようにしました。
+
+### バージョン情報パネルの読み込みを高速化
+
+設定の「バージョン情報」パネルが段階的に読み込むようになりました: アプリのバージョンバッジは解決した瞬間に表示され、ツールのプローブを待たなくなります。各ツールカードは自身のバージョン検出が完了した時点で即座に更新されます(プローブは直列ではなく並行に実行)。プローブ結果はアプリのセッション中、10 分の TTL 付きでキャッシュされるため、「バージョン情報」タブを再度開くとキャッシュ値を再利用し、期限切れの項目だけをバックグラウンドで再検証します。毎回 6 つのツールすべてを再プローブすることはなくなりました。
+
+### 火山方舟 Coding Plan の宣伝更新
+
+火山方舟(Volcengine Ark)プリセットを 6 アプリすべてで新しい Coding Plan 招待リンクへ更新し(旧 Agent Plan / キャンペーンリンクを置き換え)、4 言語でパートナー宣伝文を刷新しました(2 か月 75% 割引 + 招待コード 6J6FV5N2)。製品名も Agent Plan から Coding Plan へ訂正しました。
+
+### MiniMax を通常プロバイダーへ降格
+
+MiniMax の金色のパートナースター印と API key 宣伝バナーを削除し(全プリセットから `isPartner` フラグを除去)、引き続き通常の `cn_official` プロバイダーとしてアイコンとテーマを保持します。宣伝文は休眠状態のまま残し、必要であれば 1 行で提携関係を再有効化できます。
+
+### LemonData を削除、SudoCode を降格
+
+LemonData プロバイダープリセットを完全に削除し(宣伝文、アイコン、スポンサー項目もあわせて)、SudoCode をパートナーから通常の `third_party` プロバイダーへ降格しました(`isPartner` フラグと宣伝文を外し、アイコンは保持)。
+
+### AtlasCloud Codex GLM 5.1 のコンテキストウィンドウ
+
+AtlasCloud Codex プリセットの `zai-org/glm-5.1` モデルに 200,000 token のコンテキストウィンドウを宣言し、ほかの GLM 5.1 プリセット項目に揃えました。
+
+---
+
+## 修正
+
+### ルーティングテイクオーバーのトラフィックを本物の上流モデルで課金
+
+リクエストが別の上流へルーティングされた場合(env モデルマッピング、Claude Desktop ルーティング、Copilot 正規化、Codex chat オーバーライド)、プロキシは以前、上流が返したモデルで帰属・課金していたため、kimi / glm の token を `claude-*` として記録・課金し、コストが約 5〜25 倍に過大評価されていました。現在は転送器が本物のアウトバウンドモデルを捕捉し、「上流が返した値 → アウトバウンドモデル → クライアントのエイリアス」の順で帰属し、各行に実際に使用した課金根拠を永続化します(schema v11)。この根拠はコストのバックフィルと 30 日 rollup のプルーニングまで一貫して使われます。Claude Desktop のトラフィックも自身の `app_type` で記録されるようになり、その価格オーバーライドが正しく効くようになりました。
+
+### 形式変換経路での使用量計上
+
+プロキシの各形式変換経路(Chat、Responses、Gemini を Anthropic へ)での token / キャッシュの計上を監査・修正しました。プロキシは実際に返ったモデルを記録し、`stream_options.include_usage` を注入して OpenAI 互換の上流がストリーミング時に usage を吐くようにし、Claude←OpenAI 経路では `cache_read` と `cache_creation` を input から除外してキャッシュ token の二重計上を防ぎ、Gemini のキャッシュ済みプロンプト token を差し引き、完全にキャッシュヒットしたリクエストも引き続き記録し、過去にリクエスト数を水増ししていた合成の全ゼロ usage をスキップするようになりました([#2774](https://github.com/farion1231/cc-switch/pull/2774))。
+
+### アプリ内更新がハングしなくなった
+
+アプリ内から更新をインストールするとき、「再起動中」の画面でハングしなくなりました——以前は新版がインストール済みなのに、手動で強制終了せざるを得ない状況が起きていました。ダウンロード—インストール—再起動の一連の流れは、完全にバックエンドで実行するようになり(`install_update_and_restart` コマンドを新設)、プラットフォームごとにインストール順序を決め、再実行の前にまず単一インスタンスロックを破棄します。アプリパッケージがすでに置き換えられた後に古い WebView が JS を走らせ続けることに依存しなくなりました。終了リクエストも分類して、再起動リクエストが Tauri の既定フローに落ちるようにし、ウィンドウ状態プラグインのミューテックスでデッドロックしないようにしました([#4069](https://github.com/farion1231/cc-switch/pull/4069)、[#4074](https://github.com/farion1231/cc-switch/pull/4074))。
+
+### Codex のアップグレードがインストールを壊さなくなった
+
+設定の「バージョン情報」ページから Codex をアップグレードしても、「Missing optional dependency @openai/codex-…」エラーを投げなくなりました。アップグレードのチェーンは以前まず `codex update` を実行しますが、これは npm インストール下では実質的に素の再インストールであり、対応するプラットフォームのバイナリがインストールされていなくても成功を報告していました。現在は Codex を「self-update 優先」経路から除外し、runnable 検出が「アンインストール + 再インストール」の自己修復を駆動するようにしました(npm 管理のインストールに限定)。これが、欠けたプラットフォームバイナリを本当に補える唯一の修正です。
+
+### テイクオーバー時に Codex OAuth 認証情報を保持
+
+Codex プロバイダーでプロキシテイクオーバーを有効にするとき、`ANTHROPIC_AUTH_TOKEN` プレースホルダーを剥がさなくなりました——以前これはホットスイッチ、新規インストール、そして旧バージョンがすでに剥がしてしまった live 設定で、Claude Code のログインを壊していました。現在は管理対象(非 Copilot)の Codex プロバイダーに対して、URL のみのプロバイダーを含め無条件にこのプレースホルダーを注入します。GitHub Copilot の挙動(API_KEY のみ)は変わりません([#3789](https://github.com/farion1231/cc-switch/pull/3789)、[#3784](https://github.com/farion1231/cc-switch/issues/3784))。
+
+### 設定ディレクトリをまたぐ切り替えでのテイクオーバー残留の復元
+
+プロキシテイクオーバーが有効なときに設定ディレクトリを変更してアプリを再起動しても、Claude / Codex / Gemini を失効したローカルプロキシに向けたままにしなくなりました。現在は旧インスタンスが再起動の前にテイクオーバーされた live ファイルを先に復元し、初回実行のインポートはテイクオーバープレースホルダーをプロバイダーとして永続化することを拒否し、SSOT の復元も書き戻す前に、現在のプロバイダーの設定にプレースホルダーが含まれないことを検証します([#4076](https://github.com/farion1231/cc-switch/pull/4076))。
+
+### 形式変換フォールバックでの誤ラベル SSE レスポンスの集約
+
+Claude / Codex の形式変換を経たリクエストで、MaaS ゲートウェイが `stream:false` のリクエストを強制的にストリーミングし、非 SSE の Content-Type で SSE レスポンスボディを返したとき、難解な 422「Failed to parse upstream response」で失敗しなくなりました。プロキシは解析失敗時に SSE かどうかを検出し、チャンクを単一の JSON に集約してから既存の変換器を走らせ、クライアントが引き続き有効な非ストリーミングレスポンスを受け取れるようにします。残った解析失敗には content-type、エンコーディング、レスポンスボディの抜粋などの診断情報を付け、deflate のデコードも先に zlib を、次に素のストリームを試すように変更しました([#2234](https://github.com/farion1231/cc-switch/pull/2234))。
+
+### Hermes 設定の重複 YAML キー
+
+Hermes 設定の書き込みは、重複したトップレベルキー(`mcp_servers` など)を累積しなくなりました。これは「Failed to parse Hermes config as YAML: duplicate entry with key」エラーを引き起こしていました。セクションの置換は、追加へ退化する代わりに、残りのテキストから古いコピーをすべて取り除くようになりました。重複排除のセーフティネットは LF と CRLF の行末を両方処理します。修復時には最後(最新)のコピーを保持し、Hermes 自身の PyYAML ベースの「後勝ち」セマンティクスに揃えます([#3267](https://github.com/farion1231/cc-switch/pull/3267)、[#3633](https://github.com/farion1231/cc-switch/issues/3633)、[#2973](https://github.com/farion1231/cc-switch/issues/2973)、[#2529](https://github.com/farion1231/cc-switch/issues/2529)、[#3310](https://github.com/farion1231/cc-switch/issues/3310)、[#3762](https://github.com/farion1231/cc-switch/issues/3762))。
+
+### 使用量照会の堅牢性とエラーの明確さ
+
+使用量カードは、一度の瞬間的なゆらぎだけで赤くならなくなりました: 照会は一度再試行し、ネットワーク / タイムアウト / 5xx のような一時的な失敗下では前回成功した結果を最大 10 分間表示し続けます。一方、確定的な失敗(認証、空の key、未知のプロバイダー、4xx)は即座に表面化してスナップショットをクリアし、認証情報の変更後に古い残量が再び現れるのを防ぎます。ネイティブ残量 / Coding Plan / サブスクリプション照会のタイムアウトは、応答の遅い国際 endpoint に合わせて 10s から 15s へ引き上げました。Coding Plan も空白の失敗ではなく、明確な「API key is empty」/「Unknown coding plan provider」エラーを返すようになりました。
+
+### 使用量スクリプトのプロバイダー認証情報の解決
+
+カスタム JS スクリプトの使用量照会は、以前 env フィールドを推測して `{{apiKey}}` / `{{baseUrl}}` を解決していたため、認証情報を別の場所に置くアプリ(Codex の `auth.OPENAI_API_KEY` に加え `config.toml` の base_url など)は、プロバイダーが完全に設定されていても常に空の値となり失敗していました。スクリプト照会とそのテスト / プレビューは、ネイティブ残量経路と同じアプリごとの認証情報リゾルバを再利用するようになり、スクリプト内で明示的に記入した非空の値は引き続き優先されます([#1479](https://github.com/farion1231/cc-switch/pull/1479))。
+
+### Claude Code Workflow サブ agent の使用量集計
+
+ローカル(プロキシなし)のセッションログ使用量集計は、以前 Claude Code Workflow のサブ agent のトラフィックを取りこぼしており、全体の使用量が約 4.1% 過小評価されていました(workflow / subagent のセッションレコードに集中)。スキャナーはさらに一段深い `subagents/workflows/wf_*/` のレコードディレクトリまで掘り下げるようになり、パーサーも `stop_reason` を欠いているがすでに input / キャッシュ token のコストを生んだ assistant メッセージを捨てなくなりました。重複排除のロジックは変わらないため、重複計上はしません。
+
+### Codex `/responses` のテキスト専用モデル向け画像整流
+
+画像を伴い、テキストのみ対応の OpenAI-chat モデル(DeepSeek `deepseek-v4-flash` など)へルーティングされた Codex `/responses` リクエストが、HTTP 400「unknown variant `image_url`」で失敗しなくなりました。メディア整流器が Codex アダプターもカバーするようになり、responses の `input` 内の `input_image` ブロックをスキャンします。これにより、既知のテキスト専用モデルに対しては画像をプロアクティブに剥がし、上流が「画像非対応」を報告したときにも画像を置き換えて再試行できます。
+
+### 智譜 Coding Plan のクォータウィンドウの誤ラベル
+
+智譜 Coding Plan ビューは、各週周期の最後の数時間で 5 時間ウィンドウと週ウィンドウを取り違えてラベル付けしなくなりました。両ウィンドウは今や明示的な `unit` フィールドで分類され(3 = 5 時間、6 = 週)、リセット時刻の昇順ソートに頼らなくなりました——後者はユーザーが週クォータを最も照会するタイミングで、ちょうど両者を取り違えてラベル付けしていました。フィールドが欠けているときは引き続き従来のリセット時刻ヒューリスティックへフォールバックします([#3036](https://github.com/farion1231/cc-switch/pull/3036))。
+
+### macOS の重複プロバイダーターミナルウィンドウ
+
+macOS でプロバイダーターミナルを起動するとき、コマンドセッションの隣に空のウィンドウをもう 1 つ開かなくなりました。Terminal.app はコールドスタート時に `activate` ではなく `launch` を使い、Ghostty は初期コマンドを使うことで、単一のセッションだけを開きます。AppleScript 経路が失敗したときのフォールバックも残してあります([#4156](https://github.com/farion1231/cc-switch/pull/4156))。
+
+### Claude Desktop モデルマッピングのプレースホルダー
+
+Claude Desktop モデルマッピングフォームは、以前「メニュー表示名」と「リクエストモデル」の 2 列で一貫しないブランド例(DeepSeek vs Kimi)を使い、ある表示名が無関係なモデルへマッピングされるかのように見せていました。現在は両方のプレースホルダーが各行のロールから導かれ、ブランドの一貫性を保ち、軽量な Haiku 階層は flash の例を使います。
+
+### ポップオーバーが全画面パネルに隠れる
+
+プロバイダープリセット検索のようなポップオーバーやツールチップが、全画面パネルの後ろに描画されてクリックが効かないように見える問題がなくなりました。これらの z-index を全画面オーバーレイの上に引き上げつつ、モーダルダイアログよりは低く保ちました。
+
+### ToggleRow アイコンの縮み
+
+トグル行のアイコンは、長い説明と並んでも縮んだり歪んだりしなくなり、複数行のテキストの隣でアイコンが固定サイズを保ちます。
+
+---
+
+## ドキュメント
+
+### Release Notes の貢献者謝辞の復元
+
+v3.16.1 と v3.16.2 の release notes の貢献者謝辞を 3 言語で復元しました。
+
+---
+
+## アップグレード時の注意
+
+### 価格ライブラリ schema v11 の自動移行
+
+本リリースは `proxy_request_logs` に `pricing_model` 列を新設し、`request_model` + `pricing_model` で rollup を再構築しました。起動時に自動移行し、手動操作は不要です。過去の行のコストは書き込み時に確定済みで再計算されません(`app_type="claude"` の行はネイティブと変換の 2 種類のソースが混在しています)。本物だが当時課金されなかったテイクオーバー行のみがゼロコストのまま残り、価格が補われた後にバックフィルされます。
+
+### モデルマッピングに 4 つ目の階層(Fable 5)を追加
+
+Claude Code と Claude Desktop のモデルマッピングは 4 階層(Sonnet / Opus / Fable / Haiku)になりました。従来の 3 階層プロバイダーは、再度開いて保存すると `claude-fable-5` 階層が補われます。この階層を空のままにすると Sonnet を継承します。注意: サードパーティの endpoint でいずれかの階層を空のままにすると、その階層のモデル名がそのまま透過されて 404 になる可能性があるため、必要に応じて記入してください。
+
+### 「Kimi For Coding」プリセットはプロキシテイクオーバー + ホワイトリスト UA が必要
+
+復活した Codex「Kimi For Coding」プリセットは、既定の `codex-cli` User-Agent をそのまま使うと依然 403 になります。利用するには、プロキシテイクオーバーを有効にし、プロバイダーの高度なオプションでカスタム User-Agent をホワイトリストの UA(`claude-cli/*` など)に設定してください。
+
+### プロバイダーヘルスチェックのセマンティクス変更
+
+ヘルスチェックは「本物のモデルリクエストを送る」から「HTTP 到達性プローブ」へ変わりました。到達可能 ≠ 利用可能であることにご注意ください: 403 を返す host は到達可能でも、本物のトラフィックには壊れている可能性があります。フェイルオーバーの判定は引き続き本物のプロキシトラフィックのみで駆動され、ヘルスチェックの影響を受けません。
+
+---
+
+## リスク通知
+
+本リリースは、リバースプロキシ系機能に関する以前のリスク通知を引き続き適用します。
+
+**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションの Codex OAuth をリバースプロキシ経由で使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 release notes](v3.13.0-ja.md#️-リスクに関する注意事項) を参照してください。
+
+**Codex サードパーティプロバイダー Chat ルーティング**: CC Switch ローカルプロキシで Codex リクエストを変換し、サードパーティプロバイダーへ転送する場合、課金・コンプライアンス・データ保持に関する制約はプロバイダーごとに異なります。利用前に対象プロバイダーの利用規約を確認してください。
+
+**Claude Desktop サードパーティプロバイダープロキシ切り替え**: CC Switch 内蔵のプロキシゲートウェイで Claude Desktop のリクエストをサードパーティプロバイダーへ転送する場合も、対象プロバイダーの課金・コンプライアンス・データ保持に関する規約に従う必要があります。
+
+上記機能を有効化したユーザーは、関連するリスクを自ら負うものとします。CC Switch は、これらの機能の利用によって発生したアカウント制限、警告、サービス停止について責任を負いません。
+
+---
+
+## 謝辞
+
+v3.16.3 で機能と修正を届けてくださった以下のコントリビューターに感謝します:
+
+- [#3789](https://github.com/farion1231/cc-switch/pull/3789): テイクオーバー時に Codex OAuth 認証情報を保持、@codeasier に感謝。
+- [#2774](https://github.com/farion1231/cc-switch/pull/2774): Completions を Anthropic へ変換する際に実際に返ったモデルを記録せず input token の計算が誤っていた問題を修正、@LaoYueHanNi に感謝。
+- [#4069](https://github.com/farion1231/cc-switch/pull/4069): アプリ内更新後の再起動デッドロックを修正、@thisTom に感謝。
+- [#4156](https://github.com/farion1231/cc-switch/pull/4156): macOS の重複プロバイダーターミナルウィンドウを修正、@thisTom に感謝。
+- [#3267](https://github.com/farion1231/cc-switch/pull/3267): Hermes 設定の重複 YAML キーを修正、@que3sui に感謝。
+- [#1479](https://github.com/farion1231/cc-switch/pull/1479): 使用量スクリプトのプロバイダー認証情報の解決を修正、@pa001024 に感謝。
+- [#3975](https://github.com/farion1231/cc-switch/pull/3975): プリセットプロバイダーの検索とソートを追加、@Nastem に感謝。
+- [#4183](https://github.com/farion1231/cc-switch/pull/4183): プリセットプロバイダーボタンの外観と検索ボックスの位置を調整、@WangJiati に感謝。
+- [#4077](https://github.com/farion1231/cc-switch/pull/4077): claude-mythos-5 モデルの価格を追加、@osscv に感謝。
+
+v3.16.2 リリース後に使用量の課金、ローカルプロキシの堅牢性、Codex のアップグレード、プラットフォーム互換性の問題を報告してくださったすべてのユーザーにも感謝します。今回の多くの修正は、実際の利用シーンから得られた再現情報に基づいています。
+
+---
+
+## ダウンロードとインストール
+
+[Releases](https://github.com/farion1231/cc-switch/releases/latest) から、お使いのシステムに対応するビルドをダウンロードしてください。
+
+### システム要件
+
+| システム | 最低バージョン | アーキテクチャ |
+| -------- | ------------------------ | ----------------------------------- |
+| Windows | Windows 10 以降 | x64 |
+| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
+| Linux | 下表を参照 | x64 / ARM64 |
+
+### Windows
+
+| ファイル | 説明 |
+| ---------------------------------------- | -------------------------------------------- |
+| `CC-Switch-v3.16.3-Windows.msi` | **推奨** - 自動更新対応の MSI インストーラー |
+| `CC-Switch-v3.16.3-Windows-Portable.zip` | ポータブル版、展開してそのまま実行できます |
+
+### macOS
+
+| ファイル | 説明 |
+| -------------------------------- | ------------------------------------------------------ |
+| `CC-Switch-v3.16.3-macOS.dmg` | **推奨** - DMG インストーラー、Applications へドラッグ |
+| `CC-Switch-v3.16.3-macOS.zip` | 展開して Applications へドラッグ、Universal Binary |
+| `CC-Switch-v3.16.3-macOS.tar.gz` | Homebrew インストールと自動更新用 |
+
+Homebrew インストール:
+
+```bash
+brew install --cask cc-switch
+```
+
+更新:
+
+```bash
+brew upgrade --cask cc-switch
+```
+
+### Linux
+
+Linux アセットは **x86_64** と **ARM64**(`aarch64`)の両方を提供します。ファイル名にアーキテクチャ識別子が含まれているため、マシンの `uname -m` 出力に合わせて選択してください:
+
+- `CC-Switch-v3.16.3-Linux-x86_64.AppImage` / `.deb` / `.rpm`
+- `CC-Switch-v3.16.3-Linux-arm64.AppImage` / `.deb` / `.rpm`
+
+| ディストリビューション | 推奨形式 | インストール方法 |
+| --------------------------------------- | ----------- | ------------------------------------------------------------------------- |
+| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
+| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
+| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
+| Arch Linux / Manjaro | `.AppImage` | 実行権限を付与して直接起動、または AUR を使用 |
+| その他 / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
diff --git a/docs/release-notes/v3.16.3-zh.md b/docs/release-notes/v3.16.3-zh.md
new file mode 100644
index 000000000..725269019
--- /dev/null
+++ b/docs/release-notes/v3.16.3-zh.md
@@ -0,0 +1,340 @@
+# CC Switch v3.16.3
+
+> 🎉 **CC Switch 突破 100,000 Star!**
+> 感谢每一位用户、贡献者与 Star —— 是你们让它走到这里。🙏
+
+> 💎 **本版由 Claude Fable 5 模型协助开发**——它帮忙梳理清楚了多处关键且容易出错的逻辑:路由接管时按真实上游模型计费的归因链、格式转换路径上缓存 token 的计量与去重、应用内更新的重启死锁,以及 Codex 统一会话历史的迁移 / 还原不变量。这也是本版在「关于」页新增 **Fable 5 Verified** 标识的由来。
+
+> 在 v3.16.2 拓宽数据可携带性与用量观测之后,这一版把重心放在「让用量计费真正准确」——按真实上游模型计费、修正格式转换路径上的缓存双算、把 Claude Code Workflow 子 agent 的用量纳入统计(schema v11),并对用量看板做了一轮改版(全局供应商 / 模型筛选、品牌图标工具栏、更稳的额度查询);同时加固了一批本地代理与平台问题,新增自定义 User-Agent 覆盖、Codex 统一会话历史开关与 Claude Fable 5 档位。
+
+**[English →](v3.16.3-en.md) | [日本語版 →](v3.16.3-ja.md)**
+
+---
+
+## 使用攻略
+
+本版新增了 **Codex 统一会话历史** 开关——它涉及会话的迁移 / 还原,操作不当时容易让人误以为"会话丢了",强烈建议先读这篇攻略;用量统计的口径和看板这一版也做了较多调整,一并附上:
+
+- **[Codex 统一会话历史:功能介绍与使用攻略](../guides/codex-unified-session-history-guide-zh.md)**:讲清"统一 / 迁移 / 还原"到底改了什么、为什么数据不会真正丢失,以及看不到会话时如何自查与精确还原。**用过这个开关、或担心会话丢失,请务必先读。**
+- **[用量统计](../user-manual/zh/4-proxy/4.4-usage.md)**:了解用量看板的数据来源(代理日志、会话同步)与统计口径,本版新增了全局的供应商 / 模型筛选,并把路由接管的真实计价模型展示了出来。
+- **[设置](../user-manual/zh/1-getting-started/1.5-settings.md)**:自定义 User-Agent 覆盖、Codex 统一会话历史等开关都在供应商表单的高级选项与设置页里。
+
+---
+
+> [!WARNING]
+>
+> ## 唯一官方渠道声明(请务必阅读)
+>
+> CC Switch 是**完全免费、开源**的桌面应用,**不会向用户收取任何费用**。请仅通过下列官方渠道获取本软件:
+>
+> | 类别 | 唯一官方 |
+> | -------- | ------------------------------------------------------------------------------ |
+> | 官网 | **[ccswitch.io](https://ccswitch.io)** |
+> | 源码 | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
+> | 下载 | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
+> | 作者 | **[@farion1231](https://github.com/farion1231)** |
+> | 举报山寨 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
+>
+> **任何向你收费、要求充值、或索取登录凭据的"CC Switch"网站或客户端均为假冒**。如果你被诱导支付了费用,请立即停止操作并通过 GitHub Issues 反馈。
+
+---
+
+## 概览
+
+CC Switch v3.16.3 是 v3.16.2 之后的一版维护更新。在上一版集中拓宽数据可携带性与用量观测之后,这一版把重心放在「让用量计费真正准确」这件事上——按真实上游模型计费而非上游回显、修正格式转换(Chat / Responses / Gemini 转 Anthropic)路径上的缓存 token 双算、把 Claude Code Workflow 子 agent 的用量纳入本地统计,并以 schema v11 持久化每条记录实际使用的定价依据;用量看板也随之做了一轮改版,新增全局的供应商 / 模型筛选、品牌图标工具栏,以及更稳的额度查询(失败重试 + 保留上次成功结果)。
+
+此外,本版还加固了一批本地代理的稳健性问题(错标 Content-Type 的 SSE 响应聚合、Codex `/responses` 文本模型图像整流、Codex OAuth 凭据与接管残留的恢复、Hermes 配置重复 YAML 键),重做了供应商配置体验(自定义 User-Agent 覆盖、Codex 表单统一进高级选项、预设搜索与排序、Claude Fable 5 档位),新增 Codex 统一会话历史开关,并修复了应用内更新卡死、Codex 升级损坏安装、macOS 重复终端窗口等问题。
+
+**发布日期**:2026-06-14
+
+**更新规模**:59 commits | 130 files changed | +10,223 / -4,232 lines
+
+---
+
+## 重点内容
+
+- **用量计费更准**:路由接管的流量现在按真实上游模型计费(而非上游回显的别名),格式转换路径不再把缓存 token 重复计入 input,Claude Code Workflow 子 agent 的用量也纳入了统计——以 schema v11 持久化定价依据。
+- **用量看板改版**:供应商 / 模型筛选从请求日志表提升为全局筛选,应用筛选改用品牌图标,额度查询加入失败重试与「保留上次成功结果」,单次网络抖动不再让卡片变红。
+- **自定义 User-Agent 覆盖**:供应商可设置自定义 UA,并在转发、连通性检测、模型列表三处一致生效,绕过按 UA 白名单放行的 Coding Plan 上游(借此恢复了 Codex「Kimi For Coding」预设)。
+- **Codex 统一会话历史**:新增可选开关,让官方 Codex 会话与第三方会话共享同一份 resume 历史桶,附带可选的存量迁移与按账本精确还原。
+- **代理与平台加固**:错标 SSE 响应聚合、Codex 图像整流、接管残留恢复、Hermes YAML 去重;应用内更新不再卡在「重启中」,Codex 升级不再把安装弄坏。
+
+---
+
+## 新功能
+
+### 自定义 User-Agent 覆盖
+
+供应商配置现在可以设置自定义 User-Agent,并由代理在请求转发、连通性检测和模型列表(`GET /v1/models`)三条路径上一致应用,因此按 UA 白名单放行的 Coding Plan 上游不会再出现「检测失败 / 模型列表 403、但代理本身却能正常工作」的不一致。Claude 和 Codex 表单都在高级选项里暴露该字段,配有精选的 UA 预设下拉(Claude Code / Kilo Code 等能通过 UA 白名单的家族)和实时、非阻塞的格式校验;切换到官方预设时会丢弃残留的自定义 UA,避免悄悄改动请求头([#3671](https://github.com/farion1231/cc-switch/pull/3671))。
+
+### Codex 统一会话历史
+
+新增一个可选开关(设置 → Codex 应用增强),让官方 Codex 会话与 CC Switch 的第三方会话共享同一份 resume 历史桶,resume 选择器不再把两者互相隐藏。开启后,live 的 `config.toml` 会把官方运行路由到一个镜像内建 OpenAI 供应商的共享 `custom` model_provider(`auth.json` 不动)。默认只对未来会话生效;开启弹窗提供一个勾选项,可把已有官方会话迁入共享桶(含逐代备份),关闭弹窗则提供按备份账本精确还原——只回退备份中记录为 `openai` 的会话,开启期间新建的会话永不被改动。
+
+### 用量看板全局供应商 / 模型筛选
+
+供应商和模型筛选从请求日志表内部提升到了顶栏,对 Hero 汇总、趋势图、请求日志和两个统计页签全局生效,可以把整个看板按某个来源和模型缩小范围。来源按展示名精确匹配(因此像「Claude (Session)」这样的会话占位行也可选),模型按有效计价模型匹配,模型下拉会随所选来源级联,且两个列表只列出当前时间范围内有数据的选项。
+
+### 模型定价种子刷新
+
+对 `seed_model_pricing` 做了一次全量核价:新增 9 个模型的定价(含 Claude Fable 5、Grok 4.3、Mistral Medium 3.5 / Small 4、Qwen 3.7 Max/Plus 等),并按各厂商官方 list 价订正了 28 处既有价格(GLM、Grok、MiMo、Doubao、Kimi、MiniMax、Mistral、Qwen),让用量成本估算更准确。每处改动都同时更新种子(影响全新安装)并向 `repair_current_model_pricing` 加一条旧→新守卫(修复存量数据库,且不覆盖用户手改过的行)。
+
+### Claude Fable 5 模型档位
+
+供应商表单现在在 Claude Code 和 Claude Desktop 两条代理路径上都暴露 `claude-fable-5` 作为第四个模型映射档位,回落链为 fable → opus → default,与官方降级一致,并为 Claude Desktop 1.12603.1+ 的校验器放行了 `fable-` 前缀。四语回落提示也做了澄清:在第三方端点上把某一档留空,会原样透传该档的字面模型名并 404([#3980](https://github.com/farion1231/cc-switch/issues/3980)、[#4026](https://github.com/farion1231/cc-switch/issues/4026)、[#4049](https://github.com/farion1231/cc-switch/issues/4049))。
+
+### Unity2.ai 合作伙伴供应商
+
+新增 Unity2.ai(一个 AI API 中转合作伙伴)作为预设,覆盖全部 7 个受管应用(Claude Code、Codex、Gemini、OpenCode、OpenClaw、Claude Desktop、Hermes),每个预设都带上推广注册链接,并在四种语言里补充了合作伙伴推广文案。Codex 使用裸 base URL(该网关在根路径暴露 `/responses`),OpenCode / OpenClaw / Hermes 使用 `/v1` chat-completions 端点并以 `gpt-5.5` 为预设模型。
+
+### Kimi K2.7 Code 模型
+
+新增 `kimi-k2.7-code` 模型(输入 $0.95 / 输出 $4.00 / 缓存读取 $0.19,每百万 token,256K 上下文),并把全部 6 个官方 Moonshot Kimi 预设(Claude Code、Codex、Claude Desktop、Hermes、OpenCode、OpenClaw)指向它,OpenCode / OpenClaw 预设更名为「Kimi K2.7 Code」。定价种子通过启动时的幂等插入路径生效,存量用户无需迁移即可获得新价。
+
+### 恢复 Codex「Kimi For Coding」预设
+
+重新加入 Codex「Kimi For Coding」预设(`openai_chat`、`kimi-for-coding`、256K 上下文),默认开启思考模式。此前它被移除是因为该编程端点会以 403 拒绝 Codex 默认的 `codex-cli` User-Agent;现在借助代理接管 + 自定义 User-Agent 覆盖(设为 `claude-cli/*` 等白名单 UA)即可正常使用。
+
+### 请求详情的计价模型审计
+
+请求详情面板现在会在「请求的模型」「计价模型」与响应模型不一致时把它们都显示出来,让路由接管产生的账单可以直接在用量界面里核对。
+
+### 预设供应商搜索与排序
+
+预设供应商选择器现在是一个可搜索、可排序的列表,配有内联搜索框(点放大镜图标切换,按 ESC 或点击外部收起)。按钮改为响应式网格、尺寸统一并显示默认图标,搜索只匹配供应商的展示名 / 原始名,因此 URL 片段和共享的分类标签不会再产生噪声匹配([#3975](https://github.com/farion1231/cc-switch/pull/3975)、[#4183](https://github.com/farion1231/cc-switch/pull/4183))。
+
+### Claude Mythos 5 定价
+
+在内置模型 / 定价表里登记 `claude-mythos-5` 模型(输入 $10 / 输出 $50,每百万 token;缓存读取 $1.00、缓存写入 $12.50),让用量统计能正确计价并展示([#4077](https://github.com/farion1231/cc-switch/pull/4077))。
+
+### Fable 5 Verified 标识
+
+设置「关于」页现在会在应用名与版本旁展示 Fable 5 Verified 标识,标明这是一个特别构建,版本徽标也居中到了应用名下方。
+
+---
+
+## 变更
+
+### Claude Desktop 用量折叠进 Claude
+
+看板不再展示独立的「Claude Desktop」分桶——它一直只能显示一个不完整的数字(Desktop 聊天用量根本不经过代理,而其 Code 页签的会话只是内嵌的 Claude Code 运行时写进共享的 `~/.claude/projects` 目录)。Desktop 的代理流量现在在展示上折叠进 `claude`,但记账层仍按它自己的 `app_type` 记录以便路由接管计费审计,真实值可在请求详情面板看到。
+
+### 轻量化供应商健康检查
+
+供应商健康检查不再发送真实的流式模型请求(很多第三方供应商会以 401/403/WAF 拦截,造成误报不可用),改为对供应商 `base_url` 做一次轻量的 HTTP 可达性探测:任何 HTTP 响应都视为可达,只有 DNS / 连接 / TLS / 超时才算失败。官方供应商(使用 OAuth、base_url 故意为空、没有可靠的可达性目标)会隐藏连通性按钮,原先「发送真实请求」的确认弹窗以及测试模型 / 提示词字段都被移除,降级延迟阈值设为 6s、超时 8s。该可达性检查永不重置熔断器——可达不等于可用(403 的 host 可达,但对真实流量是坏的),失败转移仍只由真实代理流量驱动。
+
+### Codex 高级选项区整合
+
+Codex 供应商表单现在把本地路由、模型映射、推理覆盖和自定义 User-Agent 折叠进一个可展开的高级选项区,与 Claude 表单一致(设置了 UA 或开启本地路由时自动展开)。自定义 User-Agent 现在对原生 Responses 供应商也可配置,此前它只有在开启 `openai_chat` 路由时才能触及。
+
+### 用量工具栏与布局刷新
+
+应用筛选改用品牌图标(经 ProviderIcon,「全部」用网格图标)渲染,取代在窄窗口下换行难看的文字页签;用量 Hero 也会显示所选应用的品牌图标,并把 Codex 的主题色从翠绿改为中性灰,贴合 OpenAI 的单色品牌。点击循环切换的刷新按钮改成了带本地化「关闭」标签的下拉选择,顶栏控件也压缩并对齐成统一的宽度分组,过长的日期范围标签做了截断处理。
+
+### 关于面板加载更快
+
+设置「关于」面板现在渐进式加载:应用版本徽标在解析完成的瞬间就显示,不再等待工具探测;每张工具卡片在自己的版本检测完成时立即更新(探测并发执行而非串行);探测结果在应用会话期内缓存并带 10 分钟 TTL,因此再次打开「关于」页签会复用缓存值、并在后台对过期项重新校验,而不是每次都把 6 个工具全部重探一遍。
+
+### 火山方舟 Coding Plan 推广更新
+
+把火山方舟(Volcengine Ark)预设在全部 6 个应用里更新到新的 Coding Plan 邀请链接(替换旧的 Agent Plan / 活动链接),并在四种语言里刷新了合作伙伴推广文案(两个月 75% 折扣 + 邀请码 6J6FV5N2),把产品名从 Agent Plan 订正为 Coding Plan。
+
+### MiniMax 降为普通供应商
+
+移除 MiniMax 的金色合作伙伴星标和 API key 推广横幅(从所有预设里删掉 `isPartner` 标志),它继续作为常规 `cn_official` 供应商保留图标与主题。推广文案保持休眠状态,必要时一行即可重新启用合作关系。
+
+### 移除 LemonData、SudoCode 降级
+
+彻底移除 LemonData 供应商预设(连同其推广文案、图标和赞助商条目),并把 SudoCode 从合作伙伴降为常规 `third_party` 供应商(去掉 `isPartner` 标志和推广文案,保留图标)。
+
+### AtlasCloud Codex GLM 5.1 上下文窗口
+
+为 AtlasCloud Codex 预设里的 `zai-org/glm-5.1` 模型声明 200,000 token 的上下文窗口,与其他 GLM 5.1 预设条目对齐。
+
+---
+
+## 修复
+
+### 路由接管流量按真实上游模型计费
+
+当请求被路由到了不同的上游(env 模型映射、Claude Desktop 路由、Copilot 归一化、Codex chat 覆盖)时,代理过去会按上游回显的模型来归因和计价,把 kimi / glm 的 token 记成、并按 `claude-*` 计价,成本被高估约 5–25 倍。现在转发器会捕获真实的出站模型,按「上游回显 → 出站模型 → 客户端别名」的顺序归因,并在每行持久化实际使用的定价依据(schema v11),该依据会贯穿成本回填和 30 天 rollup 裁剪;Claude Desktop 流量现在也记在它自己的 `app_type` 下,使其定价覆盖能正确生效。
+
+### 格式转换路径的用量计量
+
+审计并修复了代理各条格式转换路径(Chat、Responses、Gemini 转 Anthropic)上的 token / 缓存计量。代理现在会记录实际返回的模型,注入 `stream_options.include_usage` 让 OpenAI 兼容上游在流式时吐出 usage,在 Claude←OpenAI 路径上把 `cache_read` 和 `cache_creation` 从 input 中排除以阻止缓存 token 双计费,扣减 Gemini 的缓存提示 token,仍记录完全命中缓存的请求,并跳过过去会虚增请求数的合成全零 usage([#2774](https://github.com/farion1231/cc-switch/pull/2774))。
+
+### 应用内更新不再卡死
+
+从应用内安装更新时不再卡在「重启中」界面——过去会出现新版已装好、却必须手动强制退出的情况。下载—安装—重启整条链路现在完全在后端执行(新增 `install_update_and_restart` 命令),按平台决定安装顺序,并在重新执行前先销毁单实例锁,而不再依赖旧 WebView 在应用包已被替换之后继续跑 JS;退出请求也做了分类,让重启请求落到 Tauri 默认流程,而不是在窗口状态插件的互斥锁上死锁([#4069](https://github.com/farion1231/cc-switch/pull/4069)、[#4074](https://github.com/farion1231/cc-switch/pull/4074))。
+
+### Codex 升级不再损坏安装
+
+从设置「关于」页升级 Codex 不再让它抛出「Missing optional dependency @openai/codex-…」错误。升级链此前会先跑 `codex update`,而它在 npm 安装下其实是一次裸的重装、即便对应平台的二进制没装上也会报告成功;现在 Codex 已从「优先 self-update」路径里移除,并由一个 runnable 检测触发「卸载 + 重装」自愈(仅限 npm 管理的安装),这是唯一能真正补回缺失平台二进制的修复。
+
+### 接管时保留 Codex OAuth 凭据
+
+为 Codex 供应商开启代理接管时不再剥掉 `ANTHROPIC_AUTH_TOKEN` 占位符——此前这会在热切换、全新安装、以及被旧版本已剥过的 live 配置上破坏 Claude Code 的登录。现在对受管(非 Copilot)的 Codex 供应商无条件注入该占位符,包括只有 URL 的供应商;GitHub Copilot 的行为(仅 API_KEY)不变([#3789](https://github.com/farion1231/cc-switch/pull/3789)、[#3784](https://github.com/farion1231/cc-switch/issues/3784))。
+
+### 跨配置目录切换的接管残留恢复
+
+在代理接管激活时更改配置目录后重启应用,不再把 Claude / Codex / Gemini 留在指向已失效的本地代理上。现在旧实例会在重启前先还原被接管的 live 文件,首次运行的导入会拒绝把接管占位符当作供应商持久化,SSOT 还原也会在写回前校验当前供应商的配置里不含占位符([#4076](https://github.com/farion1231/cc-switch/pull/4076))。
+
+### 格式转换兜底里错标的 SSE 响应聚合
+
+经 Claude / Codex 格式转换的请求,当 MaaS 网关把一个 `stream:false` 的请求强制流式、并以非 SSE 的 Content-Type 返回 SSE 响应体时,不再以一句晦涩的 422「Failed to parse upstream response」失败。代理现在会在解析失败时嗅探 SSE、把分片聚合成单个 JSON 再跑既有转换器,让客户端仍能拿到有效的非流式响应;剩余的解析失败会附带 content-type、编码和响应体片段等诊断信息,deflate 解码也改为先尝试 zlib 再尝试裸流([#2234](https://github.com/farion1231/cc-switch/pull/2234))。
+
+### Hermes 配置重复 YAML 键
+
+Hermes 配置写入不再累积重复的顶层键(如 `mcp_servers`),那会导致「Failed to parse Hermes config as YAML: duplicate entry with key」错误。区段替换现在会从剩余文本里清除所有过期副本,而不是退化成追加;去重保护层同时处理 LF 和 CRLF 行尾;修复时保留最后(最新)的那份副本,与 Hermes 自身基于 PyYAML 的「后者胜」语义一致([#3267](https://github.com/farion1231/cc-switch/pull/3267)、[#3633](https://github.com/farion1231/cc-switch/issues/3633)、[#2973](https://github.com/farion1231/cc-switch/issues/2973)、[#2529](https://github.com/farion1231/cc-switch/issues/2529)、[#3310](https://github.com/farion1231/cc-switch/issues/3310)、[#3762](https://github.com/farion1231/cc-switch/issues/3762))。
+
+### 用量查询韧性与错误清晰度
+
+用量卡片不再因为单次瞬时抖动就变红:查询现在会重试一次,并在网络 / 超时 / 5xx 这类瞬时失败下继续展示上次成功的结果最多 10 分钟;而确定性失败(鉴权、空 key、未知供应商、4xx)会立即暴露并清空快照,避免凭据变更后陈旧额度又冒出来。原生余额 / Coding Plan / 订阅查询的超时从 10s 提高到 15s 以适配跨境慢端点,Coding Plan 也会返回明确的「API key is empty」/「Unknown coding plan provider」错误,而不是一句空白的失败。
+
+### 用量脚本供应商凭据解析
+
+自定义 JS 脚本的用量查询此前只靠猜测 env 字段来解析 `{{apiKey}}` / `{{baseUrl}}`,因此凭据存放在别处的应用(如 Codex 的 `auth.OPENAI_API_KEY` 加 `config.toml` 里的 base_url)总是拿到空值、即便供应商已完整配置也会失败。脚本查询及其测试 / 预览现在复用与原生余额路径相同的按应用凭据解析器,脚本里显式填写的非空值仍然优先([#1479](https://github.com/farion1231/cc-switch/pull/1479))。
+
+### Claude Code Workflow 子 agent 用量统计
+
+本地(无代理)的会话日志用量统计此前漏掉了 Claude Code Workflow 子 agent 的流量,整体用量被低估约 4.1%(集中在 workflow / subagent 的会话记录里)。扫描器现在会深入更深一层的 `subagents/workflows/wf_*/` 记录目录,解析器也不再丢弃那些缺少 `stop_reason`、但已经产生 input / 缓存 token 成本的 assistant 消息;去重逻辑不变,因此不会重复计数。
+
+### Codex `/responses` 文本模型图像整流
+
+携带图片、且被路由到只支持文本的 OpenAI-chat 模型(如 DeepSeek `deepseek-v4-flash`)的 Codex `/responses` 请求,不再以 HTTP 400「unknown variant `image_url`」失败。媒体整流器现在也覆盖 Codex 适配器,会扫描 responses 的 `input` 里的 `input_image` 块,从而既能为已知的纯文本模型主动剥掉图片,也能在上游报「不支持图片」时把图片替换后重试。
+
+### 智谱 Coding Plan 配额窗口误标
+
+智谱 Coding Plan 视图不再在每个周周期的最后几个小时把 5 小时窗口和周窗口标反。两个窗口现在按显式的 `unit` 字段分类(3 = 5 小时、6 = 周),而不再靠按重置时间升序排序——后者恰好在用户最常查周额度的时候把两者标反;当字段缺失时仍回退到旧的重置时间启发式([#3036](https://github.com/farion1231/cc-switch/pull/3036))。
+
+### macOS 重复供应商终端窗口
+
+在 macOS 上启动供应商终端时不再在命令会话旁多开一个空窗口;Terminal.app 在冷启动时改用 `launch`(而非 `activate`),Ghostty 使用初始命令,从而只打开单个会话,并在 AppleScript 路径失败时保留回退方案([#4156](https://github.com/farion1231/cc-switch/pull/4156))。
+
+### Claude Desktop 模型映射占位符
+
+Claude Desktop 模型映射表单此前在「菜单展示名」和「请求模型」两列用了不一致的示例品牌(DeepSeek vs Kimi),暗示一个展示名会映射到不相关的模型。现在两个占位符都由每行的角色派生,从而保持品牌一致,轻量的 Haiku 档使用 flash 示例。
+
+### 弹层被全屏面板遮挡
+
+像供应商预设搜索这样的弹层和提示气泡不再渲染到全屏面板后面、看起来点了没反应;它们的 z-index 被提到全屏遮罩之上,同时仍低于模态对话框。
+
+### ToggleRow 图标被挤压
+
+开关行的图标在配上长描述时不再被压缩或变形,让图标在多行文字旁保持固定大小。
+
+---
+
+## 文档
+
+### Release Notes 贡献者致谢恢复
+
+恢复了 v3.16.1 与 v3.16.2 release notes 在三种语言里的贡献者致谢。
+
+---
+
+## 升级提醒
+
+### 定价库 schema v11 自动迁移
+
+本版给 `proxy_request_logs` 新增了 `pricing_model` 列、并按 `request_model` + `pricing_model` 重建了 rollup,启动时自动迁移、无需手动操作。历史行的成本在写入时已冻结、不会重算(`app_type="claude"` 的行混合了原生与转换两类来源);只有真实但当时未计价的接管行会保持零成本、待定价补齐后再回填。
+
+### 模型映射新增第四档(Fable 5)
+
+Claude Code 与 Claude Desktop 的模型映射现在是四档(Sonnet / Opus / Fable / Haiku)。老的三档供应商在重新打开并保存后会补上 `claude-fable-5` 档;该档留空表示继承 Sonnet。注意:在第三方端点上把任意一档留空,会原样透传该档的字面模型名并可能 404,请按需填写。
+
+### 「Kimi For Coding」预设需要代理接管 + 白名单 UA
+
+恢复的 Codex「Kimi For Coding」预设直接用默认的 `codex-cli` User-Agent 仍会被 403。要使用它,请开启代理接管,并在供应商高级选项里把自定义 User-Agent 设为白名单 UA(如 `claude-cli/*`)。
+
+### 供应商健康检查语义变化
+
+健康检查从「发送真实模型请求」改为「HTTP 可达性探测」。请注意可达 ≠ 可用:一个返回 403 的 host 是可达的,但对真实流量可能是坏的。失败转移的判定仍只由真实代理流量驱动,不受健康检查影响。
+
+---
+
+## 风险提示
+
+本版本继续沿用此前版本对反向代理类功能的风险提示。
+
+**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#️-风险提示)。
+
+**Codex 第三方供应商 Chat 路由**:通过 CC Switch 本地代理把 Codex 请求转换并转发到第三方供应商时,各供应商对计费、合规与数据留存的约束不同,请在使用前阅读目标供应商的服务条款。
+
+**Claude Desktop 第三方供应商代理切换**:通过 CC Switch 内置代理网关把 Claude Desktop 的请求转到第三方供应商时,同样需要遵守目标供应商的计费、合规与数据留存约束。
+
+用户启用上述功能即表示自行承担相关风险。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
+
+---
+
+## 致谢
+
+感谢以下贡献者在 v3.16.3 中提交的功能与修复:
+
+- [#3789](https://github.com/farion1231/cc-switch/pull/3789):接管时保留 Codex OAuth 凭据,感谢 @codeasier。
+- [#2774](https://github.com/farion1231/cc-switch/pull/2774):修复 Completions 转 Anthropic 时不记录实际返回模型、input token 计算错误,感谢 @LaoYueHanNi。
+- [#4069](https://github.com/farion1231/cc-switch/pull/4069):修复应用内更新后重启死锁,感谢 @thisTom。
+- [#4156](https://github.com/farion1231/cc-switch/pull/4156):修复 macOS 重复供应商终端窗口,感谢 @thisTom。
+- [#3267](https://github.com/farion1231/cc-switch/pull/3267):修复 Hermes 配置重复 YAML 键,感谢 @que3sui。
+- [#1479](https://github.com/farion1231/cc-switch/pull/1479):修复用量脚本供应商凭据解析,感谢 @pa001024。
+- [#3975](https://github.com/farion1231/cc-switch/pull/3975):新增预设供应商搜索与排序,感谢 @Nastem。
+- [#4183](https://github.com/farion1231/cc-switch/pull/4183):调整预设供应商按钮外观与搜索框位置,感谢 @WangJiati。
+- [#4077](https://github.com/farion1231/cc-switch/pull/4077):新增 claude-mythos-5 模型定价,感谢 @osscv。
+
+也感谢所有在 v3.16.2 发布后反馈用量计费、本地代理稳健性、Codex 升级与平台兼容性问题的用户,很多补丁都来自这些真实使用场景里的复现线索。
+
+---
+
+## 下载与安装
+
+访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
+
+### 系统要求
+
+| 系统 | 最低版本 | 架构 |
+| ------- | -------------------------- | ----------------------------------- |
+| Windows | Windows 10 及以上 | x64 |
+| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
+| Linux | 见下表 | x64 / ARM64 |
+
+### Windows
+
+| 文件 | 说明 |
+| ---------------------------------------- | ----------------------------------- |
+| `CC-Switch-v3.16.3-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
+| `CC-Switch-v3.16.3-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
+
+### macOS
+
+| 文件 | 说明 |
+| -------------------------------- | --------------------------------------------- |
+| `CC-Switch-v3.16.3-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
+| `CC-Switch-v3.16.3-macOS.zip` | 解压后拖入 Applications,Universal Binary |
+| `CC-Switch-v3.16.3-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
+
+Homebrew 安装:
+
+```bash
+brew install --cask cc-switch
+```
+
+更新:
+
+```bash
+brew upgrade --cask cc-switch
+```
+
+### Linux
+
+Linux 资产同时提供 **x86_64** 和 **ARM64**(`aarch64`)两种架构。资产文件名中包含架构标识,请按你机器的 `uname -m` 输出选择对应版本:
+
+- `CC-Switch-v3.16.3-Linux-x86_64.AppImage` / `.deb` / `.rpm`
+- `CC-Switch-v3.16.3-Linux-arm64.AppImage` / `.deb` / `.rpm`
+
+| 发行版 | 推荐格式 | 安装方式 |
+| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
+| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` 或 `sudo apt install ./CC-Switch-*.deb` |
+| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` 或 `sudo dnf install ./CC-Switch-*.rpm` |
+| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
+| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
+| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
diff --git a/docs/user-manual/en/2-providers/2.1-add.md b/docs/user-manual/en/2-providers/2.1-add.md
index 2e1102461..972f9fa75 100644
--- a/docs/user-manual/en/2-providers/2.1-add.md
+++ b/docs/user-manual/en/2-providers/2.1-add.md
@@ -88,7 +88,7 @@ Codex presets fall into two groups by upstream protocol.
|-------------|-------------|
| DeepSeek | DeepSeek models |
| Zhipu GLM / GLM en | Zhipu AI GLM models |
-| Kimi | Moonshot Kimi models |
+| Kimi / Kimi For Coding | Moonshot Kimi models |
| MiniMax / MiniMax en | MiniMax models |
| StepFun / StepFun en | StepFun Step models |
| Baidu Qianfan Coding Plan | Baidu Qianfan coding plan |
diff --git a/docs/user-manual/ja/2-providers/2.1-add.md b/docs/user-manual/ja/2-providers/2.1-add.md
index b913e89fd..b3bce48e2 100644
--- a/docs/user-manual/ja/2-providers/2.1-add.md
+++ b/docs/user-manual/ja/2-providers/2.1-add.md
@@ -88,7 +88,7 @@ Codex プリセットは上流プロトコルにより 2 種類に分かれま
|----------|------|
| DeepSeek | DeepSeek モデル |
| Zhipu GLM / GLM en | Zhipu AI の GLM モデル |
-| Kimi | Moonshot Kimi モデル |
+| Kimi / Kimi For Coding | Moonshot Kimi モデル |
| MiniMax / MiniMax en | MiniMax モデル |
| StepFun / StepFun en | StepFun Step モデル |
| Baidu Qianfan Coding Plan | 百度千帆コーディングプラン |
diff --git a/docs/user-manual/zh/2-providers/2.1-add.md b/docs/user-manual/zh/2-providers/2.1-add.md
index 8147997c1..710dddd5f 100644
--- a/docs/user-manual/zh/2-providers/2.1-add.md
+++ b/docs/user-manual/zh/2-providers/2.1-add.md
@@ -88,7 +88,7 @@ Codex 预设按上游协议分两类。
|----------|------|
| DeepSeek | DeepSeek 模型 |
| 智谱 GLM / GLM en | 智谱 AI 的 GLM 模型 |
-| Kimi | Moonshot Kimi 模型 |
+| Kimi / Kimi For Coding | Moonshot Kimi 模型 |
| MiniMax / MiniMax en | MiniMax 模型 |
| StepFun / StepFun en | 阶跃星辰 Step 模型 |
| 百度千帆 Coding Plan | 百度千帆编程套餐 |
diff --git a/package.json b/package.json
index beb3e207d..13076d25b 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "cc-switch",
- "version": "3.16.1",
+ "version": "3.16.3",
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
"type": "module",
"scripts": {
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index a54f8fac3..8a9b6cbb7 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -735,7 +735,7 @@ dependencies = [
[[package]]
name = "cc-switch"
-version = "3.16.1"
+version = "3.16.3"
dependencies = [
"anyhow",
"arboard",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index a89dda485..d0cd47560 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "cc-switch"
-version = "3.16.1"
+version = "3.16.3"
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
authors = ["Jason Young"]
license = "MIT"
diff --git a/src-tauri/src/claude_desktop_config.rs b/src-tauri/src/claude_desktop_config.rs
index 88c68dcf0..0824aedf1 100644
--- a/src-tauri/src/claude_desktop_config.rs
+++ b/src-tauri/src/claude_desktop_config.rs
@@ -60,6 +60,16 @@ pub const DEFAULT_PROXY_ROUTES: &[ClaudeDesktopDefaultRoute] = &[
env_key: "ANTHROPIC_DEFAULT_HAIKU_MODEL",
supports_1m: true,
},
+ // fable 置于末尾:next_catalog_safe_route_id 给非安全品牌 route 借用合法
+ // 角色名时仍按 sonnet→opus→haiku 顺序分配(向后兼容既有 catalog),不会把
+ // 无关品牌模型借用成 fable 顶配档名。UI 行序由前端 ROLE_ORDER 独立控制为
+ // Sonnet/Opus/Fable/Haiku(所有 proxy 路径都经 normalizeProxyRows 重排),
+ // 与此处物理顺序无关。
+ ClaudeDesktopDefaultRoute {
+ route_id: "claude-fable-5",
+ env_key: "ANTHROPIC_DEFAULT_FABLE_MODEL",
+ supports_1m: true,
+ },
];
#[derive(Debug, Clone)]
@@ -238,11 +248,16 @@ pub fn is_claude_safe_model_id(model: &str) -> bool {
// 角色前缀后必须还有实际模型标识,拒绝 claude-sonnet- 这类退化值
// (否则会写入 profile 并触发 Claude Desktop fail-all 拒收整组)。
- ["sonnet-", "opus-", "haiku-"].iter().any(|prefix| {
- route_tail
- .strip_prefix(prefix)
- .is_some_and(|rest| !rest.is_empty())
- })
+ // Claude Desktop 1.12603.1+ 的 fail-all validator 角色白名单已纳入 fable
+ // (app.asar 内 ["sonnet","opus","haiku","fable","mythos"]),故 claude-fable-*
+ // 可安全写入 profile。mythos 官方未公开发布,暂不暴露给用户。
+ ["sonnet-", "opus-", "haiku-", "fable-"]
+ .iter()
+ .any(|prefix| {
+ route_tail
+ .strip_prefix(prefix)
+ .is_some_and(|rest| !rest.is_empty())
+ })
}
fn inference_model_json(spec: &InferenceModelSpec) -> Value {
@@ -693,8 +708,8 @@ pub fn map_proxy_request_model(mut body: Value, provider: &Provider) -> Result Result bool {
)
}
-/// 按角色关键词(opus / haiku / sonnet)归类一个 Claude 模型名/route_id。
+/// 按角色关键词(opus / haiku / fable / sonnet)归类一个 Claude 模型名/route_id。
/// 仅在命中明确角色词时返回 Some,未知模型返回 None(不回落,保持精确报错语义)。
-/// 与前端 `routeRoleFromId` 同序(opus → haiku → sonnet)。
+/// 与前端 `routeRoleFromId` 同序(opus → haiku → fable → sonnet)。
fn claude_role_keyword(model: &str) -> Option<&'static str> {
let normalized = model.to_ascii_lowercase();
if normalized.contains("opus") {
Some("opus")
} else if normalized.contains("haiku") {
Some("haiku")
+ } else if normalized.contains("fable") {
+ Some("fable")
} else if normalized.contains("sonnet") {
Some("sonnet")
} else {
@@ -1650,6 +1679,127 @@ mod tests {
assert!(err.to_string().contains("gpt-5"));
}
+ #[test]
+ fn claude_desktop_proxy_maps_fable_to_opus_tier() {
+ // issue #4026/#4049:老用户只配 Sonnet/Opus/Haiku 三档、未显式配置
+ // fable 档时,fable 请求按官方分类器降级方向回落到 opus 档兜底。
+ let mut provider = proxy_provider("proxy");
+ provider
+ .meta
+ .as_mut()
+ .expect("meta")
+ .claude_desktop_model_routes = std::collections::HashMap::from([
+ (
+ "claude-opus-4-8".to_string(),
+ ClaudeDesktopModelRoute {
+ model: "upstream-opus".to_string(),
+ label_override: None,
+ supports_1m: Some(true),
+ },
+ ),
+ (
+ "claude-sonnet-4-6".to_string(),
+ ClaudeDesktopModelRoute {
+ model: "upstream-sonnet".to_string(),
+ label_override: None,
+ supports_1m: Some(true),
+ },
+ ),
+ ]);
+
+ let mapped = map_proxy_request_model(
+ json!({"model": "claude-fable-5", "messages": []}),
+ &provider,
+ )
+ .expect("fable should fall back to the opus tier");
+ assert_eq!(mapped["model"], json!("upstream-opus"));
+
+ // 带 [1m] 标记与日期后缀的形态也应命中同一回落。
+ let mapped_one_m = map_proxy_request_model(
+ json!({"model": "claude-fable-5[1m]", "messages": []}),
+ &provider,
+ )
+ .expect("fable with [1m] marker should fall back to the opus tier");
+ assert_eq!(mapped_one_m["model"], json!("upstream-opus"));
+
+ let mapped_dated = map_proxy_request_model(
+ json!({"model": "claude-fable-5-20260609", "messages": []}),
+ &provider,
+ )
+ .expect("dated fable alias should fall back to the opus tier");
+ assert_eq!(mapped_dated["model"], json!("upstream-opus"));
+ }
+
+ #[test]
+ fn claude_desktop_proxy_fable_without_opus_route_still_errors() {
+ // 没有 opus 档可回落时保持精确报错语义,不静默落到其他档。
+ let mut provider = proxy_provider("proxy");
+ provider
+ .meta
+ .as_mut()
+ .expect("meta")
+ .claude_desktop_model_routes = std::collections::HashMap::from([(
+ "claude-sonnet-4-6".to_string(),
+ ClaudeDesktopModelRoute {
+ model: "upstream-sonnet".to_string(),
+ label_override: None,
+ supports_1m: Some(true),
+ },
+ )]);
+
+ let err = map_proxy_request_model(
+ json!({"model": "claude-fable-5", "messages": []}),
+ &provider,
+ )
+ .expect_err("fable without an opus route should fail");
+ assert!(err.to_string().contains("claude-fable-5"));
+ }
+
+ #[test]
+ fn claude_desktop_proxy_maps_fable_to_dedicated_route() {
+ // Desktop 1.12603.1+ fail-all 校验已放行 claude-fable-5,用户可显式配置
+ // 独立 fable 档;此时 fable 请求精确命中 fable 档,不再降级到 opus。
+ let mut provider = proxy_provider("proxy");
+ provider
+ .meta
+ .as_mut()
+ .expect("meta")
+ .claude_desktop_model_routes = std::collections::HashMap::from([
+ (
+ "claude-opus-4-8".to_string(),
+ ClaudeDesktopModelRoute {
+ model: "upstream-opus".to_string(),
+ label_override: None,
+ supports_1m: Some(true),
+ },
+ ),
+ (
+ "claude-fable-5".to_string(),
+ ClaudeDesktopModelRoute {
+ model: "upstream-fable".to_string(),
+ label_override: None,
+ supports_1m: Some(true),
+ },
+ ),
+ ]);
+
+ // 精确匹配优先命中 fable 档
+ let mapped = map_proxy_request_model(
+ json!({"model": "claude-fable-5", "messages": []}),
+ &provider,
+ )
+ .expect("explicit fable route should match");
+ assert_eq!(mapped["model"], json!("upstream-fable"));
+
+ // 带日期后缀经角色关键词回落仍归 fable 档,而非降级 opus
+ let mapped_dated = map_proxy_request_model(
+ json!({"model": "claude-fable-5-20260609", "messages": []}),
+ &provider,
+ )
+ .expect("dated fable alias should map via fable role keyword");
+ assert_eq!(mapped_dated["model"], json!("upstream-fable"));
+ }
+
#[test]
fn claude_desktop_proxy_accepts_opus_4_7_4_8_alias_during_rollout() {
let mut provider = proxy_provider("proxy");
diff --git a/src-tauri/src/codex_config.rs b/src-tauri/src/codex_config.rs
index f622723e7..29ae5c334 100644
--- a/src-tauri/src/codex_config.rs
+++ b/src-tauri/src/codex_config.rs
@@ -333,7 +333,10 @@ pub fn extract_codex_api_key(auth: Option<&Value>, config_text: Option<&str>) ->
/// Extract the upstream base URL from a Codex `config.toml` string.
///
/// Prefers the active `[model_providers.].base_url`, falling
-/// back to a top-level `base_url` when no model provider is selected.
+/// back to a top-level `base_url`. Deliberately never reads a non-active
+/// `[model_providers.*]` section — the frontend `extractCodexBaseUrl`
+/// (`getRecoverableBaseUrlAssignments`) excludes those too, and a leftover
+/// section unrelated to the active provider must not leak into `{{baseUrl}}`.
pub fn extract_codex_base_url(config_text: &str) -> Option {
let doc = config_text.parse::().ok()?;
@@ -1165,16 +1168,197 @@ pub fn read_codex_live_settings() -> Result {
Ok(json!({ "auth": auth, "config": cfg_text }))
}
+/// `[model_providers.custom]` entry that makes an official (ChatGPT OAuth)
+/// provider behave like Codex's built-in `openai` entry while running under
+/// the shared custom id: `requires_openai_auth` routes auth to the ChatGPT
+/// login in `auth.json` (base_url then defaults to the official Codex
+/// backend), `name = "OpenAI"` keeps Codex's `is_openai()` feature gates
+/// (web search, remote compaction), and `supports_websockets` restores the
+/// built-in default that custom entries otherwise lose.
+fn codex_unified_official_provider_table() -> toml_edit::Table {
+ let mut table = toml_edit::Table::new();
+ table["name"] = toml_edit::value("OpenAI");
+ table["requires_openai_auth"] = toml_edit::value(true);
+ table["supports_websockets"] = toml_edit::value(true);
+ table["wire_api"] = toml_edit::value("responses");
+ table
+}
+
+fn table_matches_codex_unified_official_provider(table: &toml_edit::Table) -> bool {
+ table.len() == 4
+ && table.get("name").and_then(|item| item.as_str()) == Some("OpenAI")
+ && table
+ .get("requires_openai_auth")
+ .and_then(|item| item.as_bool())
+ == Some(true)
+ && table
+ .get("supports_websockets")
+ .and_then(|item| item.as_bool())
+ == Some(true)
+ && table.get("wire_api").and_then(|item| item.as_str()) == Some("responses")
+}
+
+/// 统一 Codex 会话历史:把官方供应商的 live 配置改写为以共享的
+/// `custom` model_provider 标识运行(认证仍走 `auth.json` 的 ChatGPT 登录),
+/// 使开关开启后创建的官方会话与第三方会话共用同一个 resume 历史桶。
+///
+/// 两种情况拒绝注入、原样返回:
+/// - 配置已有显式 `model_provider`:用户手工指定的路由不被覆盖;
+/// - 配置已有形态不同的 `[model_providers.custom]` 表:设置 `model_provider`
+/// 会激活这张我们不认识的表(可能带第三方 base_url/token,会把 ChatGPT
+/// OAuth 流量路由到错误后端),宁可让开关对该配置不生效。
+pub fn inject_codex_unified_session_bucket(config_text: &str) -> Result {
+ let mut doc = config_text
+ .parse::()
+ .map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
+
+ if doc.get("model_provider").is_some() {
+ return Ok(config_text.to_string());
+ }
+
+ let existing_custom_conflicts = doc
+ .get("model_providers")
+ .and_then(|item| item.as_table())
+ .and_then(|providers| providers.get(CC_SWITCH_CODEX_MODEL_PROVIDER_ID))
+ .and_then(|item| item.as_table())
+ .is_some_and(|table| !table_matches_codex_unified_official_provider(table));
+ if existing_custom_conflicts {
+ log::warn!(
+ "官方 Codex 配置已存在自定义 [model_providers.custom],跳过统一会话路由注入以避免激活未知路由"
+ );
+ return Ok(config_text.to_string());
+ }
+
+ doc["model_provider"] = toml_edit::value(CC_SWITCH_CODEX_MODEL_PROVIDER_ID);
+
+ if doc.get("model_providers").is_none() {
+ let mut parent = toml_edit::Table::new();
+ parent.set_implicit(true);
+ doc["model_providers"] = toml_edit::Item::Table(parent);
+ }
+ if let Some(providers) = doc["model_providers"].as_table_mut() {
+ if !providers.contains_key(CC_SWITCH_CODEX_MODEL_PROVIDER_ID) {
+ providers.insert(
+ CC_SWITCH_CODEX_MODEL_PROVIDER_ID,
+ toml_edit::Item::Table(codex_unified_official_provider_table()),
+ );
+ }
+ }
+ Ok(doc.to_string())
+}
+
+/// `inject_codex_unified_session_bucket` 的反向操作:从配置文本里剥掉注入的
+/// 统一会话路由,保证切换回填不会把它带进数据库的存储配置(关闭开关后
+/// 切换即可完全还原)。仅当形态与注入产物完全一致时才剥离;第三方模板和
+/// 用户自定义的 `custom` 条目(带 base_url 等差异字段)原样保留。
+pub fn strip_codex_unified_session_bucket(config_text: &str) -> Result {
+ if !config_text.contains("model_provider") {
+ return Ok(config_text.to_string());
+ }
+ let mut doc = config_text
+ .parse::()
+ .map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
+
+ if doc.get("model_provider").and_then(|item| item.as_str())
+ != Some(CC_SWITCH_CODEX_MODEL_PROVIDER_ID)
+ {
+ return Ok(config_text.to_string());
+ }
+ let matches_injected = doc
+ .get("model_providers")
+ .and_then(|item| item.as_table())
+ .and_then(|providers| providers.get(CC_SWITCH_CODEX_MODEL_PROVIDER_ID))
+ .and_then(|item| item.as_table())
+ .is_some_and(table_matches_codex_unified_official_provider);
+ if !matches_injected {
+ return Ok(config_text.to_string());
+ }
+
+ doc.as_table_mut().remove("model_provider");
+ let providers_empty = doc["model_providers"]
+ .as_table_mut()
+ .map(|providers| {
+ providers.remove(CC_SWITCH_CODEX_MODEL_PROVIDER_ID);
+ providers.is_empty()
+ })
+ .unwrap_or(false);
+ if providers_empty {
+ doc.as_table_mut().remove("model_providers");
+ }
+ Ok(doc.to_string())
+}
+
+/// 统一会话开关开启时,把官方供应商 `{ auth, config }` 设置对象中的
+/// config 文本注入共享 custom 路由;开关关闭或非官方供应商时不做改动。
+///
+/// 普通 live 写入(`write_codex_live_for_provider`)与代理接管备份
+/// (`update_live_backup_from_provider`)两条落盘路径共用:接管期间
+/// live 归代理所有,注入必须进备份,接管释放恢复的 live 才带统一路由。
+pub fn apply_codex_unified_session_bucket_to_settings(
+ category: Option<&str>,
+ settings: &mut Value,
+) -> Result<(), AppError> {
+ if category != Some("official") || !crate::settings::unify_codex_session_history() {
+ return Ok(());
+ }
+ let config_text = settings
+ .get("config")
+ .and_then(|value| value.as_str())
+ .unwrap_or("")
+ .to_string();
+ let injected = inject_codex_unified_session_bucket(&config_text)?;
+ if injected != config_text {
+ if let Some(obj) = settings.as_object_mut() {
+ obj.insert("config".to_string(), Value::String(injected));
+ }
+ }
+ Ok(())
+}
+
+/// Backfill helper: strip the unified-session injection from a live
+/// `{ auth, config }` settings object before it is stored back to the DB.
+pub fn strip_codex_unified_session_bucket_from_settings(
+ settings: &mut Value,
+) -> Result<(), AppError> {
+ let Some(config_text) = settings
+ .get("config")
+ .and_then(|value| value.as_str())
+ .map(str::to_string)
+ else {
+ return Ok(());
+ };
+ let stripped = strip_codex_unified_session_bucket(&config_text)?;
+ if stripped != config_text {
+ if let Some(obj) = settings.as_object_mut() {
+ obj.insert("config".to_string(), Value::String(stripped));
+ }
+ }
+ Ok(())
+}
+
/// Route a Codex live write between full auth+config or config-only.
///
/// Official providers with usable login material own `auth.json`. Third-party
/// providers only touch `config.toml` when the compatibility setting is enabled
/// so the user's ChatGPT login cache survives provider switches.
+///
+/// 统一会话开关开启时,官方配置在落盘前注入共享的 `custom` 路由
+/// (见 `inject_codex_unified_session_bucket`)。
pub fn write_codex_live_for_provider(
category: Option<&str>,
auth: &Value,
config_text: Option<&str>,
) -> Result<(), AppError> {
+ let unified_official_config =
+ if category == Some("official") && crate::settings::unify_codex_session_history() {
+ Some(inject_codex_unified_session_bucket(
+ config_text.unwrap_or(""),
+ )?)
+ } else {
+ None
+ };
+ let config_text = unified_official_config.as_deref().or(config_text);
+
let should_write_auth = (category == Some("official") && codex_auth_has_login_material(auth))
|| (category != Some("official")
&& !crate::settings::preserve_codex_official_auth_on_switch());
@@ -1409,6 +1593,153 @@ mod tests {
}
}
+ #[test]
+ fn unified_session_bucket_injects_for_empty_official_config() {
+ let injected = inject_codex_unified_session_bucket("").expect("inject");
+ let doc: toml::Table = toml::from_str(&injected).expect("parse injected config");
+
+ assert_eq!(
+ doc.get("model_provider").and_then(|v| v.as_str()),
+ Some(CC_SWITCH_CODEX_MODEL_PROVIDER_ID)
+ );
+ let custom = doc["model_providers"][CC_SWITCH_CODEX_MODEL_PROVIDER_ID]
+ .as_table()
+ .expect("custom provider table");
+ assert_eq!(custom.get("name").and_then(|v| v.as_str()), Some("OpenAI"));
+ assert_eq!(
+ custom.get("requires_openai_auth").and_then(|v| v.as_bool()),
+ Some(true)
+ );
+ assert_eq!(
+ custom.get("supports_websockets").and_then(|v| v.as_bool()),
+ Some(true)
+ );
+ assert_eq!(
+ custom.get("wire_api").and_then(|v| v.as_str()),
+ Some("responses")
+ );
+ }
+
+ #[test]
+ fn unified_session_bucket_preserves_other_keys_and_explicit_routing() {
+ let with_catalog = "model_catalog_json = \"cc-switch-model-catalog.json\"\n";
+ let injected = inject_codex_unified_session_bucket(with_catalog).expect("inject");
+ assert!(injected.contains("model_catalog_json"));
+ assert!(injected.contains("model_provider = \"custom\""));
+
+ // 用户显式指定过 model_provider 的官方配置不被覆盖
+ let explicit = "model_provider = \"openai_https\"\n";
+ let unchanged = inject_codex_unified_session_bucket(explicit).expect("inject");
+ assert_eq!(unchanged, explicit);
+ }
+
+ #[test]
+ fn unified_session_bucket_skips_conflicting_custom_table() {
+ // 残留的非注入形态 custom 表:设置 model_provider 会把官方流量
+ // 路由到表里的第三方端点,必须整体拒绝注入。
+ let stale = r#"[model_providers.custom]
+name = "Relay"
+base_url = "https://relay.example/v1"
+"#;
+ let unchanged = inject_codex_unified_session_bucket(stale).expect("inject");
+ assert_eq!(unchanged, stale);
+
+ // 已是注入形态的 custom 表(如重复注入)则照常补上 model_provider
+ let injected_once = inject_codex_unified_session_bucket("").expect("inject");
+ let reinjected = inject_codex_unified_session_bucket(&injected_once).expect("re-inject");
+ assert_eq!(reinjected, injected_once);
+ }
+
+ #[test]
+ fn unified_session_bucket_strip_round_trips_injection() {
+ let injected = inject_codex_unified_session_bucket("").expect("inject");
+ let stripped = strip_codex_unified_session_bucket(&injected).expect("strip");
+ assert_eq!(stripped.trim(), "");
+
+ let with_catalog = "model_catalog_json = \"cc-switch-model-catalog.json\"\n";
+ let injected = inject_codex_unified_session_bucket(with_catalog).expect("inject");
+ let stripped = strip_codex_unified_session_bucket(&injected).expect("strip");
+ assert_eq!(stripped, with_catalog);
+ }
+
+ #[test]
+ fn unified_session_bucket_strip_keeps_third_party_custom_entry() {
+ // 第三方模板同样用 custom 路由,但条目带 base_url 等差异字段,
+ // 形态不等于注入产物,必须原样保留。
+ let third_party = r#"model_provider = "custom"
+
+[model_providers.custom]
+name = "Relay"
+base_url = "https://relay.example/v1"
+wire_api = "responses"
+requires_openai_auth = true
+"#;
+ let untouched = strip_codex_unified_session_bucket(third_party).expect("strip");
+ assert_eq!(untouched, third_party);
+ }
+
+ #[test]
+ fn unified_session_bucket_strip_from_settings_only_touches_config() {
+ let injected = inject_codex_unified_session_bucket("").expect("inject");
+ let mut settings = json!({
+ "auth": { "tokens": { "access_token": "secret" } },
+ "config": injected,
+ });
+ strip_codex_unified_session_bucket_from_settings(&mut settings).expect("strip settings");
+ assert_eq!(
+ settings
+ .get("config")
+ .and_then(|v| v.as_str())
+ .map(str::trim),
+ Some("")
+ );
+ assert!(settings.pointer("/auth/tokens/access_token").is_some());
+ }
+
+ #[test]
+ fn extract_base_url_prefers_active_provider_section() {
+ let input = r#"model_provider = "azure"
+
+[model_providers.azure]
+base_url = "https://azure.example.com/v1"
+
+[model_providers.other]
+base_url = "https://other.example.com/v1"
+"#;
+
+ assert_eq!(
+ extract_codex_base_url(input).as_deref(),
+ Some("https://azure.example.com/v1")
+ );
+ }
+
+ #[test]
+ fn extract_base_url_falls_back_to_top_level_only() {
+ let top_level = r#"base_url = "https://top-level.example.com/v1""#;
+ assert_eq!(
+ extract_codex_base_url(top_level).as_deref(),
+ Some("https://top-level.example.com/v1")
+ );
+ }
+
+ // Mirrors the frontend extractCodexBaseUrl: a non-active provider section
+ // is never a credential source, whether the active provider points
+ // elsewhere (e.g. the built-in "openai") or none is selected at all.
+ #[test]
+ fn extract_base_url_ignores_non_active_provider_sections() {
+ let mismatched = r#"model_provider = "openai"
+
+[model_providers.custom]
+base_url = "https://leftover.example.com/v1"
+"#;
+ assert_eq!(extract_codex_base_url(mismatched), None);
+
+ let no_active = r#"[model_providers.any]
+base_url = "https://single.example.com/v1"
+"#;
+ assert_eq!(extract_codex_base_url(no_active), None);
+ }
+
#[test]
fn prepare_provider_live_config_rejects_key_without_config() {
let err = prepare_codex_provider_live_config(&json!({"OPENAI_API_KEY": "sk-test"}), "")
diff --git a/src-tauri/src/codex_history_migration.rs b/src-tauri/src/codex_history_migration.rs
index 30443eda6..240ce5e72 100644
--- a/src-tauri/src/codex_history_migration.rs
+++ b/src-tauri/src/codex_history_migration.rs
@@ -10,7 +10,8 @@ use crate::config::{atomic_write, copy_file, get_app_config_dir};
use crate::database::{is_official_seed_id, Database};
use crate::error::AppError;
use crate::settings::{
- CodexProviderTemplateMigration, CodexThirdPartyHistoryProviderBucketMigration,
+ CodexOfficialHistoryUnifyMigration, CodexProviderTemplateMigration,
+ CodexThirdPartyHistoryProviderBucketMigration,
};
use chrono::{Local, Utc};
use rusqlite::{backup::Backup, params_from_iter, Connection};
@@ -24,7 +25,25 @@ use std::time::{Duration, SystemTime};
use toml_edit::DocumentMut;
const MIGRATION_NAME: &str = "codex-history-provider-migration-v1";
+const OFFICIAL_UNIFY_MIGRATION_NAME: &str = "codex-official-history-unify-v1";
+/// 还原操作自身的备份目录(与迁移备份分开,保持迁移账本目录纯净)。
+const OFFICIAL_UNIFY_RESTORE_BACKUP_NAME: &str = "codex-official-history-unify-restore-v1";
const CODEX_STATE_DB_FILENAME: &str = "state_5.sqlite";
+/// SQLite 变量上限保守值,IN 列表按此分块。
+const STATE_DB_ID_CHUNK: usize = 500;
+
+/// 串行化官方历史的迁移与还原:开启迁移(启动重试 + 设置保存后台任务)和
+/// 关闭还原可能在毫秒级先后被触发,对同一批 jsonl / state DB 双向改写。
+static CODEX_OFFICIAL_HISTORY_OP_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+fn lock_codex_official_history_op() -> std::sync::MutexGuard<'static, ()> {
+ CODEX_OFFICIAL_HISTORY_OP_LOCK
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+/// Codex 内建默认 provider id:config.toml 没有 `model_provider` 键时会话归入此桶。
+/// 官方订阅(ChatGPT OAuth / OpenAI API key)的历史会话都记录这个 id。
+const OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID: &str = "openai";
const LEGACY_CC_SWITCH_CODEX_MODEL_PROVIDER_ID: &str = "ccswitch";
// If a Codex preset ever used a temporary routing key, keep that old key here
// so local history can be bucketed under the current custom provider id.
@@ -120,7 +139,7 @@ pub fn maybe_migrate_codex_third_party_history_provider_bucket(
});
}
- let backup_root = migration_backup_root();
+ let backup_root = migration_backup_root(MIGRATION_NAME);
let codex_dir = get_codex_config_dir();
let migrated_jsonl_files =
migrate_codex_jsonl_files(&codex_dir, &source_provider_ids, &backup_root)?;
@@ -157,7 +176,7 @@ pub fn maybe_migrate_codex_provider_template_bucket(
});
}
- let backup_root = migration_backup_root();
+ let backup_root = migration_backup_root(MIGRATION_NAME);
let outcome = migrate_codex_provider_templates_to_custom(db, &backup_root)?;
crate::settings::mark_codex_provider_template_migrated(CodexProviderTemplateMigration {
completed_at: Utc::now().to_rfc3339(),
@@ -167,6 +186,475 @@ pub fn maybe_migrate_codex_provider_template_bucket(
Ok(outcome)
}
+/// 统一会话开关的存量迁移:把官方会话(内建 "openai" 桶)迁入共享 "custom" 桶。
+///
+/// 仅当用户在开启弹窗里勾选了"迁入既有官方会话"(`unify_codex_migrate_existing`)
+/// 且本轮未完成时执行;开关关闭时标记与勾选意愿都会被清除(见 `save_settings`),
+/// 重新开启并再次勾选即可补迁关闭期间产生的官方会话。
+/// custom 桶里官方与第三方会话无法区分,自动逻辑绝不反向搬回;
+/// 用户可在关闭开关时选择按备份账本精确还原(见 `restore_codex_official_history_from_backups`)。
+/// 迁移前 jsonl / state DB 均备份到 `~/.cc-switch/backups/codex-official-history-unify-v1/`。
+pub fn maybe_migrate_codex_official_history_to_unified_bucket(
+) -> Result {
+ if !crate::settings::unify_codex_session_history() {
+ return Ok(CodexHistoryProviderBucketMigrationOutcome {
+ skipped_reason: Some("unify_toggle_off".to_string()),
+ ..Default::default()
+ });
+ }
+ if !crate::settings::unify_codex_migrate_existing_requested() {
+ return Ok(CodexHistoryProviderBucketMigrationOutcome {
+ skipped_reason: Some("stock_migration_not_requested".to_string()),
+ ..Default::default()
+ });
+ }
+ let _op_guard = lock_codex_official_history_op();
+ let codex_dir = get_codex_config_dir();
+ // marker 绑定迁移时的 Codex 目录:切换 codex_config_dir 后旧 marker 不再
+ // 挡住新目录的迁移(迁移幂等,重跑无害)。
+ let codex_dir_key = canonical_dir_string(&codex_dir);
+ if crate::settings::is_codex_official_history_unify_migrated_for_dir(&codex_dir_key) {
+ return Ok(CodexHistoryProviderBucketMigrationOutcome {
+ skipped_reason: Some("already_migrated".to_string()),
+ ..Default::default()
+ });
+ }
+ // live 必须已实际路由到共享 custom 桶才允许迁移:官方配置的注入可能被拒
+ // (已有显式 model_provider / 形态冲突的 custom 表,见
+ // `inject_codex_unified_session_bucket`),代理接管期间的 live 也不带统一
+ // 路由(注入只进备份)。这些状态下新会话仍落 "openai" 桶,迁移只会把
+ // 历史搬进当前 live 看不见的桶里。开关与迁移意愿保持不动,待 live 真正
+ // 统一后(下次切换 / 接管释放后的启动重试)再迁。
+ if !codex_config_text_routes_custom(&read_codex_config_text().unwrap_or_default()) {
+ return Ok(CodexHistoryProviderBucketMigrationOutcome {
+ skipped_reason: Some("live_not_unified".to_string()),
+ ..Default::default()
+ });
+ }
+
+ let source_provider_ids: BTreeSet =
+ std::iter::once(OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID.to_string()).collect();
+ let backup_root = migration_backup_root(OFFICIAL_UNIFY_MIGRATION_NAME);
+ let migrated_jsonl_files =
+ migrate_codex_jsonl_files(&codex_dir, &source_provider_ids, &backup_root)?;
+ let migrated_state_rows =
+ migrate_codex_state_dbs(&codex_dir, &source_provider_ids, &backup_root)?;
+ // 备份代际记录来源目录,restore 据此只取当前目录的账本。
+ write_backup_generation_meta(&backup_root, &codex_dir_key)?;
+
+ let outcome = CodexHistoryProviderBucketMigrationOutcome {
+ source_provider_ids: source_provider_ids.into_iter().collect(),
+ migrated_jsonl_files,
+ migrated_state_rows,
+ skipped_reason: None,
+ };
+
+ // 条件写入在 settings 写锁内原子完成:"迁移期间开关被关掉"时不写完成标记,
+ // 避免下一次开启被标记挡住而漏迁"关闭期间"新产生的 openai 桶会话。
+ // 与关闭路径(update_settings + 清标记)共用同一把锁,无检查-写入窗口。
+ let marker_written = crate::settings::mark_codex_official_history_unify_migrated_if_enabled(
+ CodexOfficialHistoryUnifyMigration {
+ completed_at: Utc::now().to_rfc3339(),
+ target_provider_id: CC_SWITCH_CODEX_MODEL_PROVIDER_ID.to_string(),
+ migrated_jsonl_files,
+ migrated_state_rows,
+ codex_config_dir: Some(codex_dir_key),
+ },
+ )?;
+ if !marker_written {
+ return Ok(CodexHistoryProviderBucketMigrationOutcome {
+ skipped_reason: Some("toggle_disabled_during_migration".to_string()),
+ ..outcome
+ });
+ }
+
+ Ok(outcome)
+}
+
+/// live config.toml 是否路由到共享 custom 桶(会话分桶只看这个实态:
+/// base_url / 接管与否都不影响 session_meta 记录的 model_provider)。
+fn codex_config_text_routes_custom(config_text: &str) -> bool {
+ config_text
+ .parse::()
+ .ok()
+ .and_then(|doc| {
+ doc.get("model_provider")
+ .and_then(|item| item.as_str())
+ .map(|id| id.trim() == CC_SWITCH_CODEX_MODEL_PROVIDER_ID)
+ })
+ .unwrap_or(false)
+}
+
+/// 目录的规范化字符串形式,用作 marker / 备份代际的目录身份。
+/// canonicalize 失败(目录尚不存在等)时退回原始路径字符串。
+fn canonical_dir_string(dir: &Path) -> String {
+ fs::canonicalize(dir)
+ .unwrap_or_else(|_| dir.to_path_buf())
+ .to_string_lossy()
+ .to_string()
+}
+
+/// 在备份代际根目录写入 meta.json,记录这批备份来自哪个 Codex 目录。
+/// 代际目录不存在(本轮没有任何文件被迁移)时跳过。
+fn write_backup_generation_meta(backup_root: &Path, codex_dir_key: &str) -> Result<(), AppError> {
+ if !backup_root.exists() {
+ return Ok(());
+ }
+ let payload = serde_json::json!({ "codexConfigDir": codex_dir_key });
+ let bytes =
+ serde_json::to_vec_pretty(&payload).map_err(|e| AppError::JsonSerialize { source: e })?;
+ atomic_write(&backup_root.join("meta.json"), &bytes)
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct CodexOfficialHistoryRestoreOutcome {
+ pub restored_jsonl_files: usize,
+ pub restored_state_rows: usize,
+ pub skipped_reason: Option,
+}
+
+/// 统一会话开关迁移备份的父目录(其下每次迁移一个时间戳代际目录)。
+fn official_history_unify_backup_parent() -> PathBuf {
+ get_app_config_dir()
+ .join("backups")
+ .join(OFFICIAL_UNIFY_MIGRATION_NAME)
+}
+
+/// 是否存在可用于还原的迁移备份(给前端决定要不要显示"恢复备份"勾选)。
+/// 与 restore 的账本收集共用同一目录匹配口径:只认属于当前 Codex 目录的
+/// 代际,避免切换 codex_config_dir 后弹出注定空跑的勾选。
+/// 精确账本内容仍在真正还原时才解析。
+pub fn has_codex_official_history_unify_backup() -> bool {
+ has_official_history_unify_backup_for_dir(
+ &official_history_unify_backup_parent(),
+ &canonical_dir_string(&get_codex_config_dir()),
+ )
+}
+
+fn has_official_history_unify_backup_for_dir(ledger_parent: &Path, codex_dir_key: &str) -> bool {
+ let Ok(entries) = fs::read_dir(ledger_parent) else {
+ return false;
+ };
+ entries.flatten().any(|entry| {
+ let generation = entry.path();
+ generation.is_dir() && backup_generation_matches_dir(&generation, codex_dir_key)
+ })
+}
+
+/// 关闭统一会话开关时的可选还原:按迁移备份账本,把当时迁入共享 custom 桶的
+/// 官方会话精确翻回 "openai" 桶。
+///
+/// 备份是唯一可信的归属证据:备份里 model_provider=="openai" 的会话必定源自
+/// 官方桶。开启期间新产生的会话不在任何备份里,**永不触碰**——它们可能来自
+/// 第三方,方向无法判定(产品决策:宁可留在第三方历史)。
+/// 扫描全部备份代际取并集,多次开关循环后仍能还原早期迁入的会话;
+/// 还原前改动目标先备份到独立的 restore 目录(保持迁移账本目录纯净),
+/// 且只改写当前仍为 custom 的目标,重复执行无害。
+pub fn restore_codex_official_history_from_backups(
+) -> Result {
+ let _op_guard = lock_codex_official_history_op();
+ // 开关已(重新)开启时拒绝还原:live 正路由 custom,把账本会话翻回
+ // openai 桶等于亲手制造分裂。覆盖"关闭保存成功后用户立刻重新开启,
+ // 还原排在重开迁移之后才拿到 op lock"的时序。
+ if crate::settings::unify_codex_session_history() {
+ return Ok(CodexOfficialHistoryRestoreOutcome {
+ skipped_reason: Some("unify_toggle_on".to_string()),
+ ..Default::default()
+ });
+ }
+ let config_text = read_codex_config_text().unwrap_or_default();
+ restore_codex_official_history_inner(
+ &get_codex_config_dir(),
+ &official_history_unify_backup_parent(),
+ &migration_backup_root(OFFICIAL_UNIFY_RESTORE_BACKUP_NAME),
+ &config_text,
+ )
+}
+
+fn restore_codex_official_history_inner(
+ codex_dir: &Path,
+ ledger_parent: &Path,
+ restore_backup_root: &Path,
+ config_text: &str,
+) -> Result {
+ let codex_dir_key = canonical_dir_string(codex_dir);
+ let (official_session_ids, official_thread_ids) =
+ collect_official_ledger(ledger_parent, &codex_dir_key)?;
+ if official_session_ids.is_empty() && official_thread_ids.is_empty() {
+ return Ok(CodexOfficialHistoryRestoreOutcome {
+ skipped_reason: Some("no_backup_ledger".to_string()),
+ ..Default::default()
+ });
+ }
+
+ let mut files = Vec::new();
+ collect_jsonl_files(&codex_dir.join("sessions"), &mut files, 0, 8);
+ collect_jsonl_files(&codex_dir.join("archived_sessions"), &mut files, 0, 4);
+ let mut restored_jsonl_files = 0;
+ for file_path in files {
+ if rewrite_codex_session_file_lines(&file_path, codex_dir, restore_backup_root, |line| {
+ rewrite_codex_session_meta_line_for_restore(line, &official_session_ids)
+ })? {
+ restored_jsonl_files += 1;
+ }
+ }
+
+ let mut restored_state_rows = 0;
+ for db_path in codex_state_db_paths(codex_dir, config_text) {
+ restored_state_rows += restore_codex_state_db_official_threads(
+ &db_path,
+ codex_dir,
+ &official_thread_ids,
+ restore_backup_root,
+ )?;
+ }
+
+ if restored_jsonl_files == 0 && restored_state_rows == 0 {
+ // 账本非空但没有任何"当前仍为 custom"的目标(如重复还原):
+ // 以 reason 告知前端,避免误报"已还原 0 项"为成功。
+ return Ok(CodexOfficialHistoryRestoreOutcome {
+ skipped_reason: Some("nothing_to_restore".to_string()),
+ ..Default::default()
+ });
+ }
+
+ Ok(CodexOfficialHistoryRestoreOutcome {
+ restored_jsonl_files,
+ restored_state_rows,
+ skipped_reason: None,
+ })
+}
+
+/// 从备份代际收集官方会话账本:jsonl 备份里 session_meta 为 "openai" 的
+/// 会话 id + state DB 备份里 model_provider 为 "openai" 的 thread id。
+/// 只采纳 meta.json 目录与当前 Codex 目录一致的代际,避免切换
+/// codex_config_dir 后拿旧目录的账本作用到新目录。
+/// 还原操作自身的备份(restore 目录)天然不会混入:那些副本里的 id 都是
+/// custom,解析后贡献为空。
+fn collect_official_ledger(
+ ledger_parent: &Path,
+ codex_dir_key: &str,
+) -> Result<(HashSet, BTreeSet), AppError> {
+ let mut session_ids = HashSet::new();
+ let mut thread_ids = BTreeSet::new();
+ let entries = match fs::read_dir(ledger_parent) {
+ Ok(entries) => entries,
+ Err(_) => return Ok((session_ids, thread_ids)),
+ };
+ for entry in entries.flatten() {
+ let generation = entry.path();
+ if !generation.is_dir() {
+ continue;
+ }
+ if !backup_generation_matches_dir(&generation, codex_dir_key) {
+ continue;
+ }
+ let mut backup_files = Vec::new();
+ collect_jsonl_files(&generation.join("jsonl"), &mut backup_files, 0, 10);
+ for backup_file in backup_files {
+ collect_official_session_ids_from_backup(&backup_file, &mut session_ids);
+ }
+ let mut backup_dbs = Vec::new();
+ collect_files_with_extension(&generation.join("state"), "sqlite", &mut backup_dbs, 0, 4);
+ for backup_db in backup_dbs {
+ collect_official_thread_ids_from_backup(&backup_db, &mut thread_ids);
+ }
+ }
+ Ok((session_ids, thread_ids))
+}
+
+/// 备份代际是否属于指定 Codex 目录。无 meta.json 或解析失败时宽容接受:
+/// 早期版本的备份没有 meta,而那个时期不存在切目录场景;误纳的代价也被
+/// "按会话 id 精确匹配 + 仅改写 custom"双重条件兜底。
+fn backup_generation_matches_dir(generation: &Path, codex_dir_key: &str) -> bool {
+ let Ok(text) = fs::read_to_string(generation.join("meta.json")) else {
+ return true;
+ };
+ serde_json::from_str::(&text)
+ .ok()
+ .and_then(|value| {
+ value
+ .get("codexConfigDir")
+ .and_then(Value::as_str)
+ .map(|dir| dir == codex_dir_key)
+ })
+ .unwrap_or(true)
+}
+
+fn collect_official_session_ids_from_backup(path: &Path, session_ids: &mut HashSet) {
+ let Ok(content) = fs::read_to_string(path) else {
+ log::debug!("Failed to read unify backup file {}", path.display());
+ return;
+ };
+ for line in content.lines() {
+ if !line.contains("\"session_meta\"") || !line.contains("\"model_provider\"") {
+ continue;
+ }
+ let Ok(value) = serde_json::from_str::(line) else {
+ continue;
+ };
+ if value.get("type").and_then(Value::as_str) != Some("session_meta") {
+ continue;
+ }
+ let Some(payload) = value.get("payload") else {
+ continue;
+ };
+ if payload.get("model_provider").and_then(Value::as_str)
+ != Some(OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID)
+ {
+ continue;
+ }
+ if let Some(session_id) = payload.get("id").and_then(Value::as_str) {
+ session_ids.insert(session_id.to_string());
+ }
+ }
+}
+
+fn collect_official_thread_ids_from_backup(db_path: &Path, thread_ids: &mut BTreeSet) {
+ let conn =
+ match Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) {
+ Ok(conn) => conn,
+ Err(err) => {
+ log::debug!(
+ "Failed to open unify backup state DB {}: {err}",
+ db_path.display()
+ );
+ return;
+ }
+ };
+ let has_threads = Database::table_exists(&conn, "threads").unwrap_or(false)
+ && Database::has_column(&conn, "threads", "model_provider").unwrap_or(false);
+ if !has_threads {
+ return;
+ }
+ let Ok(mut stmt) = conn.prepare("SELECT id FROM threads WHERE model_provider = ?1") else {
+ return;
+ };
+ let Ok(rows) = stmt.query_map([OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID], |row| {
+ row.get::<_, String>(0)
+ }) else {
+ return;
+ };
+ for thread_id in rows.flatten() {
+ thread_ids.insert(thread_id);
+ }
+}
+
+fn collect_files_with_extension(
+ dir: &Path,
+ extension: &str,
+ files: &mut Vec,
+ depth: u8,
+ max_depth: u8,
+) {
+ if depth > max_depth || !dir.is_dir() {
+ return;
+ }
+ let Ok(entries) = fs::read_dir(dir) else {
+ return;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ collect_files_with_extension(&path, extension, files, depth + 1, max_depth);
+ } else if path.extension().and_then(|ext| ext.to_str()) == Some(extension) {
+ files.push(path);
+ }
+ }
+}
+
+fn rewrite_codex_session_meta_line_for_restore(
+ line: &str,
+ official_session_ids: &HashSet,
+) -> Option {
+ if !line.contains("\"session_meta\"") || !line.contains("\"model_provider\"") {
+ return None;
+ }
+ let mut value: Value = serde_json::from_str(line).ok()?;
+ if value.get("type").and_then(Value::as_str) != Some("session_meta") {
+ return None;
+ }
+ let payload = value.get_mut("payload")?.as_object_mut()?;
+ if payload.get("model_provider")?.as_str()? != CC_SWITCH_CODEX_MODEL_PROVIDER_ID {
+ return None;
+ }
+ let session_id = payload.get("id")?.as_str()?;
+ if !official_session_ids.contains(session_id) {
+ return None;
+ }
+ payload.insert(
+ "model_provider".to_string(),
+ Value::String(OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID.to_string()),
+ );
+ serde_json::to_string(&value).ok()
+}
+
+fn restore_codex_state_db_official_threads(
+ db_path: &Path,
+ codex_dir: &Path,
+ official_thread_ids: &BTreeSet,
+ backup_root: &Path,
+) -> Result {
+ if !db_path.exists() || official_thread_ids.is_empty() {
+ return Ok(0);
+ }
+
+ let mut conn = Connection::open(db_path)
+ .map_err(|e| AppError::Database(format!("打开 Codex state DB 失败: {e}")))?;
+ conn.busy_timeout(Duration::from_secs(5))
+ .map_err(|e| AppError::Database(format!("设置 Codex state DB busy_timeout 失败: {e}")))?;
+
+ if !Database::table_exists(&conn, "threads")?
+ || !Database::has_column(&conn, "threads", "model_provider")?
+ {
+ return Ok(0);
+ }
+
+ let ids: Vec<&String> = official_thread_ids.iter().collect();
+ let mut matching_rows: i64 = 0;
+ for chunk in ids.chunks(STATE_DB_ID_CHUNK) {
+ let placeholders = placeholders(chunk.len());
+ let count_sql = format!(
+ "SELECT COUNT(*) FROM threads WHERE model_provider = ? AND id IN ({placeholders})"
+ );
+ let mut values = Vec::with_capacity(chunk.len() + 1);
+ values.push(CC_SWITCH_CODEX_MODEL_PROVIDER_ID.to_string());
+ values.extend(chunk.iter().map(|id| (*id).clone()));
+ let count: i64 = conn
+ .query_row(&count_sql, params_from_iter(values.iter()), |row| {
+ row.get(0)
+ })
+ .map_err(|e| AppError::Database(format!("统计 Codex state DB 待还原行失败: {e}")))?;
+ matching_rows += count;
+ }
+ if matching_rows == 0 {
+ return Ok(0);
+ }
+
+ backup_codex_state_db(db_path, codex_dir, backup_root, &conn)?;
+
+ let tx = conn
+ .transaction()
+ .map_err(|e| AppError::Database(format!("开启 Codex state DB 还原事务失败: {e}")))?;
+ let mut changed = 0;
+ for chunk in ids.chunks(STATE_DB_ID_CHUNK) {
+ let placeholders = placeholders(chunk.len());
+ let update_sql = format!(
+ "UPDATE threads SET model_provider = ? WHERE model_provider = ? AND id IN ({placeholders})"
+ );
+ let mut values = Vec::with_capacity(chunk.len() + 2);
+ values.push(OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID.to_string());
+ values.push(CC_SWITCH_CODEX_MODEL_PROVIDER_ID.to_string());
+ values.extend(chunk.iter().map(|id| (*id).clone()));
+ changed += tx
+ .execute(&update_sql, params_from_iter(values.iter()))
+ .map_err(|e| AppError::Database(format!("还原 Codex state DB provider 失败: {e}")))?;
+ }
+ tx.commit()
+ .map_err(|e| AppError::Database(format!("提交 Codex state DB 还原事务失败: {e}")))?;
+ Ok(changed)
+}
+
fn migrate_codex_provider_templates_to_custom(
db: &Database,
backup_root: &Path,
@@ -257,10 +745,10 @@ fn insert_known_cc_switch_legacy_source_id(ids: &mut BTreeSet, provider_
}
}
-fn migration_backup_root() -> PathBuf {
+fn migration_backup_root(migration_name: &str) -> PathBuf {
get_app_config_dir()
.join("backups")
- .join(MIGRATION_NAME)
+ .join(migration_name)
.join(Local::now().format("%Y%m%d_%H%M%S").to_string())
}
@@ -524,6 +1012,17 @@ fn rewrite_codex_session_file_for_provider_bucket(
codex_dir: &Path,
source_provider_ids: &HashSet,
backup_root: &Path,
+) -> Result {
+ rewrite_codex_session_file_lines(path, codex_dir, backup_root, |line| {
+ rewrite_codex_session_meta_line(line, source_provider_ids)
+ })
+}
+
+fn rewrite_codex_session_file_lines(
+ path: &Path,
+ codex_dir: &Path,
+ backup_root: &Path,
+ rewrite_line: impl Fn(&str) -> Option,
) -> Result {
let metadata_before = fs::metadata(path).map_err(|e| AppError::io(path, e))?;
let modified_before = metadata_before.modified().ok();
@@ -537,7 +1036,7 @@ fn rewrite_codex_session_file_for_provider_bucket(
.strip_suffix('\n')
.map(|line| (line, "\n"))
.unwrap_or((segment, ""));
- if let Some(next_line) = rewrite_codex_session_meta_line(line, source_provider_ids) {
+ if let Some(next_line) = rewrite_line(line) {
rewritten.push_str(&next_line);
changed = true;
} else {
@@ -820,6 +1319,39 @@ mod tests {
values.iter().map(|value| value.to_string()).collect()
}
+ #[test]
+ fn detects_custom_routed_codex_config_for_unify_gate() {
+ // 注入产物(官方 + 统一开关)
+ assert!(codex_config_text_routes_custom(
+ r#"model_provider = "custom"
+
+[model_providers.custom]
+name = "OpenAI"
+requires_openai_auth = true
+supports_websockets = true
+wire_api = "responses"
+"#
+ ));
+ // 第三方供应商的常规 custom 路由(带 base_url)同样算已统一
+ assert!(codex_config_text_routes_custom(
+ r#"model_provider = "custom"
+
+[model_providers.custom]
+name = "AIHubMix"
+base_url = "https://aihubmix.example/v1"
+"#
+ ));
+ // 注入被拒的形态:显式 openai 路由 / 无 model_provider(接管期间、空配置)
+ assert!(!codex_config_text_routes_custom(
+ "model_provider = \"openai\"\n"
+ ));
+ assert!(!codex_config_text_routes_custom(
+ "base_url = \"http://127.0.0.1:15721/codex\"\n"
+ ));
+ assert!(!codex_config_text_routes_custom(""));
+ assert!(!codex_config_text_routes_custom("not toml ["));
+ }
+
fn migrate_provider_templates_for_test(
db: &Database,
) -> (
@@ -1092,6 +1624,333 @@ base_url = "https://proxy.example/v1"
);
}
+ #[test]
+ fn simulates_official_history_unify_migration_end_to_end() {
+ let dir = tempdir().expect("tempdir");
+ let codex_dir = dir.path().join(".codex");
+ let backup_root = dir.path().join("backup");
+ fs::create_dir_all(&codex_dir).expect("create codex dir");
+
+ let source_provider_ids = source_ids(&[OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID]);
+
+ let session_dir = codex_dir.join("sessions/2026/06/12");
+ fs::create_dir_all(&session_dir).expect("create session dir");
+ let session_path = session_dir.join("official-sim.jsonl");
+ fs::write(
+ &session_path,
+ concat!(
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"openai\"}}\n",
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"s2\",\"model_provider\":\"custom\"}}\n",
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"s3\",\"model_provider\":\"my-private-relay\"}}\n",
+ "{\"type\":\"response_item\",\"payload\":{\"text\":\"openai\"}}\n",
+ ),
+ )
+ .expect("write session");
+
+ let migrated_jsonl =
+ migrate_codex_jsonl_files(&codex_dir, &source_provider_ids, &backup_root)
+ .expect("migrate jsonl");
+ assert_eq!(migrated_jsonl, 1);
+ let session_text = fs::read_to_string(&session_path).expect("read session");
+ assert_eq!(
+ session_text
+ .matches("\"model_provider\":\"custom\"")
+ .count(),
+ 2
+ );
+ assert!(!session_text.contains("\"model_provider\":\"openai\""));
+ assert!(session_text.contains("\"model_provider\":\"my-private-relay\""));
+ assert!(
+ session_text.contains("{\"type\":\"response_item\",\"payload\":{\"text\":\"openai\"}}")
+ );
+ assert!(backup_root
+ .join("jsonl/sessions/2026/06/12/official-sim.jsonl")
+ .exists());
+
+ // 第二次执行应当无事可做(幂等)
+ let rerun = migrate_codex_jsonl_files(&codex_dir, &source_provider_ids, &backup_root)
+ .expect("rerun migrate jsonl");
+ assert_eq!(rerun, 0);
+
+ let state_db_path = codex_dir.join(CODEX_STATE_DB_FILENAME);
+ let conn = Connection::open(&state_db_path).expect("open state db");
+ conn.execute_batch(
+ "CREATE TABLE threads (
+ id TEXT PRIMARY KEY,
+ model_provider TEXT NOT NULL
+ );
+ INSERT INTO threads (id, model_provider) VALUES
+ ('openai-thread', 'openai'),
+ ('custom-thread', 'custom'),
+ ('manual-thread', 'my-private-relay');",
+ )
+ .expect("seed state db");
+ drop(conn);
+
+ let migrated_state_rows = migrate_codex_state_db_provider_bucket(
+ &state_db_path,
+ &codex_dir,
+ &source_provider_ids,
+ &backup_root,
+ )
+ .expect("migrate state db");
+ assert_eq!(migrated_state_rows, 1);
+
+ let conn = Connection::open(&state_db_path).expect("reopen state db");
+ let count_provider = |provider_id: &str| -> i64 {
+ conn.query_row(
+ "SELECT COUNT(*) FROM threads WHERE model_provider = ?1",
+ [provider_id],
+ |row| row.get(0),
+ )
+ .expect("count provider")
+ };
+ assert_eq!(count_provider("custom"), 2);
+ assert_eq!(count_provider("openai"), 0);
+ assert_eq!(count_provider("my-private-relay"), 1);
+ }
+
+ #[test]
+ fn restores_only_ledgered_official_sessions_from_backups() {
+ let dir = tempdir().expect("tempdir");
+ let codex_dir = dir.path().join(".codex");
+ let ledger_parent = dir.path().join("ledger");
+ let restore_backup_root = dir.path().join("restore-backup");
+
+ // 备份账本:一个代际,jsonl 备份里 s1 是 openai;state 备份里 t1 是 openai
+ let generation = ledger_parent.join("20260612_010101");
+ let backup_session_dir = generation.join("jsonl/sessions/2026/06/01");
+ fs::create_dir_all(&backup_session_dir).expect("create backup session dir");
+ fs::write(
+ backup_session_dir.join("official.jsonl"),
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"openai\"}}\n",
+ )
+ .expect("write backup session");
+ let backup_state_dir = generation.join("state");
+ fs::create_dir_all(&backup_state_dir).expect("create backup state dir");
+ let backup_db = Connection::open(backup_state_dir.join(CODEX_STATE_DB_FILENAME))
+ .expect("open backup db");
+ backup_db
+ .execute_batch(
+ "CREATE TABLE threads (id TEXT PRIMARY KEY, model_provider TEXT NOT NULL);
+ INSERT INTO threads (id, model_provider) VALUES ('t1', 'openai');",
+ )
+ .expect("seed backup db");
+ drop(backup_db);
+
+ // 当前数据:s1(账本内,custom)应还原;s2(开启期间新会话,不在账本)
+ // 与 s3(手工 relay)必须原样保留
+ let session_dir = codex_dir.join("sessions/2026/06/01");
+ fs::create_dir_all(&session_dir).expect("create session dir");
+ let official_path = session_dir.join("official.jsonl");
+ fs::write(
+ &official_path,
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"custom\"}}\n",
+ )
+ .expect("write official session");
+ let on_period_dir = codex_dir.join("sessions/2026/06/12");
+ fs::create_dir_all(&on_period_dir).expect("create on-period dir");
+ let on_period_path = on_period_dir.join("on-period.jsonl");
+ fs::write(
+ &on_period_path,
+ concat!(
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"s2\",\"model_provider\":\"custom\"}}\n",
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"s3\",\"model_provider\":\"my-private-relay\"}}\n",
+ ),
+ )
+ .expect("write on-period session");
+
+ let state_db_path = codex_dir.join(CODEX_STATE_DB_FILENAME);
+ let conn = Connection::open(&state_db_path).expect("open state db");
+ conn.execute_batch(
+ "CREATE TABLE threads (id TEXT PRIMARY KEY, model_provider TEXT NOT NULL);
+ INSERT INTO threads (id, model_provider) VALUES
+ ('t1', 'custom'),
+ ('t2', 'custom'),
+ ('t3', 'openai');",
+ )
+ .expect("seed state db");
+ drop(conn);
+
+ // 代际 meta 指向当前 Codex 目录:精确匹配分支生效(而非无 meta 的宽容分支)
+ fs::write(
+ generation.join("meta.json"),
+ serde_json::to_vec_pretty(&serde_json::json!({
+ "codexConfigDir": canonical_dir_string(&codex_dir)
+ }))
+ .expect("serialize meta"),
+ )
+ .expect("write meta");
+
+ let outcome = restore_codex_official_history_inner(
+ &codex_dir,
+ &ledger_parent,
+ &restore_backup_root,
+ "",
+ )
+ .expect("restore");
+ assert_eq!(outcome.restored_jsonl_files, 1);
+ assert_eq!(outcome.restored_state_rows, 1);
+ assert!(outcome.skipped_reason.is_none());
+
+ let official_text = fs::read_to_string(&official_path).expect("read official");
+ assert!(official_text.contains("\"model_provider\":\"openai\""));
+ let on_period_text = fs::read_to_string(&on_period_path).expect("read on-period");
+ assert!(on_period_text.contains("\"id\":\"s2\",\"model_provider\":\"custom\""));
+ assert!(on_period_text.contains("\"model_provider\":\"my-private-relay\""));
+
+ let conn = Connection::open(&state_db_path).expect("reopen state db");
+ let provider_of = |thread_id: &str| -> String {
+ conn.query_row(
+ "SELECT model_provider FROM threads WHERE id = ?1",
+ [thread_id],
+ |row| row.get(0),
+ )
+ .expect("thread provider")
+ };
+ assert_eq!(provider_of("t1"), "openai");
+ assert_eq!(provider_of("t2"), "custom");
+ assert_eq!(provider_of("t3"), "openai");
+ drop(conn);
+
+ // 还原前的现场已备份到独立目录
+ assert!(restore_backup_root
+ .join("jsonl/sessions/2026/06/01/official.jsonl")
+ .exists());
+ assert!(restore_backup_root
+ .join("state")
+ .join(CODEX_STATE_DB_FILENAME)
+ .exists());
+
+ // 幂等:第二次还原无事可做
+ let rerun = restore_codex_official_history_inner(
+ &codex_dir,
+ &ledger_parent,
+ &dir.path().join("restore-backup-2"),
+ "",
+ )
+ .expect("rerun restore");
+ assert_eq!(rerun.restored_jsonl_files, 0);
+ assert_eq!(rerun.restored_state_rows, 0);
+ assert_eq!(rerun.skipped_reason.as_deref(), Some("nothing_to_restore"));
+ }
+
+ #[test]
+ fn restore_ignores_backup_generations_from_other_codex_dirs() {
+ let dir = tempdir().expect("tempdir");
+ let codex_dir = dir.path().join(".codex");
+ let ledger_parent = dir.path().join("ledger");
+
+ // 账本代际属于另一个 Codex 目录
+ let generation = ledger_parent.join("20260612_010101");
+ let backup_session_dir = generation.join("jsonl/sessions/2026/06/01");
+ fs::create_dir_all(&backup_session_dir).expect("create backup session dir");
+ fs::write(
+ backup_session_dir.join("official.jsonl"),
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"openai\"}}\n",
+ )
+ .expect("write backup session");
+ fs::write(
+ generation.join("meta.json"),
+ "{\n \"codexConfigDir\": \"/some/other/codex-dir\"\n}",
+ )
+ .expect("write meta");
+
+ let session_dir = codex_dir.join("sessions/2026/06/01");
+ fs::create_dir_all(&session_dir).expect("create session dir");
+ let session_path = session_dir.join("official.jsonl");
+ fs::write(
+ &session_path,
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"custom\"}}\n",
+ )
+ .expect("write session");
+
+ let outcome = restore_codex_official_history_inner(
+ &codex_dir,
+ &ledger_parent,
+ &dir.path().join("restore-backup"),
+ "",
+ )
+ .expect("restore");
+ assert_eq!(outcome.skipped_reason.as_deref(), Some("no_backup_ledger"));
+ let text = fs::read_to_string(&session_path).expect("read session");
+ assert!(text.contains("\"model_provider\":\"custom\""));
+ }
+
+ #[test]
+ fn backup_probe_only_counts_generations_for_current_dir() {
+ let dir = tempdir().expect("tempdir");
+ let ledger_parent = dir.path().join("ledger");
+ let codex_dir_key = "/current/codex-dir";
+
+ // 空父目录 / 父目录不存在:无备份
+ assert!(!has_official_history_unify_backup_for_dir(
+ &ledger_parent,
+ codex_dir_key
+ ));
+
+ // 只有其他目录的代际:不算有备份
+ let other = ledger_parent.join("20260612_010101");
+ fs::create_dir_all(&other).expect("create generation");
+ fs::write(
+ other.join("meta.json"),
+ "{\n \"codexConfigDir\": \"/some/other/codex-dir\"\n}",
+ )
+ .expect("write meta");
+ assert!(!has_official_history_unify_backup_for_dir(
+ &ledger_parent,
+ codex_dir_key
+ ));
+
+ // 无 meta 的早期代际:宽容接受(与 restore 的账本口径一致)
+ fs::create_dir_all(ledger_parent.join("20260612_020202")).expect("create legacy gen");
+ assert!(has_official_history_unify_backup_for_dir(
+ &ledger_parent,
+ codex_dir_key
+ ));
+
+ // 精确匹配当前目录的代际
+ fs::remove_dir_all(ledger_parent.join("20260612_020202")).expect("remove legacy gen");
+ let matched = ledger_parent.join("20260612_030303");
+ fs::create_dir_all(&matched).expect("create matched gen");
+ fs::write(
+ matched.join("meta.json"),
+ format!("{{\n \"codexConfigDir\": \"{codex_dir_key}\"\n}}"),
+ )
+ .expect("write matched meta");
+ assert!(has_official_history_unify_backup_for_dir(
+ &ledger_parent,
+ codex_dir_key
+ ));
+ }
+
+ #[test]
+ fn restore_skips_when_no_backup_ledger_exists() {
+ let dir = tempdir().expect("tempdir");
+ let codex_dir = dir.path().join(".codex");
+ let session_dir = codex_dir.join("sessions/2026/06/01");
+ fs::create_dir_all(&session_dir).expect("create session dir");
+ fs::write(
+ session_dir.join("session.jsonl"),
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"custom\"}}\n",
+ )
+ .expect("write session");
+
+ let outcome = restore_codex_official_history_inner(
+ &codex_dir,
+ &dir.path().join("missing-ledger"),
+ &dir.path().join("restore-backup"),
+ "",
+ )
+ .expect("restore");
+ assert_eq!(outcome.skipped_reason.as_deref(), Some("no_backup_ledger"));
+ assert_eq!(outcome.restored_jsonl_files, 0);
+ assert_eq!(outcome.restored_state_rows, 0);
+
+ let text = fs::read_to_string(session_dir.join("session.jsonl")).expect("read session");
+ assert!(text.contains("\"model_provider\":\"custom\""));
+ }
+
#[test]
fn rewrites_only_codex_session_meta_provider_ids() {
let dir = tempdir().expect("tempdir");
diff --git a/src-tauri/src/commands/misc.rs b/src-tauri/src/commands/misc.rs
index 81aa1328d..3abb43e87 100644
--- a/src-tauri/src/commands/misc.rs
+++ b/src-tauri/src/commands/misc.rs
@@ -1985,10 +1985,19 @@ fn anchored_official_update_command(tool: &str, bin_path: &str) -> Option update || `)。
+///
+/// **codex 刻意不在此列**:`codex update` 在 npm 安装上只是裸 `npm install -g
+/// @openai/codex`(无 `@latest` / `--include=optional` / 不先卸载),却只检查 exit code、
+/// 无条件打印 “Update ran successfully”。当 npm 把平台二进制 optional 依赖
+/// `@openai/codex-` 漏装时它仍 **exit 0 假成功**,使外层 `||` 兜底被短路、损坏被
+/// 成功 toast 掩盖(用户报告的 “Missing optional dependency” 即源于此)。因此 codex 一律走
+/// npm 锚定升级;真正损坏(`runnable=false`)时由 `installs_anchored_command` 的门控改用
+/// `codex_repair_command` 的 uninstall+install 自愈,而非交给 codex 自身的 self-update。
fn prefers_official_update(tool: &str, shell: LifecycleCommandShell) -> bool {
match shell {
LifecycleCommandShell::Posix => {
- matches!(tool, "claude" | "codex" | "opencode" | "openclaw")
+ matches!(tool, "claude" | "opencode" | "openclaw")
}
LifecycleCommandShell::WindowsBatch => {
matches!(
@@ -1997,12 +2006,66 @@ fn prefers_official_update(tool: &str, shell: LifecycleCommandShell) -> bool {
// 安装方式探测失败弹交互 prompt(spawn npm.cmd 没传 shell:true);静默
// lifecycle 没有 stdin 会挂死,Windows 先锚到包管理器路径,等上游修了
// 再把 opencode 加回这里。
- "claude" | "codex" | "openclaw"
+ "claude" | "openclaw"
)
}
}
}
+/// Codex 平台分发包损坏的自愈命令。Codex 的 npm 包是「主包 `@openai/codex`(纯 JS
+/// launcher)+ 平台二进制 optional 依赖 `@openai/codex-`」的分发模式(同 esbuild/swc)。
+/// 当平台二进制缺失时 codex 跑不起来——`enumerate_tool_installations` 跑 `--version` 会拿到
+/// “Missing optional dependency” 的非 0 退出,标记 `runnable=false`。此状态下普通
+/// `npm i -g @pkg@latest` 是 **no-op**:npm 视 optional 依赖缺失为非致命,reify 又认为主包已是
+/// 最新(外加半损坏留下的空 nested `node_modules` 残骸强化「tree 已满足」判断),不会补回平台
+/// 二进制。唯一实测可靠的修复是先 `uninstall` 清掉残骸、再 `install` 装回完整的主包 + 平台二进制
+/// (实测输出 `added 2 packages`)。
+///
+/// 锚定到与 codex 入口同目录的 npm(与升级路径一致,不依赖 GUI 非登录进程的 PATH)。`|| true`
+/// 让 uninstall 失败(如 nvm 上对半损坏包静默返回非 0)不触发外层 `set -e` 中止,但随后的
+/// install 若失败仍会被 `set -e` 捕获并上报给前端 toast。
+///
+/// **仅对会锚定到 sibling npm 的 node 管理器来源(nvm/fnm/mise/homebrew npm)生效**:
+/// `runnable=false` 是宽信号(权限 / node 版本 / 任意 `--version` 失败皆可触发),非 npm
+/// 全局安装各有自己的二进制分发与修复方式,无脑套 npm uninstall+install 会出错——Homebrew
+/// formula(real 在 `Cellar/`)本应 `brew upgrade codex`,npm 够不到它反而旁路装第二份 npm
+/// 全局 codex;Volta/Bun 本应 `volta install`/`bun add`,且 `~/.bun/bin` 下没有 npm、
+/// `sibling_bin` 会拼出不存在的路径;system/未知来源无可靠 sibling npm。这些来源一律返回
+/// None,让上游继续走 source-specific 的 `anchored_command_from_paths`。白名单与
+/// `package_manager_anchored_command_from_paths` 的 sibling-npm 分支对齐。
+/// 刻意**不**额外用 `inst.error` 文本确认「确系缺二进制」:enumerate 只保留 stderr 末尾 4 行,
+/// 而 codex.js 抛错的 "Missing optional dependency" 行会被尾部 node stack `at ...` 行挤出窗口
+/// (实测用户原始错误即如此),强加该条件反而漏修真实缺包;对 npm 全局安装,uninstall+install
+/// 对各类损坏都是合理且不会更糟的修复。
+#[cfg(not(target_os = "windows"))]
+fn codex_repair_command(bin_path: &str, real: &str) -> Option {
+ // brew formula(real 在 Cellar)→ 不归 npm 管,交回 anchored 走 brew upgrade。
+ if brew_formula_from_path(real).is_some() {
+ return None;
+ }
+ // 只认会落到 sibling npm 的 node 管理器来源;volta/bun/system/未知交回 anchored。
+ if !matches!(
+ infer_install_source(Path::new(bin_path)),
+ "nvm" | "fnm" | "mise" | "homebrew"
+ ) {
+ return None;
+ }
+ let npm = sibling_bin(bin_path, "npm")?;
+ let npm = quote_path_if_spaced(&npm);
+ let pkg = "@openai/codex";
+ Some(format!(
+ "{npm} uninstall -g {pkg} || true; {npm} i -g {pkg}@latest"
+ ))
+}
+
+/// Windows 暂不做平台分发自愈:Windows 上 codex 的破坏模式不同(EPERM 文件锁 / 版本 bump
+/// 残留,见 openai/codex#21872、#19824),且 `.bat` 链的错误处理与 POSIX `set -e` 语义不同,
+/// 需要单独设计;先在本问题实际发生的 POSIX 平台落地。返回 None → 上游走正常锚定命令。
+#[cfg(target_os = "windows")]
+fn codex_repair_command(_bin_path: &str, _real: &str) -> Option {
+ None
+}
+
#[cfg(not(target_os = "windows"))]
fn package_manager_anchored_command_from_paths(
tool: &str,
@@ -2190,6 +2253,17 @@ fn default_install(installs: &[ToolInstallation]) -> Option<&ToolInstallation> {
fn installs_anchored_command(tool: &str, installs: &[ToolInstallation]) -> Option {
let inst = default_install(installs)?;
let real = inst.real.to_string_lossy();
+ // Codex 平台分发包损坏自愈:主包在但平台二进制缺失时 codex 跑不起来
+ // (runnable=false),此时正常锚定的 `npm i -g @latest` 是 no-op 修不好——改用
+ // uninstall+install 重装补回平台二进制。**但仅限会锚定到 sibling npm 的 node 管理器
+ // 来源**(codex_repair_command 内按 source/real 收窄,brew/volta/bun/system 交回下方
+ // source-specific 锚定,避免误用 npm 重装)。runnable=true 的正常升级也走下方普通锚定
+ // 路径(且因 codex 不在 prefers_official_update,不会再跑会假成功掩盖损坏的 `codex update`)。
+ if tool == "codex" && !inst.runnable {
+ if let Some(cmd) = codex_repair_command(&inst.path, &real) {
+ return Some(cmd);
+ }
+ }
anchored_command_from_paths(tool, &inst.path, &real)
}
@@ -2620,29 +2694,58 @@ exec bash --norc --noprofile
result
}
-/// macOS: Terminal.app
+/// Escape a value as an AppleScript string literal.
#[cfg(target_os = "macos")]
-fn launch_macos_terminal_app(script_file: &std::path::Path) -> Result<(), String> {
- use std::process::Command;
+fn applescript_string_literal(value: &str) -> String {
+ format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
+}
- let applescript = format!(
- r#"tell application "Terminal"
- activate
- do script "bash '{}'"
+/// Build the launcher command literal used by AppleScript.
+#[cfg(target_os = "macos")]
+fn applescript_launcher_command(script_file: &std::path::Path) -> String {
+ applescript_string_literal(&format!(
+ "bash {}",
+ shell_single_quote(&script_file.to_string_lossy())
+ ))
+}
+
+/// macOS: Terminal.app AppleScript.
+/// A cold `activate` creates a default empty window before `do script` opens the command session.
+/// Use `launch` for cold starts so `do script` can create the only new session without reusing restored windows.
+#[cfg(target_os = "macos")]
+fn build_macos_terminal_applescript(script_file: &std::path::Path) -> String {
+ format!(
+ r#"set launcher_script to {launcher}
+set was_running to application "Terminal" is running
+tell application "Terminal"
+ if was_running then
+ activate
+ do script launcher_script
+ else
+ launch
+ do script launcher_script
+ activate
+ end if
end tell"#,
- script_file.display()
- );
+ launcher = applescript_launcher_command(script_file)
+ )
+}
+
+/// Run AppleScript through `osascript -e` with shared error handling.
+#[cfg(target_os = "macos")]
+fn run_terminal_osascript(applescript: &str, terminal_label: &str) -> Result<(), String> {
+ use std::process::Command;
let output = Command::new("osascript")
.arg("-e")
- .arg(&applescript)
+ .arg(applescript)
.output()
.map_err(|e| format!("执行 osascript 失败: {e}"))?;
if !output.status.success() {
let stderr = decode_command_output(&output.stderr);
return Err(format!(
- "Terminal.app 执行失败 (exit code: {:?}): {}",
+ "{terminal_label} 执行失败 (exit code: {:?}): {}",
output.status.code(),
stderr
));
@@ -2651,11 +2754,20 @@ end tell"#,
Ok(())
}
+/// macOS: Terminal.app
+#[cfg(target_os = "macos")]
+fn launch_macos_terminal_app(script_file: &std::path::Path) -> Result<(), String> {
+ run_terminal_osascript(
+ &build_macos_terminal_applescript(script_file),
+ "Terminal.app",
+ )
+}
+
/// macOS: iTerm2
#[cfg(target_os = "macos")]
fn build_macos_iterm2_applescript(script_file: &std::path::Path) -> String {
format!(
- r#"set launcher_script to "bash '{}'"
+ r#"set launcher_script to {launcher}
set was_running to application "iTerm" is running
tell application "iTerm"
if was_running then
@@ -2683,63 +2795,59 @@ tell application "iTerm"
write text launcher_script
end tell
end tell"#,
- script_file.display()
+ launcher = applescript_launcher_command(script_file)
)
}
/// macOS: iTerm2
#[cfg(target_os = "macos")]
fn launch_macos_iterm2(script_file: &std::path::Path) -> Result<(), String> {
- use std::process::Command;
-
- let applescript = build_macos_iterm2_applescript(script_file);
-
- let output = Command::new("osascript")
- .arg("-e")
- .arg(&applescript)
- .output()
- .map_err(|e| format!("执行 osascript 失败: {e}"))?;
-
- if !output.status.success() {
- let stderr = decode_command_output(&output.stderr);
- return Err(format!(
- "iTerm2 执行失败 (exit code: {:?}): {}",
- output.status.code(),
- stderr
- ));
- }
-
- Ok(())
+ run_terminal_osascript(&build_macos_iterm2_applescript(script_file), "iTerm2")
}
-/// macOS: Ghostty — use --quit-after-last-window-closed to avoid cloning existing tabs
+/// Keep the launcher path inside a `bash -c` string.
+/// A bare `.sh` passed through `open --args` may also be opened as a document.
+#[cfg(target_os = "macos")]
+fn build_macos_dash_c_command(script_file: &std::path::Path) -> String {
+ format!(
+ "exec bash {}",
+ shell_single_quote(&script_file.to_string_lossy())
+ )
+}
+
+/// macOS: Ghostty.
+/// Warm starts use AppleScript to create one command window.
+/// Cold starts use `initial-command` so the first default surface runs the launcher.
+/// Do not use `initial-window=false` plus `new window`: cold launch can still create the default window first.
+#[cfg(target_os = "macos")]
+fn build_macos_ghostty_applescript(script_file: &std::path::Path) -> String {
+ format!(
+ r#"set launcher_command to {launcher}
+set was_running to application "Ghostty" is running
+if was_running then
+ tell application "Ghostty"
+ new window with configuration {{command:launcher_command}}
+ end tell
+else
+ do shell script "open -na Ghostty --args --quit-after-last-window-closed=true " & quoted form of ("--initial-command=" & launcher_command)
+end if
+"#,
+ launcher = applescript_launcher_command(script_file)
+ )
+}
+
+/// macOS: Ghostty
#[cfg(target_os = "macos")]
fn launch_macos_ghostty(script_file: &std::path::Path) -> Result<(), String> {
- use std::process::Command;
-
- let output = Command::new("open")
- .args([
- "-na",
- "Ghostty",
- "--args",
- "--quit-after-last-window-closed=true",
- "-e",
- "bash",
- ])
- .arg(script_file)
- .output()
- .map_err(|e| format!("启动 Ghostty 失败: {e}"))?;
-
- if !output.status.success() {
- let stderr = decode_command_output(&output.stderr);
- return Err(format!(
- "Ghostty 启动失败 (exit code: {:?}): {}",
- output.status.code(),
- stderr
- ));
+ match run_terminal_osascript(&build_macos_ghostty_applescript(script_file), "Ghostty") {
+ Ok(()) => Ok(()),
+ Err(applescript_error) => {
+ log::warn!(
+ "Ghostty AppleScript launch failed, falling back to open -na: {applescript_error}"
+ );
+ launch_macos_open_app("Ghostty", script_file, true)
+ }
}
-
- Ok(())
}
/// macOS: 使用 open -na 启动支持 --args 参数的终端(Alacritty/Kitty/WezTerm/Kaku)
@@ -2757,7 +2865,10 @@ fn launch_macos_open_app(
if use_e_flag {
cmd.arg("-e");
}
- cmd.arg("bash").arg(script_file);
+ // Keep the script path inside `bash -c`; a trailing bare `.sh` can be opened as a document.
+ cmd.arg("bash")
+ .arg("-c")
+ .arg(build_macos_dash_c_command(script_file));
let output = cmd
.output()
@@ -4009,8 +4120,9 @@ mod tests {
#[test]
fn codex_nvm_anchors_to_that_npm() {
- // Codex 官方 self-update 只在支持的 release 上生效;失败时仍写回同一个
- // node 的 npm,而非 PATH 第一个 npm。
+ // Codex 不走 self-update(`codex update` 在 npm 安装上只是裸 `npm install -g`,
+ // 却会假成功掩盖平台二进制漏装)——直接锚定到同一个 node 的 npm,而非 PATH
+ // 第一个 npm。损坏时的 uninstall+install 自愈见 codex_missing_platform_binary_*。
let cmd = anchored_command_from_paths(
"codex",
"/Users/me/.nvm/versions/node/v22.14.0/bin/codex",
@@ -4018,7 +4130,7 @@ mod tests {
);
assert_eq!(
cmd.as_deref(),
- Some("/Users/me/.nvm/versions/node/v22.14.0/bin/codex update || /Users/me/.nvm/versions/node/v22.14.0/bin/npm i -g @openai/codex@latest")
+ Some("/Users/me/.nvm/versions/node/v22.14.0/bin/npm i -g @openai/codex@latest")
);
}
@@ -4038,9 +4150,25 @@ mod tests {
}
#[test]
- fn volta_uses_volta_install() {
+ fn volta_self_update_chain_anchors_to_volta() {
// `~/.volta/bin` 通常不在 GUI 非登录 `bash -c` 的 PATH 里,且用户可能
// PATH 上还有另一份 volta → 必须绝对路径锚定到命令行命中的这一份。
+ // 用 openclaw(仍在 prefers_official_update)覆盖 volta 分支的 self-update 链;
+ // codex 已改为不 self-update(见 codex_volta_anchors_to_volta_install)。
+ let cmd = anchored_command_from_paths(
+ "openclaw",
+ "/Users/me/.volta/bin/openclaw",
+ "/Users/me/.volta/tools/image/packages/openclaw/lib/node_modules/openclaw",
+ );
+ assert_eq!(
+ cmd.as_deref(),
+ Some("/Users/me/.volta/bin/openclaw update --yes || /Users/me/.volta/bin/volta install openclaw")
+ );
+ }
+
+ #[test]
+ fn codex_volta_anchors_to_volta_install() {
+ // codex 锚定到命令行命中的那份 volta,但不 self-update:纯 `volta install`。
let cmd = anchored_command_from_paths(
"codex",
"/Users/me/.volta/bin/codex",
@@ -4048,7 +4176,7 @@ mod tests {
);
assert_eq!(
cmd.as_deref(),
- Some("/Users/me/.volta/bin/codex update || /Users/me/.volta/bin/volta install @openai/codex")
+ Some("/Users/me/.volta/bin/volta install @openai/codex")
);
}
@@ -4076,7 +4204,7 @@ mod tests {
);
assert_eq!(
cmd.as_deref(),
- Some("'/Users/my name/.volta/bin/codex' update || '/Users/my name/.volta/bin/volta' install @openai/codex")
+ Some("'/Users/my name/.volta/bin/volta' install @openai/codex")
);
}
@@ -4144,7 +4272,7 @@ mod tests {
assert_eq!(
cmd.as_deref(),
Some(
- "/Users/me/.local/share/fnm_multishells/12345_abc/bin/codex update || /Users/me/.local/share/fnm_multishells/12345_abc/bin/npm i -g @openai/codex@latest"
+ "/Users/me/.local/share/fnm_multishells/12345_abc/bin/npm i -g @openai/codex@latest"
)
);
}
@@ -4158,7 +4286,7 @@ mod tests {
);
assert_eq!(
cmd.as_deref(),
- Some("'/Users/my name/.nvm/versions/node/v22/bin/codex' update || '/Users/my name/.nvm/versions/node/v22/bin/npm' i -g @openai/codex@latest")
+ Some("'/Users/my name/.nvm/versions/node/v22/bin/npm' i -g @openai/codex@latest")
);
}
@@ -4255,6 +4383,78 @@ mod tests {
assert!(default_install(&installs).is_none());
}
+ #[test]
+ fn codex_missing_platform_binary_self_heals_via_uninstall_install() {
+ // 平台二进制缺失 → `codex --version` 报 "Missing optional dependency" 退出非 0
+ // → enumerate 标记 runnable=false。此状态下普通 `npm i -g @latest` 是 no-op 修不好,
+ // 升级路径改用 uninstall+install 重装补回平台二进制(`|| true` 让 uninstall 在
+ // set -e 下对半损坏包返回非 0 时仍继续 install)。
+ let mut broken = inst("/Users/me/.nvm/versions/node/v22.14.0/bin/codex", true);
+ broken.runnable = false;
+ assert_eq!(
+ installs_anchored_command("codex", &[broken]).as_deref(),
+ Some("/Users/me/.nvm/versions/node/v22.14.0/bin/npm uninstall -g @openai/codex || true; /Users/me/.nvm/versions/node/v22.14.0/bin/npm i -g @openai/codex@latest")
+ );
+ }
+
+ #[test]
+ fn codex_runnable_uses_plain_npm_not_self_heal() {
+ // 正常(runnable=true)的 codex 升级:锚定 npm,既不重装、也不跑会假成功
+ // 掩盖损坏的 `codex update`。
+ let healthy = inst("/Users/me/.nvm/versions/node/v22.14.0/bin/codex", true);
+ let cmd = installs_anchored_command("codex", &[healthy]);
+ assert_eq!(
+ cmd.as_deref(),
+ Some("/Users/me/.nvm/versions/node/v22.14.0/bin/npm i -g @openai/codex@latest")
+ );
+ assert!(!cmd.unwrap().contains("uninstall"));
+ }
+
+ #[test]
+ fn codex_broken_homebrew_formula_uses_brew_not_npm_repair() {
+ // brew formula 装的坏 codex(real 在 Cellar):自愈门控必须收窄放行,回落到
+ // `brew upgrade codex`——若误走 npm 重装,npm 够不到 Cellar 那份、反而旁路
+ // 装第二份 npm 全局 codex 制造双安装。
+ let broken = ToolInstallation {
+ path: "/opt/homebrew/bin/codex".to_string(),
+ version: None,
+ runnable: false,
+ error: None,
+ source: "homebrew".to_string(),
+ is_path_default: true,
+ real: std::path::PathBuf::from("/opt/homebrew/Cellar/codex/1.2.3/bin/codex"),
+ };
+ assert_eq!(
+ installs_anchored_command("codex", &[broken]).as_deref(),
+ Some("/opt/homebrew/bin/brew upgrade codex")
+ );
+ }
+
+ #[test]
+ fn codex_broken_volta_uses_volta_install_not_npm_repair() {
+ // volta 装的坏 codex:回落到 `volta install`,不走 npm 重装。
+ let mut broken = inst("/Users/me/.volta/bin/codex", true);
+ broken.runnable = false;
+ assert_eq!(
+ installs_anchored_command("codex", &[broken]).as_deref(),
+ Some("/Users/me/.volta/bin/volta install @openai/codex")
+ );
+ }
+
+ #[test]
+ fn codex_broken_bun_uses_bun_add_not_phantom_npm() {
+ // bun 装的坏 codex:回落到 `bun add`,且**绝不**拼出 `~/.bun/bin/npm`
+ // (bun 目录下没有 npm,那条路径不存在、执行会直接失败)。
+ let mut broken = inst("/Users/me/.bun/bin/codex", true);
+ broken.runnable = false;
+ let cmd = installs_anchored_command("codex", &[broken]);
+ assert_eq!(
+ cmd.as_deref(),
+ Some("/Users/me/.bun/bin/bun add -g @openai/codex@latest")
+ );
+ assert!(!cmd.unwrap().contains("npm"));
+ }
+
#[test]
fn first_abs_path_line_skips_shell_noise() {
// 交互式 .zshrc 先打印欢迎语(如 powerlevel10k / 自定义提示),
@@ -4382,8 +4582,9 @@ mod tests {
);
assert_eq!(
static_fallback_command("codex"),
- "codex update || npm i -g @openai/codex@latest"
+ "npm i -g @openai/codex@latest"
);
+ assert!(!static_fallback_command("codex").contains("codex update"));
assert_eq!(
static_fallback_command("gemini"),
"npm i -g @google/gemini-cli@latest"
@@ -4693,6 +4894,124 @@ mod tests {
assert!(running_branch.contains("create tab with default profile"));
}
+ /// Terminal `activate` creates a default empty window on cold start; `launch` does not.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn terminal_applescript_cold_start_uses_launch_before_do_script() {
+ let script = build_macos_terminal_applescript(Path::new("/tmp/cc_switch_launcher.sh"));
+
+ assert!(
+ script.contains(r#"set was_running to application "Terminal" is running"#),
+ "missing was_running detection:\n{script}"
+ );
+ // Cold launches avoid `activate` until after `do script`, so no default empty window is created first.
+ assert!(
+ script.contains(
+ "else\n launch\n do script launcher_script\n activate"
+ ),
+ "cold start should launch before activating:\n{script}"
+ );
+ // Already-running launches should create a fresh session.
+ assert!(
+ script.contains(
+ "if was_running then\n activate\n do script launcher_script\n"
+ ),
+ "already-running branch should use bare do script:\n{script}"
+ );
+ }
+
+ /// Restored windows should not receive the launcher command.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn terminal_applescript_does_not_hijack_restored_windows() {
+ let script = build_macos_terminal_applescript(Path::new("/tmp/cc_switch_launcher.sh"));
+ assert!(
+ !script.contains(" in window 1"),
+ "should not inject into an existing/restored Terminal window:\n{script}"
+ );
+ assert!(
+ !script.contains("count of windows"),
+ "should not infer restored-window safety from window count:\n{script}"
+ );
+ }
+
+ /// Ghostty cold starts use `initial-command`; warm starts use the scripting dictionary.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn ghostty_applescript_cold_start_uses_initial_command() {
+ let script = build_macos_ghostty_applescript(Path::new("/tmp/cc_switch_launcher.sh"));
+
+ // Warm launches execute through the AppleScript command property, not `open -na ... -e`.
+ assert!(
+ script.contains(r#"set launcher_command to "bash '/tmp/cc_switch_launcher.sh'""#),
+ "missing launcher_command:\n{script}"
+ );
+ assert!(script.contains("if was_running then"));
+ assert!(script.contains("new window with configuration {command:launcher_command}"));
+ assert!(
+ !script.contains(" --args -e"),
+ "should not execute through open -na -e:\n{script}"
+ );
+ // Cold launches make Ghostty's first default surface execute the launcher.
+ assert!(script.contains(r#"set was_running to application "Ghostty" is running"#));
+ assert!(
+ script.contains(
+ r#"do shell script "open -na Ghostty --args --quit-after-last-window-closed=true " & quoted form of ("--initial-command=" & launcher_command)"#
+ ),
+ "cold start should use initial-command:\n{script}"
+ );
+ assert!(
+ !script.contains("--initial-window=false"),
+ "should not rely on initial-window=false:\n{script}"
+ );
+ assert!(
+ !script.contains("delay 0.5"),
+ "should not rely on a fixed delay:\n{script}"
+ );
+ assert!(
+ !script.contains("old_ids"),
+ "should not track default windows for closing:\n{script}"
+ );
+ assert!(
+ !script.contains("close window"),
+ "should not close a default window:\n{script}"
+ );
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn dash_c_command_wraps_script_path_inside_quoted_arg() {
+ // The script path must stay inside the `-c` string, not as a bare argv.
+ let s = build_macos_dash_c_command(Path::new("/tmp/cc_switch_launcher_1.sh"));
+ assert_eq!(s, "exec bash '/tmp/cc_switch_launcher_1.sh'");
+
+ // Spaces and single quotes must stay shell-safe too.
+ let s2 = build_macos_dash_c_command(Path::new("/Users/me/it's dir/x.sh"));
+ assert_eq!(s2, r#"exec bash '/Users/me/it'"'"'s dir/x.sh'"#);
+ }
+
+ /// AppleScript launchers need both shell-path quoting and AppleScript string quoting.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn applescript_builders_safely_quote_special_paths() {
+ // First shell-quote the path, then wrap the whole command as an AppleScript string.
+ let expected = r#""bash '/Users/me/it'\"'\"'s dir/x.sh'""#;
+ let p = Path::new("/Users/me/it's dir/x.sh");
+ assert_eq!(applescript_launcher_command(p), expected);
+ assert!(
+ build_macos_terminal_applescript(p).contains(expected),
+ "Terminal did not quote safely"
+ );
+ assert!(
+ build_macos_iterm2_applescript(p).contains(expected),
+ "iTerm2 did not quote safely"
+ );
+ assert!(
+ build_macos_ghostty_applescript(p).contains(expected),
+ "Ghostty did not quote safely"
+ );
+ }
+
#[test]
fn build_windows_cwd_command_str_uses_cd_for_drive_paths() {
let command = build_windows_cwd_command_str(r"C:\work\repo");
diff --git a/src-tauri/src/commands/model_fetch.rs b/src-tauri/src/commands/model_fetch.rs
index 7064e965b..c211bd651 100644
--- a/src-tauri/src/commands/model_fetch.rs
+++ b/src-tauri/src/commands/model_fetch.rs
@@ -14,12 +14,18 @@ pub async fn fetch_models_for_config(
api_key: String,
is_full_url: Option,
models_url: Option,
+ custom_user_agent: Option,
) -> Result, String> {
+ // 与转发 / 检测路径共用 parse_custom_user_agent:非法 UA 静默忽略(不阻断取模型)。
+ let user_agent = crate::provider::parse_custom_user_agent(custom_user_agent.as_deref())
+ .ok()
+ .flatten();
model_fetch::fetch_models(
&base_url,
&api_key,
is_full_url.unwrap_or(false),
models_url.as_deref(),
+ user_agent,
)
.await
}
diff --git a/src-tauri/src/commands/settings.rs b/src-tauri/src/commands/settings.rs
index 596255dc7..8cceccb4f 100644
--- a/src-tauri/src/commands/settings.rs
+++ b/src-tauri/src/commands/settings.rs
@@ -1,6 +1,7 @@
#![allow(non_snake_case)]
use tauri::AppHandle;
+use tauri_plugin_updater::UpdaterExt;
fn merge_settings_for_save(
mut incoming: crate::settings::AppSettings,
@@ -35,24 +36,11 @@ fn merge_settings_for_save(
}
_ => {}
}
- if incoming.local_migrations.is_none() {
- incoming.local_migrations = existing.local_migrations.clone();
- } else if let (Some(incoming_migrations), Some(existing_migrations)) =
- (&mut incoming.local_migrations, &existing.local_migrations)
- {
- if incoming_migrations
- .codex_third_party_history_provider_bucket_v1
- .is_none()
- {
- incoming_migrations.codex_third_party_history_provider_bucket_v1 = existing_migrations
- .codex_third_party_history_provider_bucket_v1
- .clone();
- }
- if incoming_migrations.codex_provider_template_v1.is_none() {
- incoming_migrations.codex_provider_template_v1 =
- existing_migrations.codex_provider_template_v1.clone();
- }
- }
+ // local_migrations 是纯后端状态(迁移完成标记),前端没有合法的修改场景,
+ // 无条件取现有值。若按 incoming 透传:后端清掉 marker(如关闭统一会话
+ // 开关)后、前端 query 缓存刷新前的一次全量保存会把旧 marker 重放回来,
+ // 重新开启时被"复活"的标记挡住而漏迁。
+ incoming.local_migrations = existing.local_migrations.clone();
incoming
}
@@ -64,13 +52,117 @@ pub async fn get_settings() -> Result {
/// 保存设置
#[tauri::command]
-pub async fn save_settings(settings: crate::settings::AppSettings) -> Result {
+pub async fn save_settings(
+ state: tauri::State<'_, crate::store::AppState>,
+ settings: crate::settings::AppSettings,
+) -> Result {
let existing = crate::settings::get_settings();
let merged = merge_settings_for_save(settings, &existing);
+ let unify_codex_changed =
+ merged.unify_codex_session_history != existing.unify_codex_session_history;
+ let unify_codex_enabled = merged.unify_codex_session_history;
crate::settings::update_settings(merged).map_err(|e| e.to_string())?;
+
+ // 统一会话开关变更时立即重写当前官方 Codex 供应商的 live 配置,
+ // 不必等下一次切换才生效。
+ if unify_codex_changed {
+ // live 重写失败时回滚设置并把保存整体报失败:若设置保持已切换状态,
+ // live 仍跑旧桶,后续的历史迁移/还原会让会话再次分裂(开启=历史
+ // 迁走而新会话仍写 openai 桶;关闭=会话还原而 live 仍写 custom)。
+ // 报错让前端 saved=false 短路还原;回滚是整次保存的事务语义
+ // (本开关的保存只携带开关相关字段)。
+ if let Err(err) =
+ crate::services::provider::reapply_current_codex_official_live(state.inner())
+ {
+ log::warn!("统一 Codex 会话历史开关变更后重写 live 配置失败,回滚设置: {err}");
+ if let Err(rollback_err) = crate::settings::update_settings(existing) {
+ log::error!("回滚统一会话开关设置失败: {rollback_err}");
+ }
+ return Err(format!(
+ "统一 Codex 会话历史开关未生效(live 配置重写失败): {err}"
+ ));
+ }
+
+ if unify_codex_enabled {
+ // 后台执行存量迁移(openai 桶 → custom 桶;仅当用户勾选了迁入既有
+ // 会话,函数内部自门控)。大会话目录可能要读数秒,不能阻塞设置保存;
+ // 失败时不写完成标记,下次启动自动重试。
+ tauri::async_runtime::spawn_blocking(|| {
+ match crate::codex_history_migration::maybe_migrate_codex_official_history_to_unified_bucket() {
+ Ok(outcome) => {
+ if let Some(reason) = outcome.skipped_reason {
+ log::debug!("○ Codex official history unify migration skipped: {reason}");
+ } else {
+ log::info!(
+ "✓ Codex official history unify migration completed: jsonl_files={}, state_rows={}",
+ outcome.migrated_jsonl_files,
+ outcome.migrated_state_rows
+ );
+ }
+ }
+ Err(e) => {
+ log::warn!("✗ Codex official history unify migration failed: {e}");
+ }
+ }
+ });
+ } else {
+ // 清除标记与迁移意愿,让重新开启并再次勾选时能补迁
+ // 关闭期间落入 openai 桶的官方会话。
+ if let Err(err) = crate::settings::clear_codex_official_history_unify_migration() {
+ log::warn!("清除统一会话迁移标记失败: {err}");
+ }
+ if let Err(err) = crate::settings::clear_codex_unify_migrate_existing() {
+ log::warn!("清除统一会话迁移意愿失败: {err}");
+ }
+ }
+ }
Ok(true)
}
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CodexUnifyHistoryRestoreResult {
+ pub restored_jsonl_files: usize,
+ pub restored_state_rows: usize,
+ /// 还原被跳过的原因(如当前目录没有账本),前端据此提示而非报"成功 0 项"。
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub skipped_reason: Option,
+}
+
+/// 是否存在统一会话开关的迁移备份(决定关闭弹窗里是否显示"恢复备份"勾选)。
+#[tauri::command]
+pub async fn has_codex_unify_history_backup() -> Result {
+ Ok(crate::codex_history_migration::has_codex_official_history_unify_backup())
+}
+
+/// 按迁移备份账本把当时迁入共享桶的官方会话还原回 "openai" 桶。
+/// 由关闭统一会话开关的确认弹窗触发;幂等,可安全重试。
+#[tauri::command]
+pub async fn restore_codex_unified_history() -> Result {
+ let outcome = tauri::async_runtime::spawn_blocking(|| {
+ crate::codex_history_migration::restore_codex_official_history_from_backups()
+ })
+ .await
+ .map_err(|e| e.to_string())?
+ .map_err(|e| e.to_string())?;
+
+ if let Some(reason) = &outcome.skipped_reason {
+ log::debug!("○ Codex official history restore skipped: {reason}");
+ } else {
+ log::info!(
+ "✓ Codex official history restored from backups: jsonl_files={}, state_rows={}",
+ outcome.restored_jsonl_files,
+ outcome.restored_state_rows
+ );
+ }
+
+ Ok(CodexUnifyHistoryRestoreResult {
+ restored_jsonl_files: outcome.restored_jsonl_files,
+ restored_state_rows: outcome.restored_state_rows,
+ skipped_reason: outcome.skipped_reason,
+ })
+}
+
/// 重启应用程序(当 app_config_dir 变更后使用)
#[tauri::command]
pub async fn restart_app(app: AppHandle) -> Result {
@@ -79,11 +171,80 @@ pub async fn restart_app(app: AppHandle) -> Result {
// 在后台延迟重启,让函数有时间返回响应
tauri::async_runtime::spawn(async move {
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
+ // app.restart() 走 RESTART_EXIT_CODE 路径,ExitRequested 处理器会直接
+ // 放行给 Tauri 默认 re-exec,不执行代理/Live 清理。但本命令用于
+ // app_config_dir 变更后的重启:新实例会切到新数据库,拿不到旧库里的
+ // Live 备份,无法恢复被接管的 Live 配置。因此必须趁旧实例的事件循环
+ // 仍存活,在这里同步完成恢复(保留代理状态,新实例启动时自动重新接管)。
+ crate::cleanup_before_exit(&app).await;
app.restart();
});
Ok(true)
}
+/// 下载并安装应用更新,然后由后端直接重启应用。
+///
+/// macOS 更新会原地替换 `.app` bundle。如果先返回前端、再让旧 WebView 调
+/// `process.relaunch()`,旧进程可能已经处在 bundle 被替换后的不稳定窗口期。
+/// 这里把退出清理、安装和重启串在同一个后端流程中,避免依赖旧前端继续执行。
+#[tauri::command]
+pub async fn install_update_and_restart(app: AppHandle) -> Result {
+ let updater = app
+ .updater_builder()
+ .build()
+ .map_err(|e| format!("初始化更新器失败: {e}"))?;
+
+ let Some(update) = updater
+ .check()
+ .await
+ .map_err(|e| format!("检查更新失败: {e}"))?
+ else {
+ return Ok(false);
+ };
+
+ log::info!("开始下载应用更新: {}", update.version);
+ let bytes = update
+ .download(|_, _| {}, || {})
+ .await
+ .map_err(|e| format!("下载更新失败: {e}"))?;
+
+ log::info!("开始安装应用更新: {}", update.version);
+
+ #[cfg(target_os = "windows")]
+ {
+ // Windows updater 会在 install() 内启动安装器并直接退出当前进程
+ // (插件内部 std::process::exit(0),绕过 TrayIcon::drop、不发
+ // NIM_DELETE,会残留死图标——与托盘"退出"路径相同的问题)。
+ // 因此清理只能放在 install 前执行,且必须显式移除托盘图标。
+ crate::save_window_state_before_exit(&app);
+ crate::cleanup_before_exit(&app).await;
+ crate::remove_tray_icon_before_exit(&app);
+ crate::destroy_single_instance_lock(&app);
+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
+ update.install(bytes).map_err(|e| {
+ format!(
+ "Windows 更新安装失败: {e}。已执行退出前清理,代理或 Live 接管可能已暂停;请重启应用或重新开启代理后再试。"
+ )
+ })?;
+ return Ok(true);
+ }
+
+ #[cfg(not(target_os = "windows"))]
+ {
+ // macOS/Linux install() 会返回;先安装,避免安装失败时误停代理/撤回接管。
+ update
+ .install(bytes)
+ .map_err(|e| format!("安装更新失败: {e}"))?;
+
+ crate::save_window_state_before_exit(&app);
+ crate::cleanup_before_exit(&app).await;
+
+ log::info!("应用更新安装完成,正在重启应用");
+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
+ crate::restart_process(&app);
+ }
+}
+
/// 获取 app_config_dir 覆盖配置 (从 Store)
#[tauri::command]
pub async fn get_app_config_dir_override(app: AppHandle) -> Result