Skip to content

Commit 0978221

Browse files
committed
fix(codex): address CodeRabbit round on the rebased head
Thread CodexAccountUsabilityOptions through the tier-aware selection paths (pickPriorityPreemption and the round-robin/fill-first branches of pickAlternateCodexAccount), so nativeMainSelectionOnly is honored consistently with the quota path during main-profile draining. Close and block an open Select when disabled flips: the dropdown is no longer rendered and the option buttons are disabled, so a shared controller flipping priorityUpdatingId cannot leave clickable options that silently drop the second update. Strengthen the tests: - exact-selector regression now configures a live pin alongside the priorities and asserts the pin survives, covering the stronger pin-ceiling case; - routing-level regression proves selection options reach the tier and alternate paths; - config-set pin-release test asserts each written order value; - controller-contract test guards the slice windows instead of slicing potentially-empty ranges; - toast-tone no-op test uses the real feedback selectors. Docs and copy accuracy: - switch strings state that existing account-affine threads and in-flight requests keep their captured account, and only new/unbound requests use the selected account's order tier (en/ja/ko/ru); - README qualifies lowest-usage as the quota policy and replaces unconditional thread-pinning claims; - web-dashboard adds the Pool/Direct boundary and full pin-release conditions across locales; - CLI current reports priority-aware selection; - US-English afterward and a split Russian pin-release sentence.
1 parent b507429 commit 0978221

22 files changed

Lines changed: 105 additions & 44 deletions

‎README.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,13 @@ Open **http://localhost:10100** and configure everything in the web dashboard
6161
(40+ built-ins, or any OpenAI-compatible endpoint), pick models, manage accounts. `ocx gui`
6262
re-opens the dashboard at any time.
6363
It can also manage a **ChatGPT account pool** for Codex auth. Add multiple ChatGPT / Codex accounts,
64-
refresh their 5h / weekly / 30d quota in the dashboard, and let new sessions auto-route to the
65-
lowest-usage healthy account. Existing Codex threads stay pinned to the account that started them,
66-
so long SSH, tmux, or mobile-connected sessions do not jump accounts mid-conversation. Give the
67-
accounts a selection order when one of them — usually your Codex Desktop login — should only be
68-
reached for once the others are drained.
64+
refresh their 5h / weekly / 30d quota in the dashboard. Under quota routing, new sessions can use
65+
the lowest-usage healthy account; round-robin and fill-first use their own policies. Existing Codex
66+
threads normally retain affinity to the account that started them, so long SSH, tmux, or
67+
mobile-connected sessions do not jump accounts mid-conversation — but quota re-evaluation, failover,
68+
account exclusion, affinity expiry, or 401/403 and 429 recovery can rebind them. Give the accounts a
69+
selection order when one of them — usually your Codex Desktop login — should only be reached for
70+
once the others are drained.
6971

7072
### For agents
7173

‎docs-site/src/content/docs/guides/web-dashboard.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,11 @@ catalog entry.
105105

106106
The **Codex Auth** page manages the native ChatGPT/Codex route:
107107

108+
Pool mode selects across the main and added Codex accounts; Direct uses only the caller/main login.
109+
In-flight requests keep their captured credentials, and a 401/403 reauthentication or 429 cooldown
110+
may clear affinity and rotate to another eligible Pool account. This is separate from `openai-apikey`
111+
and other providers.
112+
108113
- Manually choosing an account applies immediately: an already-bound thread moves to it on its next
109114
request, and only requests already in flight keep the account they captured. A manual choice is also
110115
pinned: the card shows a **PINNED** badge, and a higher selection order cannot preempt that account

‎docs-site/src/content/docs/ja/guides/web-dashboard.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,8 @@ Codex タスクだけに適用され、このオプション自体が委任を
8989

9090
**Codex 認証**ページはネイティブ ChatGPT/Codex ルートを管理します。
9191

