Skip to content

Commit f26edc8

Browse files
committed
fix(gui): confirm account-mode switches and refresh dependent state
The Pool/Direct select now asks for confirmation before the mode PATCH, because switching rebinds running threads and changes quota accounting; a cancelled confirmation leaves the select snapped back. After a successful mode PATCH, provider quotas and the shared Codex account controller refresh before the action reports success, so both tabs never show pre-switch state. The select is disabled during ordinary settings saves too, and mode errors are announced via role=alert. Adds focused tests for the exact PATCH body, confirm/cancel paths, failure rollback, the dependent refreshes, and the concurrency disable.
1 parent 91883da commit f26edc8

11 files changed

Lines changed: 301 additions & 10 deletions

File tree

‎gui/src/components/provider-workspace/ProviderSettings.tsx‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -282,8 +282,19 @@ export default function ProviderSettings({
282282
<select
283283
className="input"
284284
value={accountMode}
285-
disabled={modeSaving}
286-
onChange={e => void applyAccountMode(e.target.value as "pool" | "direct")}
285+
disabled={modeSaving || saving}
286+
onChange={e => {
287+
const next = e.target.value as "pool" | "direct";
288+
if (next === accountMode) return;
289+
// Flipping modes rebinds running threads and changes quota accounting,
290+
// so the PATCH only fires after an explicit confirmation.
291+
if (!window.confirm(t("pws.accountModeConfirm"))) {
292+
// Keep the visible choice aligned with the applied mode.
293+
e.target.value = accountMode;
294+
return;
295+
}
296+
void applyAccountMode(next);
297+
}}
287298
>
288299
<option value="pool">{t("codexAuth.accountModePool")}</option>
289300
<option value="direct">{t("codexAuth.accountModeDirect")}</option>
@@ -293,7 +304,10 @@ export default function ProviderSettings({
293304
</span>
294305
{modeSaving && <span className="muted text-label">{t("pws.accountSwitching")}</span>}
295306
{modeMsg && (
296-
<span className={modeMsg.ok ? "pwi-settings-mode-msg pwi-settings-mode-msg--ok" : "pwi-settings-mode-msg pwi-settings-mode-msg--err"}>
307+
<span
308+
role={modeMsg.ok ? "status" : "alert"}
309+
className={modeMsg.ok ? "pwi-settings-mode-msg pwi-settings-mode-msg--ok" : "pwi-settings-mode-msg pwi-settings-mode-msg--err"}
310+
>
297311
{modeMsg.text}
298312
</span>
299313
)}
@@ -332,7 +346,11 @@ export default function ProviderSettings({
332346
</div>
333347
</div>
334348
)}
335-
{msg && <div className={msg.ok ? "pwi-settings-msg pwi-settings-msg--ok" : "pwi-settings-msg pwi-settings-msg--err"}>{msg.text}</div>}
349+
{msg && (
350+
<div role={msg.ok ? "status" : "alert"} className={msg.ok ? "pwi-settings-msg pwi-settings-msg--ok" : "pwi-settings-msg pwi-settings-msg--err"}>
351+
{msg.text}
352+
</div>
353+
)}
336354
</div>
337355
);
338356
}

‎gui/src/i18n/de.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1466,6 +1466,7 @@ export const de: Record<TKey, string> = {
14661466
"pws.settingsSaved": "Einstellungen gespeichert.",
14671467
"pws.accountModeSaved": "Kontomodus gespeichert.",
14681468
"pws.accountModeFailed": "Kontomodus konnte nicht gewechselt werden.",
1469+
"pws.accountModeConfirm": "OpenAI-Kontomodus wechseln? Laufende Unterhaltungen werden dem anderen Kontosatz zugeordnet und die Quotennutzung wird unter dem neuen Modus erfasst.",
14691470
"pws.settingsUnsavedBar": "Es gibt ungespeicherte Änderungen.",
14701471
"pws.unsavedLeaveBody": "Es gibt ungespeicherte Änderungen. Vor dem Verlassen speichern?",
14711472
"pws.unsavedLeaveTitle": "Ungespeicherte Änderungen",

‎gui/src/i18n/en.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1042,6 +1042,7 @@ export const en = {
10421042
"pws.settingsSaved": "Settings saved.",
10431043
"pws.accountModeSaved": "Account mode saved.",
10441044
"pws.accountModeFailed": "Could not switch the account mode.",
1045+
"pws.accountModeConfirm": "Switch the OpenAI account mode? Running conversations will be reassigned to the other mode's account set, and quota usage will be tracked against the new mode.",
10451046
"pws.settingsUnsavedBar": "You have unsaved changes.",
10461047
"pws.unsavedLeaveBody": "You have unsaved changes. Save them before leaving?",
10471048
"pws.unsavedLeaveTitle": "Unsaved changes",

‎gui/src/i18n/ja.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -992,6 +992,7 @@ export const ja: Record<TKey, string> = {
992992
"pws.settingsSaved": "設定を保存しました。",
993993
"pws.accountModeSaved": "アカウントモードを保存しました。",
994994
"pws.accountModeFailed": "アカウントモードを切り替えられませんでした。",
995+
"pws.accountModeConfirm": "OpenAI のアカウントモードを切り替えますか?実行中の会話はもう一方のモードのアカウントセットに再割り当てされ、クォータ使用量は新しいモードで計上されます。",
995996
"pws.settingsUnsavedBar": "未保存の変更があります。",
996997
"pws.unsavedLeaveBody": "未保存の変更があります。保存してから移動しますか?",
997998
"pws.unsavedLeaveTitle": "未保存の変更",

‎gui/src/i18n/ko.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1493,6 +1493,7 @@ export const ko: Record<TKey, string> = {
14931493
"pws.settingsSaved": "설정이 저장되었습니다.",
14941494
"pws.accountModeSaved": "계정 모드가 저장되었습니다.",
14951495
"pws.accountModeFailed": "계정 모드를 전환할 수 없습니다.",
1496+
"pws.accountModeConfirm": "OpenAI 계정 모드를 전환할까요? 실행 중인 대화가 다른 모드의 계정 세트로 다시 연결되며, 할당량 사용량은 새 모드로 집계됩니다.",
14961497
"pws.settingsUnsavedBar": "저장하지 않은 변경사항이 있습니다.",
14971498
"pws.unsavedLeaveBody": "저장하지 않은 변경사항이 있습니다. 나가기 전에 저장하시겠습니까?",
14981499
"pws.unsavedLeaveTitle": "미저장 변경사항",

‎gui/src/i18n/ru.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1034,6 +1034,7 @@ export const ru: Record<TKey, string> = {
10341034
"pws.settingsSaved": "Настройки сохранены.",
10351035
"pws.accountModeSaved": "Режим аккаунта сохранён.",
10361036
"pws.accountModeFailed": "Не удалось переключить режим аккаунта.",
1037+
"pws.accountModeConfirm": "Переключить режим аккаунта OpenAI? Текущие беседы будут перенаправлены на другой набор аккаунтов, а использование квоты будет учитываться в новом режиме.",
10371038
"pws.settingsUnsavedBar": "Есть несохранённые изменения.",
10381039
"pws.unsavedLeaveBody": "Есть несохранённые изменения. Сохранить их перед переходом?",
10391040
"pws.unsavedLeaveTitle": "Несохранённые изменения",

‎gui/src/i18n/zh.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1486,6 +1486,7 @@ export const zh: Record<TKey, string> = {
14861486
"pws.settingsSaved": "设置已保存。",
14871487
"pws.accountModeSaved": "账户模式已保存。",
14881488
"pws.accountModeFailed": "无法切换账户模式。",
1489+
"pws.accountModeConfirm": "切换 OpenAI 账户模式?正在进行的对话将重新分配到另一种模式的账户集合,配额用量将按新模式计入。",
14891490
"pws.settingsUnsavedBar": "有未保存的更改。",
14901491
"pws.unsavedLeaveBody": "有未保存的更改。离开前保存吗?",
14911492
"pws.unsavedLeaveTitle": "未保存的更改",

‎gui/src/pages/Providers.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,9 @@ export default function Providers({ apiBase }: { apiBase: string }) {
181181
const { removeProvider, confirmRemoveProvider, setProviderDisabled, setDefaultProvider, updateProvider } = useProvidersCrud({
182182
apiBase, t, removeBusyRef, workspaceSelected, setWorkspaceSelected, setRemoveConfirmName,
183183
notify, fetchConfig, fetchOauth, fetchProviderQuotas,
184+
// Mode PATCHes clear quota caches and thread affinity; the shared controller
185+
// must re-read /active (with quota) so both tabs show the post-switch state.
186+
refreshCodexAccount: () => codexPool.load(true),
184187
});
185188

186189
const requestLoginOAuth = (provider: string, addAccount = false) => {

‎gui/src/pages/use-providers-crud.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export function useProvidersCrud({
2929
fetchConfig,
3030
fetchOauth,
3131
fetchProviderQuotas,
32+
refreshCodexAccount,
3233
}: {
3334
apiBase: string;
3435
t: TFn;
@@ -40,6 +41,8 @@ export function useProvidersCrud({
4041
fetchConfig: () => Promise<void>;
4142
fetchOauth: () => Promise<void>;
4243
fetchProviderQuotas: (refresh?: boolean) => Promise<void>;
44+
/** Shared Codex account controller refresh (Providers.tsx passes codexPool.load). */
45+
refreshCodexAccount?: () => Promise<unknown> | unknown;
4346
}) {
4447
const removeProvider = useCallback(async (name: string) => {
4548
setRemoveConfirmName(name);
@@ -103,11 +106,18 @@ export function useProvidersCrud({
103106
// Await refresh so callers (e.g. notes editor) only leave edit mode once
104107
// item.note reflects the saved value.
105108
await fetchConfig();
109+
// A codexAccountMode PATCH clears quota caches and thread affinity server-side,
110+
// so both dependent surfaces must refresh before the action reports success.
111+
if (Object.hasOwn(patch, "codexAccountMode")) {
112+
const refreshes: Promise<unknown>[] = [fetchProviderQuotas(true)];
113+
if (refreshCodexAccount) refreshes.push(Promise.resolve(refreshCodexAccount()));
114+
await Promise.all(refreshes);
115+
}
106116
return { ok: true };
107117
} catch {
108118
return { ok: false, error: t("prov.networkError") };
109119
}
110-
}, [apiBase, fetchConfig, t]);
120+
}, [apiBase, fetchConfig, fetchProviderQuotas, refreshCodexAccount, t]);
111121

112122
const setDefaultProvider = useCallback(async (name: string): Promise<boolean> => {
113123
try {
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
import { afterEach, beforeEach, expect, test } from "bun:test";
2+
import { Window } from "happy-dom";
3+
import { act } from "react";
4+
import type { Root } from "react-dom/client";
5+
import ProviderSettings from "../src/components/provider-workspace/ProviderSettings";
6+
import type { ProviderUpdatePatch } from "../src/components/provider-workspace/types";
7+
import { LanguageProvider } from "../src/i18n/provider";
8+
import type { WorkspaceItem } from "../src/provider-workspace/catalog";
9+
10+
const globals = ["document", "window", "navigator", "localStorage", "IS_REACT_ACT_ENVIRONMENT"] as const;
11+
let previousGlobals: Record<(typeof globals)[number], unknown>;
12+
let testWindow: Window;
13+
14+
beforeEach(() => {
15+
previousGlobals = Object.fromEntries(globals.map(key => [key, Reflect.get(globalThis, key)])) as typeof previousGlobals;
16+
testWindow = new Window({ url: "http://localhost/#providers/workspace" });
17+
Object.defineProperty(testWindow.navigator, "language", { configurable: true, value: "en-US" });
18+
Object.defineProperties(globalThis, {
19+
document: { configurable: true, value: testWindow.document },
20+
window: { configurable: true, value: testWindow },
21+
navigator: { configurable: true, value: testWindow.navigator },
22+
localStorage: { configurable: true, value: testWindow.localStorage },
23+
});
24+
setConfirm(true);
25+
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
26+
});
27+
28+
afterEach(() => {
29+
testWindow.close();
30+
for (const key of globals) {
31+
Object.defineProperty(globalThis, key, { configurable: true, value: previousGlobals[key] });
32+
}
33+
});
34+
35+
function setConfirm(result: boolean): void {
36+
Object.defineProperty(testWindow, "confirm", { configurable: true, value: () => result });
37+
}
38+
39+
function openAiItem(mode: "pool" | "direct" = "pool"): WorkspaceItem {
40+
return {
41+
name: "openai",
42+
adapter: "openai-responses",
43+
baseUrl: "https://chatgpt.com/backend-api/codex",
44+
authMode: "forward",
45+
codexAccountMode: mode,
46+
} as WorkspaceItem;
47+
}
48+
49+
async function mountSettings(
50+
item: WorkspaceItem,
51+
onUpdateProvider?: (name: string, patch: ProviderUpdatePatch) => Promise<{ ok: boolean; error?: string }>,
52+
): Promise<{
53+
root: Root;
54+
container: HTMLElement;
55+
patches: ProviderUpdatePatch[];
56+
}> {
57+
const patches: ProviderUpdatePatch[] = [];
58+
const container = document.createElement("div");
59+
document.body.append(container);
60+
const { createRoot } = await import("react-dom/client");
61+
let root!: Root;
62+
await act(async () => {
63+
root = createRoot(container);
64+
root.render(
65+
<LanguageProvider>
66+
<ProviderSettings
67+
item={item}
68+
onUpdateProvider={async (name, patch) => {
69+
patches.push(patch);
70+
return onUpdateProvider ? onUpdateProvider(name, patch) : { ok: true };
71+
}}
72+
/>
73+
</LanguageProvider>,
74+
);
75+
});
76+
return { root, container, patches };
77+
}
78+
79+
function modeSelect(container: HTMLElement): HTMLSelectElement {
80+
const select = [...container.querySelectorAll<HTMLSelectElement>("select")]
81+
.find(s => s.value === "pool" || s.value === "direct");
82+
expect(select).toBeTruthy();
83+
return select!;
84+
}
85+
86+
async function chooseMode(select: HTMLSelectElement, value: string): Promise<void> {
87+
await act(async () => {
88+
Object.getOwnPropertyDescriptor(testWindow.HTMLSelectElement.prototype, "value")!
89+
.set!.call(select, value);
90+
select.dispatchEvent(new testWindow.Event("change", { bubbles: true }));
91+
});
92+
}
93+
94+
test("a confirmed mode change sends the exact standalone codexAccountMode patch", async () => {
95+
const { root, container, patches } = await mountSettings(openAiItem("pool"));
96+
const select = modeSelect(container);
97+
98+
await chooseMode(select, "direct");
99+
100+
expect(patches).toEqual([{ codexAccountMode: "direct" }]);
101+
expect(select.value).toBe("direct");
102+
expect(container.querySelector('[role="status"]')?.textContent).toContain("Account mode saved.");
103+
await act(async () => { root.unmount(); });
104+
});
105+
106+
test("a cancelled confirmation sends no patch and snaps the select back", async () => {
107+
const { root, container, patches } = await mountSettings(openAiItem("pool"));
108+
const select = modeSelect(container);
109+
setConfirm(false);
110+
111+
await chooseMode(select, "direct");
112+
113+
expect(patches).toHaveLength(0);
114+
expect(select.value).toBe("pool");
115+
await act(async () => { root.unmount(); });
116+
});
117+
118+
test("a failed mode patch keeps the applied mode and announces the error", async () => {
119+
const { root, container } = await mountSettings(openAiItem("pool"), async () => ({ ok: false, error: "mode rejected" }));
120+
const select = modeSelect(container);
121+
122+
await chooseMode(select, "direct");
123+
124+
expect(select.value).toBe("pool");
125+
const alert = container.querySelector('[role="alert"]');
126+
expect(alert?.textContent).toContain("mode rejected");
127+
await act(async () => { root.unmount(); });
128+
});
129+
130+
test("the mode select is disabled while its own PATCH is in flight", async () => {
131+
let resolvePatch!: (result: { ok: boolean }) => void;
132+
const pending = new Promise<{ ok: boolean }>(resolve => {
133+
resolvePatch = resolve;
134+
});
135+
const { root, container } = await mountSettings(openAiItem(), async () => pending);
136+
const select = modeSelect(container);
137+
138+
await chooseMode(select, "direct");
139+
expect(select.disabled).toBe(true);
140+
141+
await act(async () => {
142+
resolvePatch({ ok: true });
143+
await pending;
144+
});
145+
expect(select.disabled).toBe(false);
146+
await act(async () => { root.unmount(); });
147+
});
148+
149+
test("the mode select is disabled while an ordinary settings save is in flight", async () => {
150+
let resolveSave!: (result: { ok: boolean; error?: string }) => void;
151+
const pending = new Promise<{ ok: boolean; error?: string }>(resolve => {
152+
resolveSave = resolve;
153+
});
154+
const { root, container } = await mountSettings(openAiItem(), async () => pending);
155+
const note = container.querySelector<HTMLTextAreaElement>(".pwi-settings-textarea")!;
156+
157+
await act(async () => {
158+
Object.getOwnPropertyDescriptor(testWindow.HTMLTextAreaElement.prototype, "value")!
159+
.set!.call(note, "changed");
160+
note.dispatchEvent(new testWindow.Event("input", { bubbles: true }));
161+
});
162+
const saveButton = container.querySelector<HTMLButtonElement>(".pwi-settings-sticky-bar .btn-primary")!;
163+
expect(saveButton).toBeTruthy();
164+
await act(async () => {
165+
saveButton!.click();
166+
await Promise.resolve();
167+
});
168+
169+
expect(modeSelect(container).disabled).toBe(true);
170+
await act(async () => {
171+
resolveSave({ ok: true });
172+
await pending;
173+
});
174+
expect(modeSelect(container).disabled).toBe(false);
175+
await act(async () => { root.unmount(); });
176+
});

0 commit comments

Comments
 (0)