diff --git a/devlog/_plan/260907_lane_c/040_desktop.md b/devlog/_plan/260907_lane_c/040_desktop.md index ad7fb60177..4eb4ebffd5 100644 --- a/devlog/_plan/260907_lane_c/040_desktop.md +++ b/devlog/_plan/260907_lane_c/040_desktop.md @@ -402,3 +402,7 @@ index 84ac5f67b..b6be3c2f6 100644 ``` Audit amendment: clear catalogRefreshPending only if sync status is affirmative success, not HTTP 200 skipped. Add skipped/no-write regression. + +## Lane E documentation handoff + +After run 34106956362 reported a GUI lint failure, include the separately prepared code-mode host-rule translations in the seven fr/ja/ko/ru/tr/zh-cn/zh-tw Codex integration guides. The patch adds 51 documentation lines matching the existing English paragraph; it does not modify runtime code or provider guides. Apply on the Desktop layer, record `docs handoff from lane E` and `[skip ci]` in its own commit, then cascade the fallback layer and dispatch the top CI again. Local documentation install/build remains NOT RUN. diff --git a/docs-site/public/pr-screenshots/subagent-fallback-settings.png b/docs-site/public/pr-screenshots/subagent-fallback-settings.png new file mode 100644 index 0000000000..04f72f140c Binary files /dev/null and b/docs-site/public/pr-screenshots/subagent-fallback-settings.png differ diff --git a/docs-site/src/content/docs/fr/guides/codex-integration.md b/docs-site/src/content/docs/fr/guides/codex-integration.md index 02ffa8a211..a351adeae5 100644 --- a/docs-site/src/content/docs/fr/guides/codex-integration.md +++ b/docs-site/src/content/docs/fr/guides/codex-integration.md @@ -233,6 +233,14 @@ opencodex encode cette déclaration et son historique sous forme d'outil de fonc cycle de vie diffusé de l'appel de fonction en `custom_tool_call` avant que Codex ne le reçoive. Le routage natif par transfert OpenAI et l'outil personnalisé `apply_patch`, qui est pris en charge, restent inchangés. +Avant le premier appel, les tours routés en mode code reçoivent aussi les règles de l'hôte pour les +outils auxiliaires imbriqués : `tools.apply_patch` prend une seule chaîne qui commence et se termine +par les lignes de marqueur de patch seules, sans habillage ; l'isolate ne dispose pas de `import`, +et les commandes longues sont interrogées via `write_stdin`. Lorsqu'un résultat exec en mode code +sur le chemin natif Responses routé, Kiro ou Cursor contient encore l'un des messages d'échec de +l'hôte, opencodex ajoute une indication d'une ligne qui nomme la règle. Cette modification ne +réécrit ni le code du modèle ni le texte de son patch. + Le fournisseur sélectionné doit prendre en charge les appels de fonctions ou d'outils. Un fournisseur purement textuel dépourvu de cette prise en charge ne peut pas utiliser `exec`, Browser ni Computer Use. Les lignes OpenAI natives conservent leur mode d'outil en amont. diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index 7d66e72c3f..f5592c0a72 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -215,6 +215,15 @@ HTTP/SSE. ### Authless Codex Desktop (opt-in) +In **Dashboard → Overview**, **Open Codex without signing in** controls this existing +opt-in preference. The switch defaults to **off** when the setting is absent or false; +an existing explicit `codexDesktopAuthless: true` stays enabled. The dashboard saves +the preference and runs a full sync. Restart Codex Desktop after changing it. +If synchronization fails, the saved preference remains and the dashboard shows the error; +retry **Sync** before restarting. Account-gated Desktop features may be unavailable +when enabled. Upstream credentials, local eligibility, remote admission authentication +and user-owned gateway settings retain their existing requirements. + Codex Desktop shows its ChatGPT login screen whenever the active provider requires OpenAI auth. If your OpenCodex setup never uses ChatGPT credentials (routed providers only, or a blocked `chatgpt.com`), you can opt out of that gate: @@ -577,3 +586,10 @@ ocx restore back # point plain Codex at the running proxy again When opencodex runs as a managed [background service](/reference/cli/#ocx-service), it sets `OCX_SERVICE=1` so a service-driven restart does **not** thrash the Codex config — only an explicit `ocx stop` / `ocx service stop` restores native Codex. + + +### Sub-agent fallback and V2 compatibility + +In **Subagents → Delegation settings**, edit the ordered fallback chain and its availability polling interval (5000–600000 ms), then save it separately from the featured roster. A configured target that is no longer advertised remains in the chain until you remove it. The roster and fallback chain are separate settings; this editor does not make the roster replace the fallback policy. + +When a routed preferred model may receive V2 work from a native ChatGPT parent, the panel explains the upstream encrypted-task limitation. Readable tasks from routed parents are unaffected. The guidance uses `/api/v2` mode and native V1 pin state; the current API does not expose recovery activation or request-specific eligibility, so the panel reports those as unknown. V1/plaintext-compatible delegation remains an alternative. Experimental V2 recovery, where eligible and explicitly enabled, adds quota usage, latency, backend dependence and possible fidelity loss; it does not repair the upstream protocol. See [sub-agent surfaces](/guides/sub-agent-surface/) and [the upstream limitation](https://github.com/lidge-jun/opencodex/issues/92). diff --git a/docs-site/src/content/docs/ja/guides/codex-integration.md b/docs-site/src/content/docs/ja/guides/codex-integration.md index d1d977b35c..46c33320f2 100644 --- a/docs-site/src/content/docs/ja/guides/codex-integration.md +++ b/docs-site/src/content/docs/ja/guides/codex-integration.md @@ -147,6 +147,14 @@ Codex の `exec` custom-tool grammar を受け付けない key-auth Responses pr `custom_tool_call` へ復元します。ネイティブ OpenAI の forward routing と、対応済みの `apply_patch` custom tool は 変更されません。 +ルーティングされた code-mode のターンには、最初の呼び出し前に、ネストされたヘルパーに関する +ホストの規則も伝えられます。`tools.apply_patch` は、装飾を付けないパッチマーカー行で始まり、 +同様のマーカー行で終わる単一の文字列を受け取ります。isolate では `import` を使用できず、 +長時間実行されるコマンドは `write_stdin` でポーリングします。ネイティブのルーティング済み Responses、 +Kiro、または Cursor の経路で、code-mode の exec 結果にホストの失敗メッセージがまだ含まれている場合、 +opencodex は該当する規則を示す 1 行のヒントを追加します。この変更でモデルのコードやパッチのテキストを +書き換えることはありません。 + 選択した provider は function/tool calling をサポートしている必要があります。tool call に対応しない text-only provider では `exec`、Browser、Computer Use は使用できません。ネイティブ OpenAI の項目は上流の tool mode を そのまま維持します。 diff --git a/docs-site/src/content/docs/ko/guides/codex-integration.md b/docs-site/src/content/docs/ko/guides/codex-integration.md index 44551de837..1f324adaf2 100644 --- a/docs-site/src/content/docs/ko/guides/codex-integration.md +++ b/docs-site/src/content/docs/ko/guides/codex-integration.md @@ -149,6 +149,13 @@ history를 업스트림 function tool로 인코딩한 다음 스트리밍된 fun `custom_tool_call`로 복원합니다. 네이티브 OpenAI forward routing과 지원되는 `apply_patch` custom tool은 변경되지 않습니다. +라우팅된 code-mode 턴에는 첫 호출 전에 중첩 helper에 대한 호스트 규칙도 전달됩니다. +`tools.apply_patch`는 별도 장식 없이 패치 마커만 있는 줄로 시작하고 끝나는 하나의 문자열을 받습니다. +isolate에서는 `import`를 사용할 수 없으며, 오래 실행되는 명령은 `write_stdin`으로 폴링합니다. +네이티브 라우팅 Responses, Kiro 또는 Cursor 경로의 code-mode exec 결과에 호스트의 실패 메시지 중 +하나가 여전히 포함되어 있으면, opencodex는 해당 규칙을 명시하는 한 줄짜리 힌트를 덧붙입니다. +이 변경은 모델의 코드나 패치 텍스트를 다시 작성하지 않습니다. + 선택한 provider는 function/tool calling을 지원해야 합니다. tool call을 지원하지 않는 text-only provider에서는 `exec`, Browser 또는 Computer Use를 사용할 수 없습니다. 네이티브 OpenAI 항목은 업스트림 tool mode를 그대로 유지합니다. diff --git a/docs-site/src/content/docs/ru/guides/codex-integration.md b/docs-site/src/content/docs/ru/guides/codex-integration.md index 9707a3ea44..23581e56f6 100644 --- a/docs-site/src/content/docs/ru/guides/codex-integration.md +++ b/docs-site/src/content/docs/ru/guides/codex-integration.md @@ -224,6 +224,14 @@ opencodex кодирует объявление и историю как functio потоковый lifecycle function call в `custom_tool_call` до передачи в Codex. Нативная forward- маршрутизация OpenAI и поддерживаемый custom tool `apply_patch` остаются без изменений. +Перед первым вызовом маршрутизируемые ходы в code-mode также получают правила хоста для вложенных +вспомогательных инструментов: `tools.apply_patch` принимает одну строку, которая начинается и +заканчивается отдельными строками маркеров патча без дополнительного оформления; в isolate нет +`import`, а длительные команды опрашиваются через `write_stdin`. Если результат exec в code-mode +на нативном маршрутизируемом пути Responses, Kiro или Cursor всё ещё содержит одно из сообщений +хоста об ошибке, opencodex добавляет однострочную подсказку с указанием правила. Это изменение +не переписывает код модели или текст её патча. + Выбранный provider должен поддерживать function/tool calling. Text-only provider без tool calls не может использовать `exec`, Browser или Computer Use. Нативные записи OpenAI сохраняют свой upstream tool mode без изменений. diff --git a/docs-site/src/content/docs/tr/guides/codex-integration.md b/docs-site/src/content/docs/tr/guides/codex-integration.md index 02fae0f468..d13af52274 100644 --- a/docs-site/src/content/docs/tr/guides/codex-integration.md +++ b/docs-site/src/content/docs/tr/guides/codex-integration.md @@ -262,6 +262,14 @@ fonksiyon aracı olarak kodlar, ardından akışlı fonksiyon çağrısı yaşam Codex görmeden önce `custom_tool_call`'a geri yükler. Yerel OpenAI iletme yönlendirmesi ve desteklenen `apply_patch` özel aracı değişmeden kalır. +Yönlendirilen code-mode turlarına, ilk çağrıdan önce iç içe geçmiş yardımcılar için geçerli olan +ana makine kuralları da bildirilir: `tools.apply_patch`, yalnızca yama işaretçilerinden oluşan +satırlarla başlayan ve biten tek bir dize alır; isolate içinde `import` yoktur ve uzun süren +komutlar `write_stdin` üzerinden yoklanır. Yerel yönlendirilmiş Responses, Kiro veya Cursor yolundaki +bir code-mode exec sonucu hâlâ ana makinenin hata mesajlarından birini içeriyorsa opencodex, +ilgili kuralı belirten tek satırlık bir ipucu ekler. Bu değişiklik modelin kodunu veya yama metnini +yeniden yazmaz. + Seçilen sağlayıcı fonksiyon/araç çağrısını desteklemelidir. Araç çağrısı desteği olmayan salt metin bir sağlayıcı `exec`, Tarayıcı veya Bilgisayar Kullanımını kullanamaz. Yerel OpenAI satırları yukarı akış araç modunu değiştirmeden tutar. diff --git a/docs-site/src/content/docs/zh-cn/guides/codex-integration.md b/docs-site/src/content/docs/zh-cn/guides/codex-integration.md index 552c0c3f53..0c3df0c0e2 100644 --- a/docs-site/src/content/docs/zh-cn/guides/codex-integration.md +++ b/docs-site/src/content/docs/zh-cn/guides/codex-integration.md @@ -196,6 +196,12 @@ Codex 显示的模型来自一个磁盘上的 catalog(默认是 `$CODEX_HOME/o 历史记录编码成上游 function tool,再在 Codex 收到结果前,把流式 function-call lifecycle 还原成 `custom_tool_call`。原生 OpenAI forward routing 和已支持的 `apply_patch` custom tool 保持不变。 +路由的 code-mode 轮次还会在首次调用前收到宿主对嵌套辅助工具的规则:`tools.apply_patch` +接收一个字符串,首尾必须是没有额外包装的独立补丁标记行;isolate 中没有 `import`,长时间运行的 +命令通过 `write_stdin` 轮询。如果原生路由 Responses、Kiro 或 Cursor 路径上的 code-mode exec +结果仍包含宿主的某条失败消息,opencodex 会追加一行提示,指出对应规则。此变更不会重写模型的 +代码或补丁文本。 + 所选 provider 必须支持 function/tool calling。不支持 tool call 的 text-only provider 无法使用 `exec`、 Browser 或 Computer Use。原生 OpenAI 条目会保持其上游 tool mode 不变。 diff --git a/docs-site/src/content/docs/zh-tw/guides/codex-integration.md b/docs-site/src/content/docs/zh-tw/guides/codex-integration.md index f371457be9..44ee5bbb3b 100644 --- a/docs-site/src/content/docs/zh-tw/guides/codex-integration.md +++ b/docs-site/src/content/docs/zh-tw/guides/codex-integration.md @@ -201,6 +201,12 @@ metadata,使用 Codex 的 `low | medium | high | xhigh | max | ultra` 檔位 歷史編碼成上游 function tool,再於 Codex 看見前將串流 function-call lifecycle 還原成 `custom_tool_call`。原生 OpenAI forward 路由與受支援的 `apply_patch` custom tool 維持不變。 +路由的 code-mode 回合也會在首次呼叫前收到主機對巢狀輔助工具的規則:`tools.apply_patch` +接收一個字串,開頭與結尾必須是沒有額外包裝的獨立補丁標記行;isolate 中沒有 `import`,長時間執行的 +命令透過 `write_stdin` 輪詢。如果原生路由 Responses、Kiro 或 Cursor 路徑上的 code-mode exec +結果仍包含主機的某則失敗訊息,opencodex 會附加一行提示,指出對應規則。這項變更不會重寫模型的 +程式碼或補丁文字。 + 所選 provider 必須支援 function/tool calling。不支援 tool call 的純文字 provider 無法使用 `exec`、 Browser 或 Computer Use。原生 OpenAI 列保留上游 tool mode 不變。 diff --git a/docs/pr-assets/codex-desktop-opt-in.jpg b/docs/pr-assets/codex-desktop-opt-in.jpg new file mode 100644 index 0000000000..d06203e711 Binary files /dev/null and b/docs/pr-assets/codex-desktop-opt-in.jpg differ diff --git a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx index 46c0447a7c..a1b405c2d9 100644 --- a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx +++ b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx @@ -6,9 +6,9 @@ * better next to the roster it affects: the roster picks who may be called, this picks who * gets called first. */ -import { useState } from "react"; +import { useLayoutEffect, useRef, useState } from "react"; import { Select, Tooltip } from "../../ui"; -import { IconInfo } from "../../icons"; +import { IconArrowDown, IconArrowUp, IconInfo, IconX } from "../../icons"; import { useT, type TKey } from "../../i18n/shared"; import { formatNamespacedModelId } from "../../provider-icons"; import type { DelegationPatch, DelegationModelOption } from "../../pages/use-subagent-delegation"; @@ -28,6 +28,13 @@ export interface SubagentDelegationSectionProps { onUltraModeSave: (patch: UltraModePatch) => void; ultraLoadFailed: boolean; onUltraModeRetry: () => void; + fallback: string[]; + fallbackPollMs: number; + fallbackBusy: boolean; + availableModels: string[]; + onFallbackChange: (models: string[]) => void; + onFallbackPollMsChange: (pollMs: number) => void; + onFallbackSave: () => void; } export default function SubagentDelegationSection({ @@ -44,12 +51,60 @@ export default function SubagentDelegationSection({ onUltraModeSave, ultraLoadFailed, onUltraModeRetry, + fallback, fallbackPollMs, fallbackBusy, availableModels, onFallbackChange, onFallbackPollMsChange, onFallbackSave, }: SubagentDelegationSectionProps) { const t = useT(); // A present empty/whitespace hint is an upstream override that suppresses the // Proactive message, so it must render as OFF (and the toggle can install the // preset). Only a nonblank hint is "on". const ultraOn = (ultraMode.hintText ?? "").trim().length > 0; + const routedPreferred = available.some(option => option.namespaced === model + && !(option.provider === "openai" && option.namespaced === option.model)); + const nativeMayUseV2 = ultraMode.enabled || (ultraMode.multiAgentMode !== "v1" + && !(ultraMode.multiAgentMode === "v2" && ultraMode.keepNativeChatGptOnV1)); + const showV2Compatibility = !ultraLoadFailed && ultraMode.loaded === true && routedPreferred && nativeMayUseV2; + const fallbackControlsRef = useRef(null); + const [identity, setIdentity] = useState(() => ({ + models: fallback, + rows: fallback.map((rowModel, id) => ({ model: rowModel, id })), + nextId: fallback.length, + })); + let rows = identity.rows; + // Keys are render state. Guarded prop reconciliation retains each occurrence; + // event handlers move the same identities with their corresponding models. + if (identity.models !== fallback) { + const remaining = [...identity.rows]; + let nextId = identity.nextId; + rows = fallback.map(modelName => { + const old = remaining.findIndex(row => row.model === modelName); + return old >= 0 ? remaining.splice(old, 1)[0] : { model: modelName, id: nextId++ }; + }); + setIdentity({ models: fallback, rows, nextId }); + } + const pendingFocus = useRef<{ row: number; action: string } | null>(null); + useLayoutEffect(() => { + const target = pendingFocus.current; + if (!target) return; + pendingFocus.current = null; + const row = fallbackControlsRef.current?.querySelectorAll(".swi-fallback-row")[target.row]; + const enabledActions = row?.querySelectorAll("button[data-action]:not(:disabled)"); + const action = Array.from(enabledActions ?? []).find(button => button.dataset.action === target.action) + ?? row?.querySelector("button:not(:disabled)") + ?? fallbackControlsRef.current?.querySelector('button[role="combobox"]'); + action?.focus(); + }, [fallback]); + const validPollMs = Number.isInteger(fallbackPollMs) && fallbackPollMs >= 5000 && fallbackPollMs <= 600000; + const moveFallback = (index: number, direction: -1 | 1) => { + const next = [...fallback]; + const target = index + direction; + if (fallbackBusy || target < 0 || target >= next.length) return; + [next[index], next[target]] = [next[target], next[index]]; + const nextRows = [...rows]; + [nextRows[index], nextRows[target]] = [nextRows[target], nextRows[index]]; + setIdentity({ ...identity, models: next, rows: nextRows }); + pendingFocus.current = { row: target, action: direction === -1 ? "up" : "down" }; + onFallbackChange(next); + }; return (
@@ -97,6 +152,52 @@ export default function SubagentDelegationSection({
+ {showV2Compatibility && ( +
+
+
{t("sub.v2Compatibility.title")}
+

{t("sub.v2Compatibility.risk")}

+

{t("sub.v2Compatibility.recoveryUnknown")}

+ {t("sub.v2Compatibility.details")} +
+
+ )} + +
+
+
{t("sub.fallbackLabel")}
+
{t("sub.fallbackHint")}
+
+
+ {fallback.map((modelName, index) => ( +
+ {index + 1}. {modelName} + {!availableModels.includes(modelName) && {t("sub.fallbackUnavailable")}} + + + + + + +
+ ))} + onFallbackPollMsChange(Number(e.target.value))} disabled={fallbackBusy} aria-invalid={!validPollMs} /> ms + + {!validPollMs &&
{t("sub.fallbackPollInvalid")}
} + +
+
+
{t("dash.syncCodexSubagentDefaults")}
diff --git a/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx b/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx index a22bd2a305..30b722b2bf 100644 --- a/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx +++ b/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx @@ -37,6 +37,12 @@ export interface SubagentsWorkspaceProps { onToggle: (m: string) => void; onMove: (i: number, dir: -1 | 1) => void; onSave: () => void; + fallback: string[]; + fallbackPollMs: number; + fallbackBusy: boolean; + onFallbackChange: (models: string[]) => void; + onFallbackPollMsChange: (pollMs: number) => void; + onFallbackSave: () => void; delegation: { model: string; effort: string; @@ -63,6 +69,7 @@ export default function SubagentsWorkspace({ onToggle, onMove, onSave, + fallback, fallbackPollMs, fallbackBusy, onFallbackChange, onFallbackPollMsChange, onFallbackSave, delegation, }: SubagentsWorkspaceProps) { const t = useT(); @@ -237,6 +244,13 @@ export default function SubagentsWorkspace({ onUltraModeSave={delegation.onUltraModeSave} ultraLoadFailed={delegation.ultraLoadFailed} onUltraModeRetry={delegation.onUltraModeRetry} + fallback={fallback} + fallbackPollMs={fallbackPollMs} + fallbackBusy={fallbackBusy} + availableModels={available} + onFallbackChange={onFallbackChange} + onFallbackPollMsChange={onFallbackPollMsChange} + onFallbackSave={onFallbackSave} />
diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 5faab4b356..4145cb8032 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -2408,6 +2408,18 @@ export const de: Record = { "sub.sections": "Subagent-Abschnitte", "sub.delegation.model": "Zuerst aufgerufenes Modell", "sub.delegation.modelHint": "Das Modell, zu dem Codex zuerst greift, wenn es Arbeit übergibt. Oben steht, wen es überhaupt aufrufen darf; hier wählst du den Ersten davon.", + "sub.fallbackLabel": "Fallback-Kette für Sub-Agenten", + "sub.fallbackHint": "Geordnete Modelle, die versucht werden, wenn ein Sub-Agent-Modell nicht verfügbar ist oder fehlschlägt.", + "sub.fallbackAdd": "Fallback-Modell hinzufügen…", + "sub.fallbackPoll": "Intervall der Verfügbarkeitsprüfung", + "sub.fallbackSaved": "Fallback-Einstellungen für Sub-Agenten gespeichert.", + "sub.fallbackSaveFailed": "Fallback-Einstellungen konnten nicht gespeichert werden", + "sub.fallbackUnavailable": "Derzeit nicht gelistet; bleibt in der Kette.", + "sub.fallbackPollInvalid": "Eine ganze Zahl von 5000 bis 600000 ms eingeben.", + "sub.v2Compatibility.title": "V2-Kompatibilität nativer Eltern", + "sub.v2Compatibility.risk": "Delegiert ein nativer ChatGPT-Elternagent über V2 an dieses geroutete Modell, kann die Aufgabe verschlüsselt sein und vor der Ausführung scheitern. Lesbare Aufgaben gerouteter Eltern sind nicht betroffen.", + "sub.v2Compatibility.recoveryUnknown": "Dieser Server meldet weder Aktivierung noch Eignung der Wiederherstellung. V1/Klartext verwenden oder experimentelle V2-Wiederherstellung nur bei Eignung aktivieren. Sie kostet Kontingent und Latenz, hängt vom Backend ab und kann Wiedergabetreue verlieren; das Upstream-Protokoll bleibt unverändert.", + "sub.v2Compatibility.details": "Details zur Kompatibilität", "dash.syncModelsHint": "Schreibt Codex' Modellkatalog anhand deiner verbundenen Provider neu.", "dash.syncRun": "Jetzt synchronisieren", "lab.title": "Kompatibilitäts-Labor", @@ -2469,6 +2481,8 @@ export const de: Record = { "dash.visionTimeout": "Timeout", "dash.visionTimeoutInvalid": "Geben Sie eine ganze Zahl von {min} bis {max} Millisekunden ein.", "dash.visionAdvancedPopover": "Erweiterte Vision-Einstellungen", + "dash.codexDesktopAuthless": "Codex ohne Anmeldung öffnen", + "dash.codexDesktopAuthlessHint": "Standardmäßig aus. Überspringt die separate Desktop-Anmeldung bei geeigneten lokalen Verbindungen. Zugangsdaten für den Anbieter bleiben erforderlich. Codex nach einer Änderung neu starten. Kontogebundene Desktop-Funktionen können fehlen.", "models.newPolicyGlobal": "Neue Modelle zunächst deaktivieren", "models.newPolicyProvider": "Richtlinie für neue Modelle", "models.newPolicy_inherit": "Übernehmen", "models.newPolicy_off": "Aus", "models.newPolicy_on": "An", "models.newBadge": "NEU", "models.newCount": "{count} neu, aus", "models.aliases": "Aliase", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index c71208942f..2a31ec7947 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -575,6 +575,8 @@ export const en = { "models.keepNativeOnV1Hint": "ChatGPT encrypts v2 child tasks only when a ChatGPT-native parent stays on v2, so Grok and Claude cannot read them. Turn this on to keep Sol/Terra on v1 and avoid that encryption. Routed parents keep v2.", "models.v2Help": "Controls the multi-agent surface for all models.\n\nv1: Classic single-thread agent. Every model uses the v1 collab surface.\nbase: Upstream defaults — sol/terra use v2, luna uses v1, others follow the codex feature flag.\nv2: Multi-thread agent with spawn_agent. Every model uses the v2 collab surface.\n\nOn v2, Keep ChatGPT on v1 leaves Sol/Terra on the v1 surface so they can still spawn Grok or Claude. ChatGPT encrypts v2 child tasks; routed models cannot read them. Routed parents stay on v2.\n\nChanges apply to new sessions.", "dash.multiAgent": "Sub-agent", + "dash.codexDesktopAuthless": "Open Codex without signing in", + "dash.codexDesktopAuthlessHint": "Off by default. Skip the separate Desktop sign-in for eligible local connections. Upstream credentials are still required. Restart Codex after changing this setting. Account-gated Desktop features may be unavailable.", "models.v2Conflict": "[agents] max_threads is set — codex will refuse to start; remove it from config.toml", "models.v2Applied": "Sub-agent mode updated — applies to new sessions (restart the Codex app to refresh the picker)", "models.v2ThreadsLabel": "Max threads", @@ -717,6 +719,18 @@ export const en = { "sub.workspace.selectModel": "Select a model", "sub.workspace.selectModelDesc": "Pick a model from the list to see details and feature it for spawn_agent.", "sub.workspace.selector": "Public selector", + "sub.fallbackLabel": "Sub-agent fallback chain", + "sub.fallbackHint": "Ordered models tried when a sub-agent model is unavailable or fails.", + "sub.fallbackAdd": "Add fallback model…", + "sub.fallbackPoll": "Availability check interval", + "sub.fallbackSaved": "Sub-agent fallback settings saved.", + "sub.fallbackSaveFailed": "Failed to save fallback settings", + "sub.fallbackUnavailable": "Not currently advertised; kept in the chain.", + "sub.fallbackPollInvalid": "Enter an integer from 5000 to 600000 ms.", + "sub.v2Compatibility.title": "Native-parent V2 compatibility", + "sub.v2Compatibility.risk": "If a native ChatGPT parent delegates to this routed model using V2, its task may be encrypted and fail before execution. Readable tasks from routed parents are unaffected.", + "sub.v2Compatibility.recoveryUnknown": "Recovery enabled/eligibility state is not exposed by this server. Use V1/plaintext-compatible delegation, or enable experimental V2 recovery only if eligible. Recovery adds quota, latency, backend dependence and possible fidelity loss; it does not fix the upstream protocol.", + "sub.v2Compatibility.details": "Compatibility details", // logs "logs.title": "Request Logs", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index e1b3519ef1..753982c1bf 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -560,6 +560,8 @@ export const fr: Record = { "models.keepNativeOnV1Hint": "ChatGPT chiffre les tâches enfants v2 uniquement lorsqu’un parent natif ChatGPT reste sur v2, de sorte que Grok et Claude ne peuvent pas les lire. Activez cette option pour garder Sol/Terra sur v1 et éviter ce chiffrement. Les parents routés restent sur v2.", "models.v2Help": "Contrôle l’interface multi-agent pour tous les modèles.\n\nv1 : agent classique à fil unique. Tous les modèles utilisent l’interface collab v1.\nbase : valeurs par défaut en amont — sol/terra utilisent v2, luna utilise v1 et les autres suivent l’indicateur de fonctionnalité codex.\nv2 : agent multifil avec spawn_agent. Tous les modèles utilisent l’interface collab v2.\n\nEn v2, « Garder ChatGPT sur v1 » laisse Sol/Terra sur l’interface v1 afin qu’ils puissent encore lancer Grok ou Claude. ChatGPT chiffre les tâches enfants v2 ; les modèles routés ne peuvent pas les lire. Les parents routés restent sur v2.\n\nLes modifications s’appliquent aux nouvelles sessions.", "dash.multiAgent": "Sous-agent", + "dash.codexDesktopAuthless": "Ouvrir Codex sans se connecter", + "dash.codexDesktopAuthlessHint": "Désactivé par défaut. Ignore la connexion Desktop séparée pour les connexions locales admissibles. Les identifiants du fournisseur restent nécessaires. Redémarrez Codex après toute modification. Certaines fonctions Desktop liées au compte peuvent être indisponibles.", "models.v2Conflict": "[agents] max_threads est défini — codex refusera de démarrer ; supprimez-le de config.toml", "models.v2Applied": "Mode sous-agent mis à jour — s’applique aux nouvelles sessions (redémarrez l’application Codex pour actualiser le sélecteur)", "models.v2ThreadsLabel": "Nombre maximal de fils", @@ -700,6 +702,18 @@ export const fr: Record = { "sub.workspace.selectModel": "Sélectionner un modèle", "sub.workspace.selectModelDesc": "Choisissez un modèle dans la liste pour afficher ses détails et le mettre à la une pour spawn_agent.", "sub.workspace.selector": "Sélecteur public", + "sub.fallbackLabel": "Chaîne de secours des sous-agents", + "sub.fallbackHint": "Modèles essayés dans l’ordre lorsqu’un modèle de sous-agent est indisponible ou échoue.", + "sub.fallbackAdd": "Ajouter un modèle de secours…", + "sub.fallbackPoll": "Intervalle de vérification de disponibilité", + "sub.fallbackSaved": "Paramètres de secours des sous-agents enregistrés.", + "sub.fallbackSaveFailed": "Échec de l’enregistrement des paramètres de secours", + "sub.fallbackUnavailable": "Absent du catalogue actuel ; conservé dans la chaîne.", + "sub.fallbackPollInvalid": "Saisissez un entier de 5000 à 600000 ms.", + "sub.v2Compatibility.title": "Compatibilité V2 du parent natif", + "sub.v2Compatibility.risk": "Si un parent ChatGPT natif délègue à ce modèle routé via V2, la tâche peut être chiffrée et échouer avant son exécution. Les tâches lisibles des parents routés ne sont pas affectées.", + "sub.v2Compatibility.recoveryUnknown": "Ce serveur ne fournit pas l’activation ni l’éligibilité de la récupération. Utilisez V1/texte clair, ou activez la récupération V2 expérimentale uniquement si éligible. Elle ajoute quota, latence, dépendance au backend et risque de perte de fidélité ; elle ne corrige pas le protocole amont.", + "sub.v2Compatibility.details": "Détails de compatibilité", "logs.title": "Journaux des requêtes", "logs.tabLogs": "Journaux", "logs.tabDebug": "Débogage", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index cf94831583..300d1f8c51 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -2429,6 +2429,18 @@ export const ja: Record = { "sub.sections": "サブエージェントのセクション", "sub.delegation.model": "最初に呼ぶモデル", "sub.delegation.modelHint": "Codex が作業を任せるとき、最初に呼ぶモデルです。上のおすすめが呼べる候補で、ここで選んだものがその中の第一候補になります。", + "sub.fallbackLabel": "サブエージェントのフォールバックチェーン", + "sub.fallbackHint": "サブエージェントモデルが利用できないか失敗した場合に順番に試すモデルです。", + "sub.fallbackAdd": "フォールバックモデルを追加…", + "sub.fallbackPoll": "利用可能性チェック間隔", + "sub.fallbackSaved": "サブエージェントのフォールバック設定を保存しました。", + "sub.fallbackSaveFailed": "フォールバック設定の保存に失敗しました", + "sub.fallbackUnavailable": "現在の一覧にはありませんが、チェーンに保持されます。", + "sub.fallbackPollInvalid": "5000〜600000 ms の整数を入力してください。", + "sub.v2Compatibility.title": "ネイティブ親の V2 互換性", + "sub.v2Compatibility.risk": "ネイティブ ChatGPT 親が V2 でこのルーティングモデルに委任すると、タスクが暗号化され実行前に失敗する場合があります。ルーティング親からの読み取り可能なタスクは影響を受けません。", + "sub.v2Compatibility.recoveryUnknown": "このサーバーは復旧の有効状態や適格性を公開していません。V1・平文互換の委任を使うか、適格な場合のみ実験的 V2 復旧を有効にしてください。復旧にはクォータ、遅延、バックエンド依存、忠実度低下の可能性があり、上流プロトコルは修正されません。", + "sub.v2Compatibility.details": "互換性の詳細", "dash.syncModelsHint": "接続済みのプロバイダーをもとに Codex のモデルカタログを書き直します。", "dash.syncRun": "今すぐ同期", "lab.title": "Compatibility Lab", @@ -2490,6 +2502,8 @@ export const ja: Record = { "dash.visionTimeout": "タイムアウト", "dash.visionTimeoutInvalid": "{min} から {max} ミリ秒の整数を入力してください。", "dash.visionAdvancedPopover": "詳細なビジョン設定", + "dash.codexDesktopAuthless": "ログインせずに Codex を開く", + "dash.codexDesktopAuthlessHint": "既定ではオフです。対象のローカル接続で Desktop の個別ログインを省略します。上流プロバイダーの認証情報は引き続き必要です。変更後は Codex を再起動してください。アカウントに依存する Desktop 機能が利用できない場合があります。", "models.newPolicyGlobal": "新しいモデルを無効で追加", "models.newPolicyProvider": "新しいモデルのポリシー", "models.newPolicy_inherit": "継承", "models.newPolicy_off": "オフ", "models.newPolicy_on": "オン", "models.newBadge": "新着", "models.newCount": "新着 {count} 件、オフ", "models.aliases": "エイリアス", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index c1959482b7..42c000c6bb 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -703,6 +703,18 @@ export const ko: Record = { "sub.ultraModeLoadFail": "울트라 모드 설정을 불러오지 못했습니다 — 프록시가 실행 중인가요?", "sub.ultraModeSaveFail": "울트라 모드 설정 저장에 실패했습니다", "sub.ultraModeSaved": "울트라 모드가 저장되었습니다. 새 Codex 세션부터 적용됩니다.", + "sub.fallbackLabel": "서브에이전트 폴백 체인", + "sub.fallbackHint": "서브에이전트 모델을 사용할 수 없거나 실패할 때 순서대로 시도할 모델입니다.", + "sub.fallbackAdd": "폴백 모델 추가…", + "sub.fallbackPoll": "가용성 확인 간격", + "sub.fallbackSaved": "서브에이전트 폴백 설정을 저장했습니다.", + "sub.fallbackSaveFailed": "폴백 설정을 저장하지 못했습니다", + "sub.fallbackUnavailable": "현재 목록에 없지만 체인에 유지됩니다.", + "sub.fallbackPollInvalid": "5000~600000ms 범위의 정수를 입력하세요.", + "sub.v2Compatibility.title": "네이티브 부모의 V2 호환성", + "sub.v2Compatibility.risk": "네이티브 ChatGPT 부모가 V2로 이 라우팅 모델에 위임하면 작업이 암호화되어 실행 전에 실패할 수 있습니다. 라우팅 부모가 보내는 읽을 수 있는 작업에는 영향이 없습니다.", + "sub.v2Compatibility.recoveryUnknown": "이 서버는 복구 활성화 여부와 사용 가능 상태를 제공하지 않습니다. V1·평문 호환 위임을 사용하거나, 조건을 충족할 때만 실험적 V2 복구를 켜세요. 복구에는 할당량·지연·백엔드 의존성과 원문 충실도 손실 가능성이 따르며, 업스트림 프로토콜을 고치지는 않습니다.", + "sub.v2Compatibility.details": "호환성 자세히 보기", // logs "logs.title": "요청 로그", @@ -2491,6 +2503,8 @@ export const ko: Record = { "dash.visionTimeout": "제한 시간", "dash.visionTimeoutInvalid": "{min}에서 {max} 밀리초 사이의 정수를 입력하세요.", "dash.visionAdvancedPopover": "고급 비전 설정", + "dash.codexDesktopAuthless": "로그인 없이 Codex 열기", + "dash.codexDesktopAuthlessHint": "기본값은 꺼짐입니다. 지원되는 로컬 연결에서 별도의 Desktop 로그인을 건너뜁니다. 업스트림 인증 정보는 여전히 필요합니다. 변경 후 Codex를 다시 시작하세요. 계정에 연결된 Desktop 기능을 사용하지 못할 수 있습니다.", "models.newPolicyGlobal": "새 모델을 비활성화 상태로 추가", "models.newPolicyProvider": "새 모델 정책", "models.newPolicy_inherit": "상속", "models.newPolicy_off": "끔", "models.newPolicy_on": "켬", "models.newBadge": "신규", "models.newCount": "신규 {count}개, 꺼짐", "models.aliases": "별칭", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 0109f5ebdc..51fcaef210 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -2431,6 +2431,18 @@ export const ru: Record = { "sub.sections": "Разделы подагентов", "sub.delegation.model": "Модель, которую вызывать первой", "sub.delegation.modelHint": "Модель, к которой Codex обращается первой, когда передаёт работу. Список выше — кого он вообще может вызвать, а здесь выбирается первый в очереди.", + "sub.fallbackLabel": "Цепочка резервных моделей субагента", + "sub.fallbackHint": "Модели, которые последовательно пробуются, если модель субагента недоступна или завершается ошибкой.", + "sub.fallbackAdd": "Добавить резервную модель…", + "sub.fallbackPoll": "Интервал проверки доступности", + "sub.fallbackSaved": "Настройки резервных моделей субагента сохранены.", + "sub.fallbackSaveFailed": "Не удалось сохранить настройки резервных моделей", + "sub.fallbackUnavailable": "Сейчас отсутствует в каталоге; сохранена в цепочке.", + "sub.fallbackPollInvalid": "Введите целое число от 5000 до 600000 мс.", + "sub.v2Compatibility.title": "Совместимость V2 с нативным родителем", + "sub.v2Compatibility.risk": "Если нативный родитель ChatGPT делегирует этой маршрутизируемой модели через V2, задача может быть зашифрована и завершиться ошибкой до выполнения. Читаемые задачи маршрутизируемых родителей не затрагиваются.", + "sub.v2Compatibility.recoveryUnknown": "Сервер не сообщает, включено ли восстановление и доступно ли оно. Используйте V1/открытый текст или включите экспериментальное восстановление V2 только при соответствии условиям. Оно расходует квоту, увеличивает задержку, зависит от бэкенда и может снизить точность; исходный протокол не исправляется.", + "sub.v2Compatibility.details": "Подробнее о совместимости", "dash.syncModelsHint": "Перезаписывает каталог моделей Codex по подключённым провайдерам.", "dash.syncRun": "Синхронизировать", "lab.title": "Compatibility Lab", @@ -2492,6 +2504,8 @@ export const ru: Record = { "dash.visionTimeout": "Таймаут", "dash.visionTimeoutInvalid": "Введите целое число от {min} до {max} миллисекунд.", "dash.visionAdvancedPopover": "Дополнительные настройки изображений", + "dash.codexDesktopAuthless": "Открывать Codex без входа", + "dash.codexDesktopAuthlessHint": "По умолчанию выключено. Пропускает отдельный вход в Desktop для допустимых локальных подключений. Учётные данные провайдера по-прежнему нужны. После изменения перезапустите Codex. Функции Desktop, связанные с аккаунтом, могут быть недоступны.", "models.newPolicyGlobal": "Добавлять новые модели выключенными", "models.newPolicyProvider": "Политика новых моделей", "models.newPolicy_inherit": "Наследовать", "models.newPolicy_off": "Выкл.", "models.newPolicy_on": "Вкл.", "models.newBadge": "НОВАЯ", "models.newCount": "Новых: {count}, выкл.", "models.aliases": "Псевдонимы", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index fa8b8e9c25..c764bf11ca 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -708,6 +708,18 @@ export const tr: Record = { "sub.ultraModeLoadFail": "Ultra modu ayarları yüklenemedi — proxy çalışıyor mu?", "sub.ultraModeSaveFail": "Ultra modu ayarları kaydedilemedi", "sub.ultraModeSaved": "Ultra modu kaydedildi. Yeni Codex oturumlarına uygulanır.", + "sub.fallbackLabel": "Alt ajan yedek zinciri", + "sub.fallbackHint": "Alt ajan modeli kullanılamadığında veya başarısız olduğunda sırayla denenecek modeller.", + "sub.fallbackAdd": "Yedek model ekle…", + "sub.fallbackPoll": "Kullanılabilirlik kontrol aralığı", + "sub.fallbackSaved": "Alt ajan yedek ayarları kaydedildi.", + "sub.fallbackSaveFailed": "Yedek ayarlar kaydedilemedi", + "sub.fallbackUnavailable": "Şu anda listelenmiyor; zincirde korunur.", + "sub.fallbackPollInvalid": "5000–600000 ms arasında bir tam sayı girin.", + "sub.v2Compatibility.title": "Yerel üst ajanın V2 uyumluluğu", + "sub.v2Compatibility.risk": "Yerel ChatGPT üst ajanı V2 ile bu yönlendirilmiş modele görev verirse görev şifrelenmiş olabilir ve yürütülmeden başarısız olabilir. Yönlendirilmiş üst ajanların okunabilir görevleri etkilenmez.", + "sub.v2Compatibility.recoveryUnknown": "Bu sunucu kurtarmanın etkinliğini veya uygunluğunu bildirmez. V1/düz metin kullanın ya da deneysel V2 kurtarmayı yalnızca uygunsa açın. Kurtarma kota, gecikme, arka uç bağımlılığı ve aslına uygunluk kaybı getirebilir; üst sistem protokolünü düzeltmez.", + "sub.v2Compatibility.details": "Uyumluluk ayrıntıları", // logs "logs.title": "İstek Günlükleri", @@ -2492,6 +2504,8 @@ export const tr: Record = { "dash.visionTimeout": "Zaman aşımı", "dash.visionTimeoutInvalid": "{min} ile {max} milisaniye arasında bir tam sayı girin.", "dash.visionAdvancedPopover": "Gelişmiş görsel ayarları", + "dash.codexDesktopAuthless": "Codex’i oturum açmadan başlat", + "dash.codexDesktopAuthlessHint": "Varsayılan olarak kapalıdır. Uygun yerel bağlantılarda ayrı Desktop oturum açma adımını atlar. Sağlayıcı kimlik bilgileri yine gereklidir. Değişiklikten sonra Codex’i yeniden başlatın. Hesaba bağlı Desktop özellikleri kullanılamayabilir.", "models.newPolicyGlobal": "Yeni modeller devre dışı başlasın", "models.newPolicyProvider": "Yeni model ilkesi", "models.newPolicy_inherit": "Devral", "models.newPolicy_off": "Kapalı", "models.newPolicy_on": "Açık", "models.newBadge": "YENİ", "models.newCount": "{count} yeni, kapalı", "models.aliases": "Takma adlar", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 3bc246543a..ab6aedd67a 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -1966,6 +1966,18 @@ export const zhTW: Record = { "sub.sections": "子代理分區", "sub.delegation.model": "優先調用的模型", "sub.delegation.modelHint": "Codex 分派工作時最先調用的模型。上面的推薦是可調用的名單,這裡選的是其中第一順位。", + "sub.fallbackLabel": "子代理備援鏈", + "sub.fallbackHint": "子代理模型無法使用或失敗時,依序嘗試的模型。", + "sub.fallbackAdd": "新增備援模型…", + "sub.fallbackPoll": "可用性檢查間隔", + "sub.fallbackSaved": "子代理備援設定已儲存。", + "sub.fallbackSaveFailed": "備援設定儲存失敗", + "sub.fallbackUnavailable": "目前未列出,仍保留在回退鏈中。", + "sub.fallbackPollInvalid": "請輸入 5000 到 600000 ms 之間的整數。", + "sub.v2Compatibility.title": "原生父代理的 V2 相容性", + "sub.v2Compatibility.risk": "原生 ChatGPT 父代理透過 V2 委派給此路由模型時,任務可能被加密並在執行前失敗。路由父代理傳送的可讀任務不受影響。", + "sub.v2Compatibility.recoveryUnknown": "此伺服器未提供復原功能的啟用或適用狀態。請使用 V1/明文相容委派,或僅在符合條件時啟用實驗性 V2 復原。復原會增加配額消耗、延遲、後端依賴及保真度損失風險,並不修復上游協定。", + "sub.v2Compatibility.details": "相容性詳情", "debug.loadFailed": "無法載入偵錯設定。", "provider.name.volcengine": "Volcengine Ark", "provider.name.volcengineCodingPlan": "Volcengine Ark Coding Plan", @@ -2454,6 +2466,8 @@ export const zhTW: Record = { "dash.visionTimeout": "逾時", "dash.visionTimeoutInvalid": "請輸入 {min} 到 {max} 毫秒之間的整數。", "dash.visionAdvancedPopover": "進階視覺設定", + "dash.codexDesktopAuthless": "無需登入即可開啟 Codex", + "dash.codexDesktopAuthlessHint": "預設關閉。為符合條件的本機連線略過獨立的 Desktop 登入。仍需上游供應商憑證。變更後請重新啟動 Codex。依賴帳戶的 Desktop 功能可能無法使用。", "models.newPolicyGlobal": "新模型預設停用", "models.newPolicyProvider": "新模型策略", "models.newPolicy_inherit": "繼承", "models.newPolicy_off": "關閉", "models.newPolicy_on": "開啟", "models.newBadge": "新增", "models.newCount": "{count} 個新增,已關閉", "models.aliases": "別名", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index b10c48688d..052f449855 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -2429,6 +2429,18 @@ export const zh: Record = { "sub.sections": "子代理分区", "sub.delegation.model": "优先调用的模型", "sub.delegation.modelHint": "Codex 分派工作时最先调用的模型。上面的推荐是可调用的名单,这里选的是其中第一顺位。", + "sub.fallbackLabel": "子代理回退链", + "sub.fallbackHint": "子代理模型不可用或失败时按顺序尝试的模型。", + "sub.fallbackAdd": "添加回退模型…", + "sub.fallbackPoll": "可用性检查间隔", + "sub.fallbackSaved": "子代理回退设置已保存。", + "sub.fallbackSaveFailed": "保存回退设置失败", + "sub.fallbackUnavailable": "当前未列出,仍保留在回退链中。", + "sub.fallbackPollInvalid": "请输入 5000 到 600000 ms 之间的整数。", + "sub.v2Compatibility.title": "原生父代理的 V2 兼容性", + "sub.v2Compatibility.risk": "原生 ChatGPT 父代理通过 V2 委派给此路由模型时,任务可能被加密并在执行前失败。路由父代理发送的可读任务不受影响。", + "sub.v2Compatibility.recoveryUnknown": "此服务器未提供恢复功能的启用或适用状态。请使用 V1/明文兼容委派,或仅在符合条件时启用实验性 V2 恢复。恢复会增加配额消耗、延迟、后端依赖及保真度损失风险,并不修复上游协议。", + "sub.v2Compatibility.details": "兼容性详情", "dash.syncModelsHint": "按已连接的提供商重写 Codex 的模型目录。", "dash.syncRun": "立即同步", "lab.title": "Compatibility Lab", @@ -2490,6 +2502,8 @@ export const zh: Record = { "dash.visionTimeout": "超时", "dash.visionTimeoutInvalid": "请输入 {min} 到 {max} 毫秒之间的整数。", "dash.visionAdvancedPopover": "高级视觉设置", + "dash.codexDesktopAuthless": "无需登录即可打开 Codex", + "dash.codexDesktopAuthlessHint": "默认关闭。为符合条件的本地连接跳过单独的 Desktop 登录。仍需上游提供商凭据。更改后请重启 Codex。依赖账户的 Desktop 功能可能不可用。", "models.newPolicyGlobal": "新模型默认停用", "models.newPolicyProvider": "新模型策略", "models.newPolicy_inherit": "继承", "models.newPolicy_off": "关闭", "models.newPolicy_on": "开启", "models.newBadge": "新增", "models.newCount": "{count} 个新增,已关闭", "models.aliases": "别名", diff --git a/gui/src/pages/Subagents.tsx b/gui/src/pages/Subagents.tsx index 6b54d39ffd..cf9f1b33d0 100644 --- a/gui/src/pages/Subagents.tsx +++ b/gui/src/pages/Subagents.tsx @@ -8,7 +8,7 @@ import { useDataSurface } from "../data-surface"; import { DataSurfaceSkeleton } from "../components/data-surface"; import { useSubagentDelegation, type UltraModePatch, type UltraModeState } from "./use-subagent-delegation"; -type CachedSubagents = { available: string[]; chosen: string[] }; +type CachedSubagents = { available: string[]; chosen: string[]; fallback?: string[]; pollMs?: number }; function seedSubagents(cacheKey: string): CachedSubagents | null { return readSessionListCache(cacheKey); @@ -19,6 +19,14 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const cacheKey = `ocx.subagents.v1:${apiBase}`; const cached = seedSubagents(cacheKey); const [chosen, setChosen] = useState(() => cached?.chosen ?? []); + const [fallback, setFallback] = useState(() => cached?.fallback ?? []); + const [fallbackPollMs, setFallbackPollMs] = useState(() => cached?.pollMs ?? 60000); + const [fallbackBusy, setFallbackBusy] = useState(false); + const [fallbackLoaded, setFallbackLoaded] = useState(() => Array.isArray(cached?.fallback) && Number.isInteger(cached?.pollMs)); + const fallbackRevision = useRef(0); + const rosterRevision = useRef(0); + const fallbackSaveInFlight = useRef(false); + const committed = useRef(cached); const [status, setStatus] = useState(""); const [ok, setOk] = useState(false); const [busy, setBusy] = useState(false); @@ -46,12 +54,15 @@ export default function Subagents({ apiBase }: { apiBase: string }) { enabled?: boolean; multiAgentMode?: "v1" | "default" | "v2"; multiAgentModeHintText?: string | null; + keepNativeChatGptOnV1?: boolean; }>(res, t("sub.ultraModeLoadFail")); if (!data) return false; if (signal?.aborted || generation !== ultraLoadGeneration.current || currentUltraApiBase.current !== apiBase) return false; setUltraLoadFailed(false); setUltraMode({ enabled: data.enabled ?? false, + loaded: true, + keepNativeChatGptOnV1: data.keepNativeChatGptOnV1 === true, hintText: data.multiAgentModeHintText ?? null, // Ultra mode replaces Codex's effort-derived policy for every model. The // `default` surface still preserves upstream V1 pins (for example luna), @@ -117,16 +128,34 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const loadSubagents = useCallback(async (signal?: AbortSignal): Promise => { // The resource layer's deadline abort must reach the wire — a signal dropped // here is a store that can only settle by race timeout. - const res = await fetch(`${apiBase}/api/subagent-models`, { signal }); - const response = await readJsonOrThrow<{ available?: string[]; chosen?: string[] }>(res, t("sub.loadFail")); - if (!response) throw new Error(t("sub.loadFail")); - const available = response.available ?? []; + const rosterReadRevision = rosterRevision.current; + const fallbackReadRevision = fallbackRevision.current; + const [rosterRes, fallbackRes] = await Promise.all([ + fetch(`${apiBase}/api/subagent-models`, { signal }), + fetch(`${apiBase}/api/subagent-model-fallback`, { signal }), + ]); + const response = await readJsonOrThrow<{ available?: string[]; chosen?: string[] }>(rosterRes, t("sub.loadFail")); + const fallbackResponse = await readJsonOrThrow<{ available?: string[]; models?: string[]; pollMs?: number }>(fallbackRes, t("sub.loadFail")); + if (!response || !fallbackResponse) throw new Error(t("sub.loadFail")); + const available = response.available ?? fallbackResponse.available ?? []; const availableSet = new Set(available); + const rosterCurrent = rosterReadRevision === rosterRevision.current && !saveInFlight.current; + const fallbackCurrent = fallbackReadRevision === fallbackRevision.current && !fallbackSaveInFlight.current; const next = { available, - chosen: (response.chosen ?? []).filter(model => availableSet.has(model)), + chosen: rosterCurrent ? (response.chosen ?? []).filter(model => availableSet.has(model)) : committed.current?.chosen ?? [], + // Configured targets remain editable even when discovery no longer advertises them. + fallback: fallbackCurrent ? fallbackResponse.models ?? [] : committed.current?.fallback ?? [], + pollMs: fallbackCurrent ? fallbackResponse.pollMs ?? 60000 : committed.current?.pollMs ?? 60000, }; - setChosen(next.chosen); + if (signal?.aborted) throw signal.reason; + committed.current = next; + if (rosterCurrent) setChosen(next.chosen); + if (fallbackCurrent) { + setFallback(next.fallback); + setFallbackPollMs(next.pollMs); + setFallbackLoaded(true); + } writeSessionListCache(cacheKey, next); return next; }, [apiBase, cacheKey, t]); @@ -147,10 +176,12 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const toggle = (m: string) => { if (busy) return; setStatus(""); + rosterRevision.current += 1; setChosen(prev => prev.includes(m) ? prev.filter(x => x !== m) : (prev.length >= FEATURED_MAX ? prev : [...prev, m])); }; const move = (i: number, dir: -1 | 1) => { if (busy) return; + rosterRevision.current += 1; setChosen(prev => { const next = [...prev]; const j = i + dir; @@ -163,6 +194,7 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const save = async () => { if (busy || saveInFlight.current) return; saveInFlight.current = true; + rosterRevision.current += 1; setBusy(true); setStatus(""); try { @@ -172,9 +204,13 @@ export default function Subagents({ apiBase }: { apiBase: string }) { body: JSON.stringify({ models: chosen }), }); const d = await readJsonOrThrow<{ applied?: string[] }>(r, t("sub.saveFailed")); + rosterRevision.current += 1; const applied = d?.applied ?? chosen; if (d?.applied) setChosen(d.applied); - writeSessionListCache(cacheKey, { available, chosen: applied }); + // A legacy roster-only seed does not prove that an empty fallback was loaded. + const next = { ...committed.current, available, chosen: applied }; + committed.current = next; + writeSessionListCache(cacheKey, next); setOk(true); setStatus(t("sub.saved", { n: applied.length, cmd: "ocx sync" })); } catch (error) { @@ -186,6 +222,39 @@ export default function Subagents({ apiBase }: { apiBase: string }) { } }; + const saveFallback = async () => { + if (!fallbackLoaded || fallbackSaveInFlight.current || !Number.isInteger(fallbackPollMs) || fallbackPollMs < 5000 || fallbackPollMs > 600000) return; + fallbackSaveInFlight.current = true; + fallbackRevision.current += 1; + const requestApiBase = apiBase; + setFallbackBusy(true); + setStatus(""); + try { + const r = await fetch(`${apiBase}/api/subagent-model-fallback`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ models: fallback, pollMs: fallbackPollMs }), + }); + const d = await readJsonOrThrow<{ models?: string[]; pollMs?: number }>(r, t("sub.fallbackSaveFailed")); + if (currentUltraApiBase.current !== requestApiBase) return; + if (!d || !Array.isArray(d.models) || typeof d.pollMs !== "number") throw new Error(t("sub.fallbackSaveFailed")); + fallbackRevision.current += 1; + setFallback(d.models); + setFallbackPollMs(d.pollMs); + const next = { available, chosen: committed.current?.chosen ?? [], fallback: d.models, pollMs: d.pollMs }; + committed.current = next; + writeSessionListCache(cacheKey, next); + setOk(true); + setStatus(t("sub.fallbackSaved")); + } catch (error) { + setOk(false); + setStatus(error instanceof Error && error.message ? error.message : t("sub.networkError")); + } finally { + fallbackSaveInFlight.current = false; + setFallbackBusy(false); + } + }; + // The skeleton owns the live region while this resource has no content yet. if (state.showSkeleton && !snapshot) { return ; @@ -208,13 +277,20 @@ export default function Subagents({ apiBase }: { apiBase: string }) {
{status && {status}} {state.showError && {t("sub.loadFail")}} + {!fallbackLoaded && state.showError && } { void save(); }} + onSave={() => { void save(); }} + fallback={fallback} + fallbackPollMs={fallbackPollMs} + fallbackBusy={fallbackBusy || !fallbackLoaded} + onFallbackChange={models => { fallbackRevision.current += 1; setFallback(models); }} + onFallbackPollMsChange={pollMs => { fallbackRevision.current += 1; setFallbackPollMs(pollMs); }} + onFallbackSave={() => { void saveFallback(); }} delegation={{ model: delegation.model, effort: delegation.effort, diff --git a/gui/src/pages/dashboard-overview-sections.tsx b/gui/src/pages/dashboard-overview-sections.tsx index 8da531f97c..6606c4f560 100644 --- a/gui/src/pages/dashboard-overview-sections.tsx +++ b/gui/src/pages/dashboard-overview-sections.tsx @@ -163,7 +163,7 @@ export function DashboardInjectionPanel({ d }: { apiBase: string; d: Dash }) { export function DashboardMaintenancePanel({ d }: { d: Dash }) { const { - t, runSync, syncing, updateTriggerRef, openUpdateDialog, updateLoading, updateOpen, + t, runSync, syncing, settingsSaving, updateTriggerRef, openUpdateDialog, updateLoading, updateOpen, syncResult, syncError, updateJob, reconnecting, clearSyncFeedback, } = d; const syncHoldsWarning = !!syncResult && ( @@ -211,7 +211,7 @@ export function DashboardMaintenancePanel({ d }: { d: Dash }) {
{t("dash.syncModelsHint")}
-
+
+
+
+
{t("dash.codexDesktopAuthless")}
+
{t("dash.codexDesktopAuthlessHint")}
+ {settings?.catalogRefreshPending &&
{t("codexAuth.catalogRefreshPending")}
} +
+ +
+
+
{/* Both sidecar cards wear the DashboardInjectionPanel shell: the PANEL is the flex row, copy left, controls right. */} diff --git a/gui/src/pages/dashboard-shared.ts b/gui/src/pages/dashboard-shared.ts index 0793a7def2..b6914586b6 100644 --- a/gui/src/pages/dashboard-shared.ts +++ b/gui/src/pages/dashboard-shared.ts @@ -48,6 +48,8 @@ export interface ProviderInfo { name: string; adapter: string; baseUrl: string; export interface ModelInfo { id: string; provider: string; namespaced: string; owned_by?: string; reasoningEfforts?: string[] } export interface SettingsData { codexAutoStart: boolean; + codexDesktopAuthless?: boolean; + catalogRefreshPending?: boolean; /** Whether a login may open a browser on the machine running the proxy. */ oauthOpenBrowser?: boolean; port: number; @@ -126,6 +128,7 @@ export type Installer = "npm" | "bun" | "source"; export type UpdateJobStatus = "running" | "restarting" | "succeeded" | "failed"; export interface SyncResult { ok: boolean; + status?: "applied" | "skipped" | "catalog-only" | "refused"; added: number; catalogPath: string | null; catalogExists: boolean; diff --git a/gui/src/pages/use-dashboard-data.ts b/gui/src/pages/use-dashboard-data.ts index 6f84950ce1..8634e7caa8 100644 --- a/gui/src/pages/use-dashboard-data.ts +++ b/gui/src/pages/use-dashboard-data.ts @@ -361,7 +361,12 @@ export function useDashboardData(apiBase: string) { useEffect(() => { const data = settingsPoll.data; if (!data) return; - if (data.settings !== undefined) setSettings(data.settings); + if (data.settings !== undefined) { + const next = data.settings; + // GET settings does not report application receipts. Keep a saved preference's + // pending indication until an affirmative sync result clears it. + setSettings(prev => ({ ...next, catalogRefreshPending: prev?.catalogRefreshPending === true || next.catalogRefreshPending })); + } // Latest-wins: only seed from settings when no newer dedicated probe has committed // while this settings poll was in flight. Always merge against the live ref. if ( @@ -607,23 +612,24 @@ export function useDashboardData(apiBase: string) { finally { setInjectionSaving(false); } }; - const toggleCodexAutoStart = async () => { - if (!settings || settingsSaving) return; - const next = !settings.codexAutoStart; + const toggleCodexSetting = async (key: "codexAutoStart" | "codexDesktopAuthless") => { + if (!settings || settingsSaving || syncing) return; + const next = !(settings[key] ?? (key === "codexAutoStart")); setSettingsSaving(true); settingsMutationInFlightRef.current = true; - setSettings({ ...settings, codexAutoStart: next }); + setSettings({ ...settings, [key]: next }); try { const res = await fetch(`${apiBase}/api/settings`, { method: "PUT", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ codexAutoStart: next }), + body: JSON.stringify({ [key]: next }), }); - const data = await requireJson<{ codexAutoStart: boolean; startupHealth?: SettingsData["startupHealth"] }>(res, "save failed"); + const data = await requireJson(res, "save failed"); settingsMutationEpochRef.current += 1; - setSettings(prev => prev ? { ...prev, codexAutoStart: data.codexAutoStart, startupHealth: data.startupHealth ?? prev.startupHealth } : prev); + setSettings(prev => prev ? { ...prev, [key]: data[key], catalogRefreshPending: key === "codexDesktopAuthless" ? data.catalogRefreshPending : prev.catalogRefreshPending, startupHealth: data.startupHealth ?? prev.startupHealth } : prev); + if (key === "codexDesktopAuthless") await runSync(); } catch { - setSettings(prev => prev ? { ...prev, codexAutoStart: !next } : prev); + setSettings(prev => prev ? { ...prev, [key]: !next } : prev); setError(true); } finally { settingsMutationInFlightRef.current = false; @@ -631,6 +637,9 @@ export function useDashboardData(apiBase: string) { } }; + const toggleCodexAutoStart = () => toggleCodexSetting("codexAutoStart"); + const toggleCodexDesktopAuthless = () => toggleCodexSetting("codexDesktopAuthless"); + // Clears the sync result/error in this hook. The dashboard toast owns its own dismissal // timer but must publish the dismissal here: syncResult/syncError live above the dashboard // tabs, so a component-local flag alone would let a stale result remount as a fresh toast @@ -649,6 +658,9 @@ export function useDashboardData(apiBase: string) { const res = await fetch(`${apiBase}/api/sync`, { method: "POST" }); const data = await requireJson(res, "sync failed"); setSyncResult(data); + if (data.ok && data.status === "applied") { + setSettings(prev => prev ? { ...prev, catalogRefreshPending: false } : prev); + } if (data.projectConfigGrouped) setProjectConfigWarnings(data.projectConfigGrouped); } catch (err) { setSyncError(err instanceof Error ? err.message : String(err)); @@ -789,7 +801,7 @@ export function useDashboardData(apiBase: string) { effortCapHelpTriggerRef, updateTriggerRef, maHelpTriggerRef, shadowCallHelpTriggerRef, effortCapHelpDialogRef, updateDialogRef, maHelpDialogRef, shadowCallHelpDialogRef, filteredGroups, sidecarModels, visionModels, - saveSidecar, saveShadowCall, switchMaMode, toggleCodexAutoStart, runSync, clearSyncFeedback, + saveSidecar, saveShadowCall, switchMaMode, toggleCodexAutoStart, toggleCodexDesktopAuthless, runSync, clearSyncFeedback, fetchUpdateCheck, closeUpdateDialog, openUpdateDialog, changeUpdateChannel, runUpdate, }; } diff --git a/gui/src/pages/use-subagent-delegation.ts b/gui/src/pages/use-subagent-delegation.ts index 716eb11482..9baa5baa9a 100644 --- a/gui/src/pages/use-subagent-delegation.ts +++ b/gui/src/pages/use-subagent-delegation.ts @@ -21,6 +21,8 @@ export type DelegationPatch = { /** Ultra mode (Proactive delegation for every model/effort) via /api/v2. */ export type UltraModeState = { + loaded?: boolean; + keepNativeChatGptOnV1?: boolean; enabled: boolean; hintText: string | null; multiAgentV2Enabled: boolean; diff --git a/gui/src/styles-subagents-workspace.css b/gui/src/styles-subagents-workspace.css index c6292077b7..a9f9466ce7 100644 --- a/gui/src/styles-subagents-workspace.css +++ b/gui/src/styles-subagents-workspace.css @@ -575,3 +575,16 @@ } } } + + +/* Fallback targets keep their identifiers readable next to row actions. */ +.swi-fallback-controls { display: flex; flex-direction: column; align-items: stretch; gap: var(--space-2); flex: 1 1 55%; min-width: 0; } +.swi-fallback-row { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); } +.swi-fallback-model { min-width: 0; overflow-wrap: anywhere; } +.swi-fallback-model .setting-hint { display: block; } +.swi-fallback-actions { display: inline-flex; flex-shrink: 0; } +.swi-fallback-controls > .btn { align-self: flex-end; } +@media (max-width: 640px) { + .swi-fallback-editor { flex-direction: column; } + .swi-fallback-controls { width: 100%; } +} diff --git a/gui/tests/multi-agent-guidance.test.tsx b/gui/tests/multi-agent-guidance.test.tsx index 16470385b8..8907406f0e 100644 --- a/gui/tests/multi-agent-guidance.test.tsx +++ b/gui/tests/multi-agent-guidance.test.tsx @@ -65,7 +65,14 @@ function props(overrides: Partial = {}): Props { guidanceEnabled: false, syncCodexDefaults: true, onSave: (patch) => { requests.push(patch); }, - ultraMode: { enabled: false, hintText: null, multiAgentV2Enabled: false }, + ultraMode: { enabled: false, hintText: null, multiAgentV2Enabled: false, multiAgentMode: "default" }, + fallback: [], + fallbackPollMs: 60000, + fallbackBusy: false, + availableModels: [], + onFallbackChange: () => {}, + onFallbackPollMsChange: () => {}, + onFallbackSave: () => {}, ultraSaving: false, onUltraModeSave: () => {}, ultraLoadFailed: false, diff --git a/gui/tests/subagents-fallback.test.tsx b/gui/tests/subagents-fallback.test.tsx new file mode 100644 index 0000000000..ad794b8261 --- /dev/null +++ b/gui/tests/subagents-fallback.test.tsx @@ -0,0 +1,571 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import { clearClientResourceStoresForTests } from "../src/client-resource"; +import { en } from "../src/i18n/en"; +import { LanguageProvider } from "../src/i18n/provider"; +import Subagents from "../src/pages/Subagents"; +import { readSessionListCache } from "../src/session-list-cache"; + +const CACHE_KEY = "ocx.subagents.v1:"; +const FALLBACK_PATH = "/api/subagent-model-fallback"; +const ROSTER_PATH = "/api/subagent-models"; +const UNAVAILABLE_MODEL = "retired-provider/configured-model"; +const globals = [ + "document", "window", "navigator", "localStorage", "sessionStorage", "fetch", "IS_REACT_ACT_ENVIRONMENT", +] as const; + +type CachedSubagents = { available: string[]; chosen: string[]; fallback?: string[]; pollMs?: number }; +type FallbackSettings = { models: string[]; pollMs: number }; +type SentRequest = { path: string; method: string; init?: RequestInit }; +type V2Settings = { + enabled: boolean; + multiAgentMode: "v1" | "default" | "v2"; + multiAgentModeHintText: string | null; + keepNativeChatGptOnV1: boolean; +}; + +let previousGlobals: Record<(typeof globals)[number], PropertyDescriptor | undefined>; +let testWindow: Window; +let container: HTMLElement; +let root: Root | null = null; +let requests: SentRequest[]; +let available: string[]; +let chosen: string[]; +let fallbackSettings: FallbackSettings; +let failFallbackPut: boolean; +let v2Settings: V2Settings; +let preferredModel: string | null; +let fallbackGetGate: Promise | null; +let pendingFallbackResponse: Promise | null; + +beforeEach(() => { + clearClientResourceStoresForTests(); + previousGlobals = Object.fromEntries(globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])) as typeof previousGlobals; + testWindow = new Window({ url: "http://localhost/" }); + Object.defineProperty(testWindow.navigator, "language", { configurable: true, value: "en-US" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + navigator: { configurable: true, value: testWindow.navigator }, + localStorage: { configurable: true, value: testWindow.localStorage }, + sessionStorage: { configurable: true, value: testWindow.sessionStorage }, + IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + }); + + requests = []; + available = ["a-1", "a-2", "a-3"]; + chosen = ["a-1"]; + fallbackSettings = { models: ["a-2"], pollMs: 45_000 }; + failFallbackPut = false; + v2Settings = { enabled: true, multiAgentMode: "v2", multiAgentModeHintText: null, keepNativeChatGptOnV1: false }; + preferredModel = null; + fallbackGetGate = null; + pendingFallbackResponse = null; + Object.defineProperty(globalThis, "fetch", { + configurable: true, + value: async (input: RequestInfo | URL, init?: RequestInit) => { + const path = new URL(String(input), "http://localhost/").pathname; + const method = init?.method ?? "GET"; + requests.push({ path, method, init }); + // Match agent-settings-routes: fallback uses models, roster uses chosen/applied. + if (path === FALLBACK_PATH && method === "GET") { + if (pendingFallbackResponse) { + const pending = pendingFallbackResponse; + pendingFallbackResponse = null; + return pending; + } + if (fallbackGetGate) await fallbackGetGate; + return Response.json({ ...fallbackSettings, available }); + } + if (path === FALLBACK_PATH && method === "PUT") { + if (failFallbackPut) return Response.json({ error: "Fallback settings could not be persisted" }, { status: 500 }); + fallbackSettings = JSON.parse(String(init?.body)) as FallbackSettings; + return Response.json({ ok: true, ...fallbackSettings }); + } + if (path === ROSTER_PATH && method === "GET") return Response.json({ available, chosen }); + if (path === ROSTER_PATH && method === "PUT") { + chosen = (JSON.parse(String(init?.body)) as { models: string[] }).models; + return Response.json({ applied: chosen }); + } + if (path === "/api/v2" && method === "GET") { + return Response.json(v2Settings); + } + if (path === "/api/injection-model" && method === "GET") { + return Response.json({ + model: preferredModel, + effort: null, + available: [ + { provider: "openai", model: "gpt-5.4", namespaced: "gpt-5.4" }, + { provider: "anthropic", model: "claude-sonnet-4-6", namespaced: "anthropic/claude-sonnet-4-6" }, + ], + efforts: [], + }); + } + throw new Error(`Unexpected request: ${method} ${path}`); + }, + }); + container = testWindow.document.createElement("div") as unknown as HTMLElement; + testWindow.document.body.appendChild(container); +}); + +afterEach(async () => { + try { + if (root) { + const current = root; + await act(async () => { current.unmount(); }); + root = null; + } + } finally { + clearClientResourceStoresForTests(); + testWindow.close(); + for (const key of globals) { + const descriptor = previousGlobals[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + } +}); + +async function mount() { + // Match sibling input tests: initialize ReactDOM's event support after installing the DOM. + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(container); + root.render(); + }); + expect(requests.some(request => request.path === FALLBACK_PATH && request.method === "GET")).toBe(true); + expect(editor()).toBeTruthy(); +} + +function editor(): HTMLElement { + const element = container.querySelector(".swi-fallback-editor"); + if (!element) throw new Error("Fallback editor not found"); + return element; +} + +function rows(): HTMLElement[] { + return Array.from(editor().querySelectorAll(".swi-fallback-row")); +} + +function expectOrder(models: string[]) { + expect(rows()).toHaveLength(models.length); + models.forEach((model, index) => { + // The model span can also contain the unavailable-model warning. + expect(rows()[index]?.querySelector("span")?.textContent?.trim().startsWith(`${index + 1}. ${model}`)).toBe(true); + expect(rowButton(index, "sub.removeAria", model)).toBeTruthy(); + }); +} + +function labelledButton(scope: ParentNode, label: string): HTMLButtonElement { + const button = Array.from(scope.querySelectorAll("button")) + .find(candidate => candidate.getAttribute("aria-label") === label); + if (!button) throw new Error(`Button not found: ${label}`); + return button; +} + +function rowButton(index: number, key: "sub.moveUp" | "sub.moveDown" | "sub.removeAria", model: string) { + const row = rows()[index]; + if (!row) throw new Error(`Fallback row not found: ${index}`); + return labelledButton(row, en[key].replace("{m}", model)); +} + +function saveButton(scope: ParentNode = editor()): HTMLButtonElement { + const button = Array.from(scope.querySelectorAll("button")) + .find(candidate => candidate.textContent?.trim() === en["common.save"]); + if (!button) throw new Error("Save button not found"); + return button; +} + +async function click(button: HTMLButtonElement) { + expect(button.disabled).toBe(false); + await act(async () => { button.click(); }); +} + +async function addFallback(model: string) { + const trigger = labelledButton(editor(), en["sub.fallbackAdd"]); + expect(trigger.getAttribute("role")).toBe("combobox"); + await click(trigger); + // Select portals its listbox into document.body, outside the page container. + const listbox = testWindow.document.getElementById(trigger.getAttribute("aria-controls") ?? ""); + if (!listbox) throw new Error("Fallback model listbox not found"); + const option = Array.from(listbox.querySelectorAll('[role="option"]')) + .find(candidate => candidate.textContent?.trim() === model); + if (!option) throw new Error(`Fallback option not found: ${model}`); + await click(option as unknown as HTMLButtonElement); + expect(trigger.getAttribute("aria-expanded")).toBe("false"); +} + +function pollInput(): HTMLInputElement { + const input = editor().querySelector('input[type="number"]'); + if (!input) throw new Error("Fallback polling interval input not found"); + return input; +} + +async function changePollMs(value: number) { + await act(async () => { + const input = pollInput(); + Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!.call(input, String(value)); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true })); + input.dispatchEvent(new testWindow.Event("change", { bubbles: true })); + }); +} + +function putBodies(path = FALLBACK_PATH): unknown[] { + return requests.filter(request => request.path === path && request.method === "PUT") + .map(request => JSON.parse(String(request.init?.body)) as unknown); +} + +function cached(): CachedSubagents | null { + return readSessionListCache(CACHE_KEY); +} + +test("preserves an unavailable configured fallback ID on load and save", async () => { + fallbackSettings = { models: [UNAVAILABLE_MODEL, "a-2"], pollMs: 45_000 }; + expect(available).not.toContain(UNAVAILABLE_MODEL); + await mount(); + + expectOrder([UNAVAILABLE_MODEL, "a-2"]); + expect(rows()[0]?.textContent).toContain(en["sub.fallbackUnavailable"]); + expect(rows()[1]?.textContent).not.toContain(en["sub.fallbackUnavailable"]); + expect(cached()?.fallback).toEqual([UNAVAILABLE_MODEL, "a-2"]); + await click(saveButton()); + expect(putBodies()).toEqual([{ models: [UNAVAILABLE_MODEL, "a-2"], pollMs: 45_000 }]); + expectOrder([UNAVAILABLE_MODEL, "a-2"]); + expect(container.textContent).toContain(en["sub.fallbackSaved"]); +}); + +test("adds, reorders in both directions, and removes fallback models before saving their exact order", async () => { + await mount(); + await addFallback("a-3"); + expectOrder(["a-2", "a-3"]); + expect(rowButton(0, "sub.moveUp", "a-2").disabled).toBe(true); + expect(rowButton(1, "sub.moveDown", "a-3").disabled).toBe(true); + + await click(rowButton(1, "sub.moveUp", "a-3")); + expectOrder(["a-3", "a-2"]); + await click(rowButton(0, "sub.moveDown", "a-3")); + expectOrder(["a-2", "a-3"]); + await addFallback("a-1"); + await click(rowButton(0, "sub.removeAria", "a-2")); + expectOrder(["a-3", "a-1"]); + expect(putBodies()).toEqual([]); + + await click(saveButton()); + expect(putBodies()).toEqual([{ models: ["a-3", "a-1"], pollMs: 45_000 }]); + expect(putBodies(ROSTER_PATH)).toEqual([]); +}); + +test("keyboard moves retain row focus and removal moves focus to the next row or add control", async () => { + fallbackSettings.models = ["a-1", "a-2", "a-3"]; + await mount(); + + const activateWithEnter = async (button: HTMLButtonElement) => { + expect(button.disabled).toBe(false); + await act(async () => { + button.focus(); + expect(testWindow.document.activeElement).toBe(button); + button.dispatchEvent(new testWindow.KeyboardEvent("keydown", { key: "Enter", code: "Enter", bubbles: true })); + // happy-dom does not synthesize native button activation from Enter. Supply the + // keyboard-generated click (detail 0) explicitly; this test covers focus restoration. + button.dispatchEvent(new testWindow.MouseEvent("click", { bubbles: true, detail: 0 })); + button.dispatchEvent(new testWindow.KeyboardEvent("keyup", { key: "Enter", code: "Enter", bubbles: true })); + }); + }; + + const middleRow = rows()[1]; + await activateWithEnter(rowButton(1, "sub.moveDown", "a-2")); + expectOrder(["a-1", "a-3", "a-2"]); + expect(rows()[2]).toBe(middleRow); + expect(rowButton(2, "sub.moveDown", "a-2").disabled).toBe(true); + // The requested direction is disabled at the boundary; focus an enabled action + // in the moved row, rather than the neighboring row or document.body. + expect(testWindow.document.activeElement).toBe(rowButton(2, "sub.moveUp", "a-2")); + + await activateWithEnter(rowButton(2, "sub.moveUp", "a-2")); + expectOrder(["a-1", "a-2", "a-3"]); + expect(rows()[1]).toBe(middleRow); + expect(testWindow.document.activeElement).toBe(rowButton(1, "sub.moveUp", "a-2")); + + await activateWithEnter(rowButton(1, "sub.removeAria", "a-2")); + expectOrder(["a-1", "a-3"]); + expect(testWindow.document.activeElement).toBe(rowButton(1, "sub.removeAria", "a-3")); + + await activateWithEnter(rowButton(1, "sub.removeAria", "a-3")); + expectOrder(["a-1"]); + expect(testWindow.document.activeElement).toBe(rowButton(0, "sub.removeAria", "a-1")); + + await activateWithEnter(rowButton(0, "sub.removeAria", "a-1")); + expectOrder([]); + expect(testWindow.document.activeElement).toBe(labelledButton(editor(), en["sub.fallbackAdd"])); + expect(putBodies()).toEqual([]); +}); + +test("removes only the selected duplicate fallback occurrence by index", async () => { + fallbackSettings.models = ["a-2", "a-1", "a-2", "a-3"]; + await mount(); + expectOrder(["a-2", "a-1", "a-2", "a-3"]); + + await click(rowButton(2, "sub.removeAria", "a-2")); + expectOrder(["a-2", "a-1", "a-3"]); + await click(saveButton()); + expect(putBodies()).toEqual([{ models: ["a-2", "a-1", "a-3"], pollMs: 45_000 }]); +}); + +test("a failed fallback PUT retains the editable draft and leaves the committed cache unchanged", async () => { + await mount(); + const committed = cached(); + expect(committed).toEqual({ available, chosen: ["a-1"], fallback: ["a-2"], pollMs: 45_000 }); + await addFallback("a-3"); + await changePollMs(90_000); + failFallbackPut = true; + await click(saveButton()); + + expect(putBodies()).toEqual([{ models: ["a-2", "a-3"], pollMs: 90_000 }]); + expectOrder(["a-2", "a-3"]); + expect(pollInput().value).toBe("90000"); + expect(container.textContent).toContain("Fallback settings could not be persisted"); + expect(container.textContent).not.toContain(en["sub.fallbackSaved"]); + expect(saveButton().disabled).toBe(false); + expect(cached()).toEqual(committed); + + failFallbackPut = false; + await click(saveButton()); + expect(putBodies()).toEqual([ + { models: ["a-2", "a-3"], pollMs: 90_000 }, + { models: ["a-2", "a-3"], pollMs: 90_000 }, + ]); + expect(cached()?.fallback).toEqual(["a-2", "a-3"]); + expect(cached()?.pollMs).toBe(90_000); +}); + +test("a successful fallback save updates committed session data without committing a roster draft", async () => { + await mount(); + await click(labelledButton(container, en["sub.workspace.addToFeatured"].replace("{m}", "a-3"))); + await addFallback("a-3"); + await changePollMs(120_000); + await click(saveButton()); + + expect(putBodies()).toEqual([{ models: ["a-2", "a-3"], pollMs: 120_000 }]); + expect(putBodies(ROSTER_PATH)).toEqual([]); + expect(cached()).toEqual({ available, chosen: ["a-1"], fallback: ["a-2", "a-3"], pollMs: 120_000 }); + expectOrder(["a-2", "a-3"]); + expect(container.querySelectorAll(".swi-featured-row").length).toBe(2); +}); + +test("independent roster Save never caches an unsaved fallback draft", async () => { + await mount(); + await addFallback("a-3"); + await changePollMs(90_000); + await click(labelledButton(container, en["sub.workspace.addToFeatured"].replace("{m}", "a-3"))); + const rosterSaveRow = container.querySelector(".swi-save-row"); + if (!rosterSaveRow) throw new Error("Roster Save row not found"); + await click(saveButton(rosterSaveRow)); + + expect(putBodies(ROSTER_PATH)).toEqual([{ models: ["a-1", "a-3"] }]); + expect(putBodies()).toEqual([]); + expect(cached()).toEqual({ available, chosen: ["a-1", "a-3"], fallback: ["a-2"], pollMs: 45_000 }); + expectOrder(["a-2", "a-3"]); + expect(pollInput().value).toBe("90000"); + + // Saving the fallback afterward must retain the already committed roster. + await click(saveButton()); + expect(putBodies()).toEqual([{ models: ["a-2", "a-3"], pollMs: 90_000 }]); + expect(cached()).toEqual({ available, chosen: ["a-1", "a-3"], fallback: ["a-2", "a-3"], pollMs: 90_000 }); +}); + +test("remount shows the committed fallback and roster while a fresh fallback GET is pending", async () => { + await mount(); + await addFallback("a-3"); + await changePollMs(120_000); + await click(saveButton()); + + // A later roster save must not commit these newer fallback edits. + await click(rowButton(0, "sub.removeAria", "a-2")); + await changePollMs(90_000); + await click(labelledButton(container, en["sub.workspace.addToFeatured"].replace("{m}", "a-3"))); + const rosterSaveRow = container.querySelector(".swi-save-row"); + if (!rosterSaveRow) throw new Error("Roster Save row not found"); + await click(saveButton(rosterSaveRow)); + expectOrder(["a-3"]); + expect(pollInput().value).toBe("90000"); + + const current = root!; + await act(async () => { current.unmount(); }); + root = null; + // Keep sessionStorage, but discard the resource store so it cannot mask a stale session seed. + clearClientResourceStoresForTests(); + const getsBefore = requests.filter(request => request.path === FALLBACK_PATH && request.method === "GET").length; + let releaseGet!: () => void; + fallbackGetGate = new Promise(resolve => { releaseGet = resolve; }); + try { + await mount(); + expect(requests.filter(request => request.path === FALLBACK_PATH && request.method === "GET")).toHaveLength(getsBefore + 1); + // These assertions run before the fresh GET can return any data. + expectOrder(["a-2", "a-3"]); + expect(pollInput().value).toBe("120000"); + expect(Array.from(container.querySelectorAll(".swi-featured-name"), node => node.textContent?.trim())) + .toEqual(["a-1", "a-3"]); + expect(cached()).toEqual({ available, chosen: ["a-1", "a-3"], fallback: ["a-2", "a-3"], pollMs: 120_000 }); + } finally { + await act(async () => { releaseGet(); }); + fallbackGetGate = null; + } + expectOrder(["a-2", "a-3"]); + expect(pollInput().value).toBe("120000"); +}); + +test("a legacy cache keeps fallback disabled through GET failure, roster Save, and remount", async () => { + const legacyCache = { available, chosen: ["a-1"] }; + testWindow.sessionStorage.setItem(CACHE_KEY, JSON.stringify(legacyCache)); + let releaseGet!: (response: Response) => void; + pendingFallbackResponse = new Promise(resolve => { releaseGet = resolve; }); + + const assertBlocked = async (expectedCache = legacyCache) => { + expect(labelledButton(editor(), en["sub.fallbackAdd"]).disabled).toBe(true); + expect(pollInput().disabled).toBe(true); + expect(saveButton().disabled).toBe(true); + expect(Array.from(editor().querySelectorAll("input, button")) + .every(control => control.disabled)).toBe(true); + await act(async () => { saveButton().click(); }); + expect(putBodies()).toEqual([]); + expect(cached()).toEqual(expectedCache); + expect(cached()).not.toHaveProperty("fallback"); + expect(cached()).not.toHaveProperty("pollMs"); + // A failed read must never turn the page's empty placeholder into a saved empty chain. + expect(fallbackSettings).toEqual({ models: ["a-2"], pollMs: 45_000 }); + }; + + try { + await mount(); + expect(rows()).toHaveLength(0); + expect(pendingFallbackResponse).toBeNull(); + await assertBlocked(); + } finally { + await act(async () => { + releaseGet(Response.json({ error: "Fallback discovery failed" }, { status: 503 })); + }); + } + expect(container.textContent).toContain(en["sub.loadFail"]); + await assertBlocked(); + + await click(labelledButton(container, en["sub.workspace.addToFeatured"].replace("{m}", "a-3"))); + const rosterSaveRow = container.querySelector(".swi-save-row"); + if (!rosterSaveRow) throw new Error("Roster Save row not found"); + await click(saveButton(rosterSaveRow)); + const savedRosterCache = { available, chosen: ["a-1", "a-3"] }; + expect(putBodies(ROSTER_PATH)).toEqual([{ models: ["a-1", "a-3"] }]); + await assertBlocked(savedRosterCache); + + const current = root!; + await act(async () => { current.unmount(); }); + root = null; + clearClientResourceStoresForTests(); + const getsBefore = requests.filter(request => request.path === FALLBACK_PATH && request.method === "GET").length; + pendingFallbackResponse = new Promise(resolve => { releaseGet = resolve; }); + try { + await mount(); + expect(requests.filter(request => request.path === FALLBACK_PATH && request.method === "GET")).toHaveLength(getsBefore + 1); + expect(pendingFallbackResponse).toBeNull(); + await assertBlocked(savedRosterCache); + } finally { + await act(async () => { + releaseGet(Response.json({ error: "Fallback discovery still unavailable" }, { status: 503 })); + }); + } + expect(container.textContent).toContain(en["sub.loadFail"]); + await assertBlocked(savedRosterCache); + expect(putBodies(ROSTER_PATH)).toEqual([{ models: ["a-1", "a-3"] }]); +}); + +test.each([false, true])("a captured old fallback GET cannot overwrite a newer draft or save (saved=%s)", async (saveNewer) => { + const committedA = { available, chosen: ["a-1"], fallback: ["a-2"], pollMs: 45_000 }; + testWindow.sessionStorage.setItem(CACHE_KEY, JSON.stringify(committedA)); + // Serialize A before any edit or PUT. Reading mutable fallbackSettings after the gate + // would accidentally return B and let the stale-response regression pass. + const capturedOldResponse = Response.json({ models: ["a-2"], pollMs: 45_000, available }); + let releaseGet!: (response: Response) => void; + pendingFallbackResponse = new Promise(resolve => { releaseGet = resolve; }); + const committedB = { available, chosen: ["a-1"], fallback: ["a-3"], pollMs: 90_000 }; + + try { + await mount(); + expect(pendingFallbackResponse).toBeNull(); + expectOrder(["a-2"]); + await addFallback("a-3"); + await click(rowButton(0, "sub.removeAria", "a-2")); + await changePollMs(90_000); + if (saveNewer) await click(saveButton()); + expectOrder(["a-3"]); + expect(pollInput().value).toBe("90000"); + expect(cached()).toEqual(saveNewer ? committedB : committedA); + } finally { + await act(async () => { releaseGet(capturedOldResponse); }); + } + + // The delayed GET has now settled; both UI fields and the committed session seed + // must retain their respective newer-draft / newer-save semantics. + expect(capturedOldResponse.bodyUsed).toBe(true); + expectOrder(["a-3"]); + expect(pollInput().value).toBe("90000"); + expect(cached()).toEqual(saveNewer ? committedB : committedA); + expect(putBodies()).toEqual(saveNewer ? [{ models: ["a-3"], pollMs: 90_000 }] : []); +}); + +test("invalid polling intervals disable Save without a PUT or cache mutation, and a valid interval recovers", async () => { + await mount(); + const committed = cached(); + for (const interval of [0, 4_999, 600_001, 5_000.5]) { + await changePollMs(interval); + expect(pollInput().getAttribute("aria-invalid")).toBe("true"); + expect(editor().querySelector('[role="alert"]')?.textContent).toContain(en["sub.fallbackPollInvalid"]); + expect(saveButton().disabled).toBe(true); + await act(async () => { saveButton().click(); }); + expect(putBodies()).toEqual([]); + expect(cached()).toEqual(committed); + } + + await changePollMs(5_000); + expect(pollInput().getAttribute("aria-invalid")).toBe("false"); + expect(editor().querySelector('[role="alert"]')).toBeNull(); + await click(saveButton()); + expect(putBodies()).toEqual([{ models: ["a-2"], pollMs: 5_000 }]); + expect(cached()?.pollMs).toBe(5_000); +}); + +const compatibilityCases: Array<{ + name: string; + model: string; + enabled: boolean; + mode: V2Settings["multiAgentMode"]; + keepNative: boolean; + warning: boolean; +}> = [ + { name: "native preferred model", model: "gpt-5.4", enabled: true, mode: "v2", keepNative: false, warning: false }, + { name: "routed preferred model on the default surface", model: "anthropic/claude-sonnet-4-6", enabled: false, mode: "default", keepNative: false, warning: true }, + { name: "routed preferred model on V1", model: "anthropic/claude-sonnet-4-6", enabled: false, mode: "v1", keepNative: false, warning: false }, + { name: "forced V2 preserving native V1 with global V2 disabled", model: "anthropic/claude-sonnet-4-6", enabled: false, mode: "v2", keepNative: true, warning: false }, + { name: "global V2 enabled despite native V1 preservation", model: "anthropic/claude-sonnet-4-6", enabled: true, mode: "v2", keepNative: true, warning: true }, +]; + +test.each(compatibilityCases)("V2 compatibility guidance: $name", async ({ model, enabled, mode, keepNative, warning }) => { + preferredModel = model; + v2Settings = { enabled, multiAgentMode: mode, multiAgentModeHintText: null, keepNativeChatGptOnV1: keepNative }; + await mount(); + + const note = container.querySelector('.swi-v2-compatibility[role="note"]'); + if (warning) { + expect(note).toBeTruthy(); + expect(note?.textContent).toContain(en["sub.v2Compatibility.title"]); + expect(note?.textContent).toContain(en["sub.v2Compatibility.risk"]); + // The response exposes no recovery state: guidance must explicitly say it is unknown. + expect(note?.textContent).toContain(en["sub.v2Compatibility.recoveryUnknown"]); + expect(note?.querySelector("a")?.getAttribute("href")).toBe("https://github.com/lidge-jun/opencodex/issues/92"); + expect(note?.querySelector('[role="switch"], [aria-pressed], input[type="checkbox"]')).toBeNull(); + } else { + expect(note).toBeNull(); + expect(container.textContent).not.toContain(en["sub.v2Compatibility.recoveryUnknown"]); + } + expect(requests.filter(request => request.method !== "GET")).toEqual([]); +}); diff --git a/gui/tests/vision-sidecar-dashboard.test.tsx b/gui/tests/vision-sidecar-dashboard.test.tsx index dc762de58f..738ed866e6 100644 --- a/gui/tests/vision-sidecar-dashboard.test.tsx +++ b/gui/tests/vision-sidecar-dashboard.test.tsx @@ -12,7 +12,8 @@ import { LanguageProvider } from "../src/i18n/provider"; import { DashboardSidecarPanels } from "../src/pages/dashboard-overview-sections"; import type { SidecarData, SidecarPatch } from "../src/pages/dashboard-shared"; import { mergeSidecarSetting } from "../src/pages/dashboard-shared"; -import type { useDashboardData } from "../src/pages/use-dashboard-data"; +import { useDashboardData } from "../src/pages/use-dashboard-data"; +import { setClientResourceData } from "../src/client-resource"; const globals = ["document", "window", "navigator", "IS_REACT_ACT_ENVIRONMENT"] as const; let previousGlobals: Record<(typeof globals)[number], PropertyDescriptor | undefined>; @@ -382,4 +383,114 @@ test("model and reasoning saves still omit enabled, limit, and timeout", async ( expect(patches).toHaveLength(2); expect(patches[1]).toEqual({ vision: { reasoning: "high" } }); assertVisionControlFieldsOmitted(patches[1]!); -}); \ No newline at end of file +}); + +test("Desktop login switch defaults off, preserves explicit opt-in, and disables while saving", async () => { + const { d } = harness(); + let clicks = 0; + d.toggleCodexDesktopAuthless = async () => { clicks += 1; }; + d.settings = { codexAutoStart: true, port: 10100, hostname: "127.0.0.1" }; + await mount(d); + const toggle = () => host.querySelector(`button[aria-label="${en["dash.codexDesktopAuthless"]}"]`)!; + expect(toggle().getAttribute("aria-pressed")).toBe("false"); + d.settings.codexDesktopAuthless = true; + await mount(d); + expect(toggle().getAttribute("aria-pressed")).toBe("true"); + await act(async () => { toggle().click(); }); + expect(clicks).toBe(1); + d.settings.codexDesktopAuthless = false; + d.settings.catalogRefreshPending = true; + d.settingsSaving = true; + await mount(d); + expect(toggle().getAttribute("aria-pressed")).toBe("false"); + expect(toggle().disabled).toBe(true); + expect(host.textContent).toContain(en["codexAuth.catalogRefreshPending"]); +}); + + +test.each([undefined, false, true])("Desktop login preference %s persists before full sync; sync failure keeps the saved preference", async (initial) => { + const originalFetch = globalThis.fetch; + const writes: Array<{ path: string; body: unknown }> = []; + let latest: Dash | undefined; + let saved = initial; + const apiBase = `/authless-test-${String(initial)}`; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const path = String(input); + if (init?.method === "PUT") { + const body = JSON.parse(String(init.body)); + writes.push({ path, body }); + if (body.codexDesktopAuthless !== undefined) { + saved = body.codexDesktopAuthless; + return Response.json({ codexDesktopAuthless: saved, catalogRefreshPending: true }); + } + return Response.json({ codexAutoStart: body.codexAutoStart, catalogRefreshPending: false }); + } + if (path.endsWith("/api/sync")) { + writes.push({ path, body: null }); + return Response.json({ error: "sync unavailable" }, { status: 503 }); + } + if (path.endsWith("/api/settings")) { + return Response.json({ codexAutoStart: true, codexDesktopAuthless: saved, port: 10100, hostname: "127.0.0.1" }); + } + return Response.json({}, { status: 503 }); + }) as typeof fetch; + function Harness() { latest = useDashboardData(apiBase); return null; } + try { + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(host); + root.render(); + }); + expect(latest?.settings?.codexDesktopAuthless).toBe(initial); + await act(async () => { await latest!.toggleCodexDesktopAuthless(); }); + expect(writes).toEqual([ + { path: `${apiBase}/api/settings`, body: { codexDesktopAuthless: !initial } }, + { path: `${apiBase}/api/sync`, body: null }, + ]); + expect(latest?.settings?.codexDesktopAuthless).toBe(!initial); + expect(latest?.syncError).toBe("sync unavailable"); + expect(latest?.settings?.catalogRefreshPending).toBe(true); + await act(async () => { await latest!.toggleCodexAutoStart(); }); + expect(latest?.settings?.codexAutoStart).toBe(false); + expect(latest?.settings?.catalogRefreshPending).toBe(true); + } finally { + await act(async () => { root?.unmount(); }); + root = null; + globalThis.fetch = originalFetch; + } +}); + + +test.each(["skipped", "catalog-only", "applied"])("Desktop preference pending state follows %s sync application evidence", async (syncStatus) => { + const originalFetch = globalThis.fetch; + let latest: Dash | undefined; + const apiBase = `/authless-sync-${syncStatus}`; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const path = String(input); + if (init?.method === "PUT") return Response.json({ codexDesktopAuthless: true, catalogRefreshPending: true }); + if (path.endsWith("/api/sync")) return Response.json({ ok: true, status: syncStatus, message: syncStatus }); + if (path.endsWith("/api/settings")) return Response.json({ codexAutoStart: true, codexDesktopAuthless: false, port: 10100, hostname: "127.0.0.1" }); + return Response.json({}, { status: 503 }); + }) as typeof fetch; + function Harness() { latest = useDashboardData(apiBase); return null; } + try { + const { createRoot } = await import("react-dom/client"); + await act(async () => { root = createRoot(host); root.render(); }); + await act(async () => { await latest!.toggleCodexDesktopAuthless(); }); + expect(latest?.settings?.codexDesktopAuthless).toBe(true); + expect(latest?.settings?.catalogRefreshPending).toBe(syncStatus !== "applied"); + expect(latest?.syncResult?.status).toBe(syncStatus); + // A fresh settings poll has no application receipt and cannot erase pending. + await act(async () => { + setClientResourceData(`dashboard-settings:${apiBase}`, { + settings: { codexAutoStart: true, codexDesktopAuthless: true, port: 10100, hostname: "127.0.0.1" }, + }); + }); + expect(latest?.settings?.codexDesktopAuthless).toBe(true); + expect(latest?.settings?.catalogRefreshPending === true).toBe(syncStatus !== "applied"); + } finally { + await act(async () => { root?.unmount(); }); + root = null; + globalThis.fetch = originalFetch; + } +}); diff --git a/tests/codex-integration/codex-inject.test.ts b/tests/codex-integration/codex-inject.test.ts index 84ac5f67b6..b6be3c2f69 100644 --- a/tests/codex-integration/codex-inject.test.ts +++ b/tests/codex-integration/codex-inject.test.ts @@ -31,8 +31,8 @@ describe("Codex config injection", () => { }); describe("authless Codex Desktop opt-in (#1107)", () => { - test("default target on loopback stays Design B and byte-identical", () => { - const target = standaloneCodexRoutingTarget(10100, {}); + test.each([undefined, false])("disabled preference %s on loopback stays Design B and byte-identical", (codexDesktopAuthless) => { + const target = standaloneCodexRoutingTarget(10100, { codexDesktopAuthless }); expect(target.desktopAuthless).toBeUndefined(); expect(buildProfileFile(target, null)).toBe(buildProfileFile(10100, null)); expect(buildProviderTableBlock(target)).toContain("requires_openai_auth = true");