92+
プールモードはメインと追加した Codex アカウントを横断して選択します。Direct は呼び出し元またはメインのログインのみを使います。送信中のリクエストは取得済みの資格情報を維持し、401/403 の再認証や 429 の cooldown が affinity を解除して別の適格なプールアカウントへ切り替えることがあります。これは `openai-apikey` や他のプロバイダーとは別の仕組みです。
93+
9294
- アカウントを直接選ぶとすぐに反映されます。すでにアカウントが紐付いた thread も次のリクエストで選んだ
9395
アカウントに移り、すでに送信中のリクエストだけが取得済みのアカウントを使い続けます。手動で選んだアカウントは固定もされます。
9496
カードに **固定中** バッジが付き、そのアカウントが使い切られるか、別のアカウントを選ぶか、いずれかの

‎docs-site/src/content/docs/ja/reference/cli/providers-accounts.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ Codex pool selection applies to the next request after clearing existing affinit
121121

122122
### `ocx account current <provider> [--json]`
123123

124-
アクティブなアカウントまたはキーを表示します。手動ピンのない Codex プールは、自動的に最低使用量の選択を報告します。アクティブな認証情報を持たない別のファミリーは、その状態を報告し、依然として 0 を終了します。`--json` は次を返します。
124+
アクティブなアカウントまたはキーを表示します。手動ピンのない Codex プールは、優先度を考慮した自動選択を報告します。最も優先度の高い適格ティアが選ばれ、そのティア内でクォータルーティングのもと最低使用量のアカウントが選ばれます。アクティブな認証情報を持たない別のファミリーは、その状態を報告し、依然として 0 を終了します。`--json` は次を返します。
125125

126126
```text
127127
{ provider, type, activeId: string | null, autoSwitchThreshold?: number, account: AccountRow | null }

‎docs-site/src/content/docs/ko/guides/web-dashboard.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ Dashboard의 **Sub-agent delegation** 선택기는 `injectionModel`과 선택적
9292
- 계정을 직접 고르면 곧바로 적용됩니다. 이미 계정이 묶인 thread도 다음 요청에서 고른 계정으로
9393
옮겨가고, 이미 전송 중인 요청만 가져간 계정을 그대로 씁니다. 직접 고른 계정은 고정되기도 합니다. 카드에 **고정됨** 배지가
9494
붙고, 그 계정이 소진되거나, 다른 계정을 고르거나, 어느 계정의 선택 순서를 바꿀 때까지 더 높은 선택
95-
순서가 끼어들지 못합니다.
95+
순서가 끼어들지 못합니다. 계정이 제외되거나 삭제되거나 명시적으로 failover/promotion 되면 고정도 함께 풀립니다.
9696
- 각 계정 카드에는 **선택 순서** 컨트롤(가장 먼저 / 먼저 / 기본 / 나중에 / 가장 마지막)이 있습니다.
9797
순서가 높은 계정부터 쓰이며, 그 위의 계정이 모두 소진되거나 사용할 수 없게 된 뒤에야 낮은 순서로
9898
내려갑니다. 순서를 바꾸면 **다음 미바인딩 요청** 부터 적용되며, 이미 계정에 바인딩된 thread를 옮기지

‎docs-site/src/content/docs/ko/reference/cli/providers-accounts.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ Codex pool selection applies to the next request after clearing existing affinit
121121

122122
### `ocx account current <provider> [--json]`
123123

124-
활성 계정이나 키를 보여줍니다. 수동 고정이 없는 Codex 풀은 자동으로 가장 적게 사용한 항목을 선택한다고 보고합니다. 활성 자격 증명이 없는 다른 계열은 그 상태를 보고하고도 종료 코드 0으로 끝납니다. `--json`은 다음을 반환합니다:
124+
활성 계정이나 키를 보여줍니다. 수동 고정이 없는 Codex 풀은 우선순위를 고려한 자동 선택을 보고합니다. 가장 우선순위가 높은 적격 tier를 고르고, 그 tier 안에서 할당량 라우팅 기준으로 가장 적게 사용한 항목을 선택합니다. 활성 자격 증명이 없는 다른 계열은 그 상태를 보고하고도 종료 코드 0으로 끝납니다. `--json`은 다음을 반환합니다:
125125

126126
```text
127127
{ provider, type, activeId: string | null, autoSwitchThreshold?: number, account: AccountRow | null }

‎docs-site/src/content/docs/reference/cli/providers-accounts.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,10 @@ returns:
144144

145145
### `ocx account current <provider> [--json]`
146146

147-
Shows the active account or key. A Codex pool with no manual pin reports automatic lowest-usage
148-
selection; another family with no active credential reports that state and still exits 0. `--json`
149-
returns:
147+
Shows the active account or key. A Codex pool with no manual pin reports the priority-aware
148+
automatic selection: the highest-priority eligible tier is chosen, and the lowest-usage account
149+
within that tier is selected under quota routing; another family with no active credential reports
150+
that state and still exits 0. `--json` returns:
150151

151152
```text
152153
{ provider, type, activeId: string | null, autoSwitchThreshold?: number, account: AccountRow | null }

‎docs-site/src/content/docs/reference/configuration/providers.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ authenticated.
2020
| `codexAccountNamespaces?` | `Record<string, string>` | — | Optional map from an arbitrary public model selector to a stored Codex account target. Each selector whose target is present adds separate `<selector>/<native-openai-model>` rows to the Codex picker; each row uses only that account. With any selector active, bare native rows are hidden in the picker, but their ids remain routable and listed by raw `/v1/models` unless explicitly disabled. |
2121
| `activeCodexAccountId?` | `string` | — | Manually selected Pool account for the next request. Selection clears thread affinity; in-flight requests keep captured credentials. |
2222
| `codexAccountPriorities?` | `Record<string, number>` | — | Per-account selection order for the Codex pool: account id → integer from `-100` to `100`, **higher is used earlier**, absent means `0`. This is an ordering boundary, not an eligibility one: selection narrows the already-eligible accounts to the highest tier that still has quota headroom, and `accountPoolStrategy` then picks within that tier. A tier is skipped only when every member is over `autoSwitchThreshold`, cooling down, soft-avoided, paused, or needs reauthentication — unknown quota never drains a tier. Ordering never makes an ineligible account selectable and never re-binds a thread that already has an account. The main `__main__` account participates on equal terms, which is how the Codex Desktop login can be set to drain last. With no entries the pool behaves exactly as before. A malformed map is ignored with a console warning (ordering off, no config repair). Managed by `ocx account priority` and the Codex Auth page. |
23-
| `activeCodexAccountPinned?` | `string` | — | Account id the operator last selected by hand. While set, a higher `codexAccountPriorities` tier cannot preempt it until the pin is released by drain, exclusion, deletion, or an explicit failover/promotion away. Ordinary round-robin movement inside the capped tier does not release it. Writing any `codexAccountPriorities` entry also releases the pin, so a pin made before an order existed cannot outrank one set afterwards. `GET /api/codex-auth/active` reports both whether the effective account is pinned (`pinned`) and the account carrying the ceiling (`pinnedAccountId`). |
23+
| `activeCodexAccountPinned?` | `string` | — | Account id the operator last selected by hand. While set, a higher `codexAccountPriorities` tier cannot preempt it until the pin is released by drain, exclusion, deletion, or an explicit failover/promotion away. Ordinary round-robin movement inside the capped tier does not release it. Writing any `codexAccountPriorities` entry also releases the pin, so a pin made before an order existed cannot outrank one set afterward. `GET /api/codex-auth/active` reports both whether the effective account is pinned (`pinned`) and the account carrying the ceiling (`pinnedAccountId`). |
2424
| `autoSwitchThreshold?` | `number` | `80` | Usage threshold for proactive switching. `quota` can re-evaluate both bound and unbound tasks on their next request; `fill-first` uses it only as the drain point for unbound assignment; normal `round-robin` selection does not use it. The score uses the hottest known 5h, weekly, or 30d quota window. `0` disables usage-based proactive switching only, not unbound assignment or failure recovery. |
2525
| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | Assignment strategy for new/unbound Codex requests. A request is unbound when it has no live (parent thread id, quota scope) affinity; a visible existing task can become unbound after proxy restart or affinity reset. `quota` picks the lowest-usage eligible account when no active account exists, keeps an eligible active account below `autoSwitchThreshold`, and after the threshold may move an unbound request or proactively rebind a bound task to a lower-usage eligible account. `round-robin` distributes unbound requests evenly; `fill-first` keeps assigning unbound requests to the active account until cooldown, unavailability, or the configured drain threshold. |
2626
| `accountPoolStickyLimit?` | `number` | `1` | New/unbound task assignments retained on one round-robin selection before advancing; the counter advances when a task is bound, not after an upstream success. Range 1–100. |

‎docs-site/src/content/docs/ru/guides/web-dashboard.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,8 @@ bun run dev:gui
9696
следующего запроса, а захваченный аккаунт сохраняют только уже отправленные запросы. Выбранный вручную аккаунт также закрепляется:
9797
на карточке появляется бейдж **ЗАКРЕПЛЁН**, и более высокий порядок выбора не может вытеснить этот
9898
аккаунт, пока он не исчерпан, пока вы не выберете другой аккаунт или пока не измените порядок
99-
выбора любого аккаунта.
99+
выбора любого аккаунта. Закрепление также снимается при исключении или удалении аккаунта, а также
100+
при явном failover/promotion.
100101
- На карточке каждого аккаунта есть элемент управления **Порядок выбора** (Первым, Раньше,
101102
По умолчанию, Позже, Последним). Аккаунты с более высоким порядком используются раньше, а на более
102103
низкий порядок пул опускается лишь тогда, когда все аккаунты выше исчерпаны или недоступны.

‎docs-site/src/content/docs/ru/reference/cli/providers-accounts.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ label и masked key.
149149
### `ocx account current <provider> [--json]`
150150

151151
Показывает активный аккаунт или ключ. Если в пуле Codex нет ручного pin'а, команда сообщает об
152-
автоматическом выборе аккаунта с наименьшим usage; если в другом семействе нет активного
152+
автоматическом выборе с учётом порядка: выбирается самый высокий подходящий уровень, а внутри него при quota-маршрутизации аккаунт с наименьшим usage; если в другом семействе нет активного
153153
credential'а, это состояние тоже печатается, но код выхода всё равно остаётся 0. `--json`
154154
возвращает:
155155

@@ -212,7 +212,8 @@ quota-bar'ов дашборда.
212212
него аккаунт выбирает `accountPoolStrategy`. Пауза, cooldown и повторная аутентификация не
213213
затрагиваются. Изменения действуют начиная со **следующего непривязанного запроса**, а не только для новых сессий:
214214
как только у более высокого порядка снова появляется запас, preemption сразу поднимает непривязанный
215-
запрос. Потоки, уже привязанные к аккаунту, обычно сохраняют его до исчерпания, но ошибка повторной аутентификации, cooldown по квоте или серия временных сбоев снимают привязку раньше. Любая принятая запись также снимает ручное закрепление "использовать этот аккаунт сейчас" с того аккаунта, на котором оно стояло, в том числе запись того же порядка, который уже был установлен, -- это единственный способ снять закрепление, сохранив выбранный аккаунт. (Сброс активного аккаунта через management API тоже снимает закрепление, но вместе с самим выбором.) Недоступный прокси, неизвестный id аккаунта или значение вне допустимого набора завершаются
215+
запрос. Потоки, уже привязанные к аккаунту, обычно сохраняют его до исчерпания, но ошибка повторной аутентификации, cooldown по квоте или серия временных сбоев снимают привязку раньше.
216+
Любая принятая запись также снимает ручное закрепление "использовать этот аккаунт сейчас" с того аккаунта, на котором оно стояло. Это касается и записи того же порядка, который уже был установлен. Такой способ — единственный, который снимает закрепление, сохранив выбранный аккаунт. Сброс активного аккаунта через management API тоже снимает закрепление, но вместе с самим выбором. Недоступный прокси, неизвестный id аккаунта или значение вне допустимого набора завершаются
216217
с кодом 1. `--json` возвращает:
217218

218219
```text

0 commit comments

Comments
 (0)