provider: magpie's own Codex account switches leave the Codex app running unless Restart the app is ticked (atom0964)

atom0964 on Discord (#help) has two ChatGPT Plus accounts in magpie, with
Codex always signed in to the first and Only switch Codex's sign-in both
off, on Smart routing. The Codex desktop app kept restarting by itself.
They tried several combinations of the ticks and it still did.

Why: with both off, SwitchWhenSpent signs Codex in to the next account at
98% and back to the first below 90%. Each switch was noted for the Codex
app (codexAppSpentSwitch), and KeepCodexAppOnItsProvider ended its
app-server once no turn ran; the ChatGPT app shows that as an error and
relaunches (#4550). With Codex kept on the first account there is no
switch, but the used-up takeover (magpie made Codex's provider for a
used-up account and given back once it has room; f37742e14 only limits
it to when another account can serve, which two accounts always can)
changed Codex's route, and that ended it too. So every combination
restarted the app.

What changed:
- Provider.RestartApp (restartApp), off by default, set by
  provider/restartapp (SetRestartApp, Codex only). This computer's own,
  like KeepLogin: Mirror keeps it and davsync's hash leaves it out.
- switchLoginBy(agent, user, byMagpie): SwitchWhenSpent marks its
  switch magpie's own (codexApp.auto). In codexAppStep, a change that is
  magpie's own (its switch, the takeover in or out, the first look at an
  app on a used-up account) ends nothing unless RestartApp is on; it
  logs why and the app follows once restarted. The switch notice's
  Restart, the Agents row's Restart, and uninstall are unchanged.
- Still restarted: a switch the user makes (Switch, the Agents row, the
  CLI), a Connect or Disconnect, failover written or taken out (any
  route change while the takeover state is unchanged), and a user's
  switch pending when magpie's comes.
- GUI: under Codex's accounts, with more than one on (or the tick set),
  "Restart the Codex app when magpie switches its account", with a tip
  and toasts in en, zh, zh-TW, ja and de. app.js paid for it with five
  account-row comments cut; TestCoreScriptBudget is not raised.
- docs/subsystems/agent-wiring.md says which changes restart the app.

Known edge: a takeover flip in the same 3s tick as a Connect is taken
as the Connect's (restarted), since the route changed by the user.

Run at the pushed head (on mote, rebased on b967b1620; then rebased on 2a19043af, a Library change touching none of these files, with the core budget checked again: 160 bytes under):
- gofmt -l clean; GOOS=linux (-tags nogui) and GOOS=windows go vet of
  provider, gui, davsync clean.
- go test -count=1 -timeout 45m ./internal/provider ./internal/davsync
  ./internal/backup: ok. ./internal/gui: ok except
  TestMainWindowCorners/macOS_26_SDK, red alone on origin/main 694f4a6d6
  too (#3949). ./internal/cli: ok except TestEveryRouteHasACommandOrIsNamed
  on GET /api/context/reply (#5026).
- GUI (chromium + webkit, 1100 and 420 wide, en/zh/ja/de):
  restart-app (new), switch-only, claude-switch-only, keep-login,
  codex-accounts-via, account-arrange, i18n-keys: 110/110 and 94/94.
  account-arrange's webkit case went red once in a 5-file run on an
  aborted /api/lanes request; it passes alone on origin/main and at
  this head.

Broken by hand:
- codexAppStep's guard turned off: TestCodexAppLeftRunningForMagpiesOwnChanges
  and TestCodexAppFirstLookLeftRunning go red (ended [60]).
- SwitchWhenSpent marking its switch as the user's: TestCodexSwitchedWhenUsedUp
  goes red ("magpie's own switch is counted the user's").

Not tried: a real ChatGPT desktop app on a real used-up account (the
app-server end is stubbed as before); Windows, where the app is quit and
reopened (CodexAppReopen runs only after an end, so leaving it running
skips it too); no CLI command for the tick (switch-only has none either).
This commit is contained in:
yetone
2026-11-03 16:34:30 +08:00
parent 2a19043afc
commit 1dead5dc7b
19 changed files with 378 additions and 52 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -829,7 +829,7 @@ func hashes(b backup.Bundle) map[string]string {
}
ps := slices.Clone(b.Providers)
for i := range ps { // this computer's own: kept by Mirror, never synced
ps[i].KeepLogin, ps[i].KeepLoginAs, ps[i].SwitchOnly = false, "", false
ps[i].KeepLogin, ps[i].KeepLoginAs, ps[i].SwitchOnly, ps[i].RestartApp = false, "", false, false
}
providers := []any{ps, b.Icons, b.Groups}
if b.Searches != nil && len(*b.Searches) > 0 { // as before them, without one
+1 -1
View File
@@ -13,7 +13,7 @@ import (
func TestKeepLoginIsNoChange(t *testing.T) {
p := provider.Provider{ID: "codex", Name: "Codex"}
home := backup.Bundle{Providers: []provider.Provider{p}}
p.KeepLogin, p.KeepLoginAs, p.SwitchOnly = true, "work@example.com", true
p.KeepLogin, p.KeepLoginAs, p.SwitchOnly, p.RestartApp = true, "work@example.com", true, true
office := backup.Bundle{Providers: []provider.Provider{p}}
if hashes(home)["providers"] != hashes(office)["providers"] {
t.Fatal("the account kept signed in changed the providers hash")
+2 -2
View File
@@ -2728,8 +2728,8 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.acc + .acc, .accts .signing { border-top: 1px solid var(--line-2); }
/* every row of the box ruled off from the one above it, a setting's too
(the owner, 10-29: Add another sat unruled under Only switch) */
.accts > :is(.keep-login, .switch-only, .pool-ends) + .acc { border-top: 1px solid var(--line-2); }
.editor .accts .keep-login, .editor .accts .switch-only, .editor .accts .pool-ends { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; min-height: 34px; padding: 6px 11px; font-size: 12px; border-top: 1px solid var(--line-2); }
.accts > :is(.keep-login, .switch-only, .restart-app, .pool-ends) + .acc { border-top: 1px solid var(--line-2); }
.editor .accts .keep-login, .editor .accts .switch-only, .editor .accts .restart-app, .editor .accts .pool-ends { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; min-height: 34px; padding: 6px 11px; font-size: 12px; border-top: 1px solid var(--line-2); }
.editor .accts .keep-login .keep-as { max-width: 240px; }
/* Claude Code's interactive mode or -p, with why (claudeModeRow) */
.claude-mode { display: contents; }
+9 -13
View File
@@ -13064,9 +13064,7 @@ function renderAccounts(a, p) {
const list = el("div", "accts");
const ls = loginsInOrder(a, p);
if (p) list.dataset.provider = p.id, list.classList.toggle("weighted", (draft?.routing ?? (p.routing || "")) === "weight");
// a Claude account whose sign-in Anthropic refused, or that has none,
// can't be used till it is signed in again; another subscription's lapse
// shows on its quota line only, as before
// a Claude account refused or with no sign-in waits to sign in again
const unusable = (l) => a.agent === "claude" && !!l.lapsed;
// one whose sign-in its vendor refused (a plugin's, #1363; Copilot's
// revoked token; #1793's token_revoked) keeps Sign in again and Remove
@@ -13185,10 +13183,7 @@ function renderAccounts(a, p) {
out.onclick = () => askSignOutLogin(a, l);
line.append(out);
} else if (a.agent === "codex" || a.agent === "claude" && ls.some((o) => o !== l && !o.token)) {
// the agent is signed in to another of its accounts first, then
// this one goes (ForgetLogin), rather than Codex signed out or the
// removal refused (#4532); Claude Code's only one it can be signed
// in to has no Remove: magpie never signs it out
// switched to another first, then removed (ForgetLogin, #4532)
line.append(forgetOf(t("{agent} is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched", { agent: a.agentName })));
}
} else {
@@ -13239,15 +13234,11 @@ function renderAccounts(a, p) {
if (amBox) row.append(amBox);
list.append(row);
}
// magpie signs Codex or Claude Code in to the next account when the
// first runs low (#209, #408); this keeps it on the first instead, or on
// an account of the user's choosing, the gateway still spreading requests
// over the ticked ones in their order (#524)
// one account (#209, #408, #524)
if ((a.agent === "codex" || a.agent === "claude") && several && p && !p.switchOnly) {
const box = el("div", "keep-login");
const [keep, cb] = tick(t("Keep {agent} signed in to", { agent: a.agentName }), !!p.keepLogin);
keep.title = t("magpie won't sign {agent} in to another account when the first runs low; requests through magpie still go to the other ticked accounts as Routing says", { agent: a.agentName });
// the app's own menu, as every other pick in it, not a native select
let keepAs = kept;
const opts = [{ v: "", name: t("the first account"), note: "", literalName: true }];
for (const l of ls) if (!l.lapsed) opts.push({ v: l.user, name: l.user, note: "", literalName: true });
@@ -13265,7 +13256,6 @@ function renderAccounts(a, p) {
: keepAs ? t("{agent} stays signed in to {user}", { agent: a.agentName, user: keepAs }) : t("{agent} stays signed in to the first account", { agent: a.agentName }));
};
cb.onchange = () => post(cb.checked);
// picking one keeps it so, ticked or not
as.onclick = (e) => {
e.stopPropagation();
if (as.classList.contains("open")) return closeProtoMenu();
@@ -13291,6 +13281,12 @@ function renderAccounts(a, p) {
cb.onchange = () => accountAction("provider/switchonly", { id: p.id, switchOnly: cb.checked }, cb.checked ? on : off);
list.append(el("div", "switch-only", only));
}
if (p && cx && (several || p.restartApp)) {
const [re, cb] = tick(t("Restart the {agent} app when magpie switches its account", ag), !!p.restartApp);
re.title = t("Off, the {agent} app stays on its account until you restart it.", ag);
cb.onchange = () => accountAction("provider/restartapp", { id: p.id, restartApp: cb.checked }, t(cb.checked ? "magpie restarts the {agent} app when it switches accounts" : "magpie leaves the {agent} app running when it switches accounts", ag));
list.append(el("div", "restart-app", re));
}
// how a pool ends at its caps (plugins#349)
const capped = (l) => accountCapOf(p, l.user) || windowCapsOf(p, l.user);
if (p && (ls.some(capped) || p.capStop || p.capCareful)) {
+16
View File
@@ -1808,6 +1808,10 @@ const I18N = {
"Keep {agent} signed in to the first account": "{agent} 始终登录首选账号",
"Keep {agent} signed in to": "{agent} 始终登录",
"Only switch {agent}'s sign-in": "只切换 {agent} 的登录",
"Restart the {agent} app when magpie switches its account": "magpie 切换账号时自动重启 {agent} 应用",
"Off, the {agent} app stays on its account until you restart it.": "关闭时,{agent} 应用会停留在原来的账号上,直到你重启它。",
"magpie restarts the {agent} app when it switches accounts": "magpie 切换账号时会重启 {agent} 应用",
"magpie leaves the {agent} app running when it switches accounts": "magpie 切换账号时不再重启 {agent} 应用",
"Switch accounts only": "仅切换账号",
"Switch accounts only: {agent} is signed in as {user}. Pick another of its accounts to sign {agent} in to it, without connecting it to magpie.": "仅切换账号:{agent} 当前登录的是 {user}。选另一个账号,即可把 {agent} 切换过去,无需接入 magpie。",
"Not signed in": "未登录",
@@ -6324,6 +6328,10 @@ const I18N = {
"Keep {agent} signed in to the first account": "{agent} 始終登入首選帳號",
"Keep {agent} signed in to": "{agent} 始終登入",
"Only switch {agent}'s sign-in": "只切換 {agent} 的登入",
"Restart the {agent} app when magpie switches its account": "magpie 切換帳號時自動重新啟動 {agent} 應用程式",
"Off, the {agent} app stays on its account until you restart it.": "關閉時,{agent} 應用程式會停留在原來的帳號上,直到你重新啟動它。",
"magpie restarts the {agent} app when it switches accounts": "magpie 切換帳號時會重新啟動 {agent} 應用程式",
"magpie leaves the {agent} app running when it switches accounts": "magpie 切換帳號時不再重新啟動 {agent} 應用程式",
"Switch accounts only": "僅切換帳號",
"Switch accounts only: {agent} is signed in as {user}. Pick another of its accounts to sign {agent} in to it, without connecting it to magpie.": "僅切換帳號:{agent} 目前登入的是 {user}。選另一個帳號,即可把 {agent} 切換過去,無需接入 magpie。",
"Not signed in": "未登入",
@@ -10816,6 +10824,10 @@ const I18N = {
"Keep {agent} signed in to the first account": "{agent} を最初のアカウントにサインインしたままにする",
"Keep {agent} signed in to": "{agent} のサインイン先を固定:",
"Only switch {agent}'s sign-in": "{agent} のサインインだけを切り替える",
"Restart the {agent} app when magpie switches its account": "magpie がアカウントを切り替えたら {agent} アプリを再起動する",
"Off, the {agent} app stays on its account until you restart it.": "オフのとき、{agent} アプリは再起動するまで元のアカウントのままです。",
"magpie restarts the {agent} app when it switches accounts": "magpie はアカウントを切り替えると {agent} アプリを再起動します",
"magpie leaves the {agent} app running when it switches accounts": "magpie はアカウントを切り替えても {agent} アプリを再起動しません",
"Switch accounts only": "アカウント切り替えのみ",
"Switch accounts only: {agent} is signed in as {user}. Pick another of its accounts to sign {agent} in to it, without connecting it to magpie.": "アカウント切り替えのみ:{agent} は {user} としてサインイン中です。別のアカウントを選ぶと、{agent} を magpie に接続せずにそのアカウントへ切り替えます。",
"Not signed in": "未サインイン",
@@ -15339,6 +15351,10 @@ const I18N = {
"Keep {agent} signed in to the first account": "{agent} beim ersten Konto angemeldet lassen",
"Keep {agent} signed in to": "{agent} angemeldet lassen bei",
"Only switch {agent}'s sign-in": "Nur die Anmeldung von {agent} wechseln",
"Restart the {agent} app when magpie switches its account": "{agent}-App neu starten, wenn magpie das Konto wechselt",
"Off, the {agent} app stays on its account until you restart it.": "Aus bleibt die {agent}-App beim bisherigen Konto, bis du sie neu startest.",
"magpie restarts the {agent} app when it switches accounts": "magpie startet die {agent}-App neu, wenn es das Konto wechselt",
"magpie leaves the {agent} app running when it switches accounts": "magpie lässt die {agent}-App laufen, wenn es das Konto wechselt",
"Switch accounts only": "Nur Konten wechseln",
"Switch accounts only: {agent} is signed in as {user}. Pick another of its accounts to sign {agent} in to it, without connecting it to magpie.": "Nur Konten wechseln: {agent} ist als {user} angemeldet. Wähle ein anderes seiner Konten, um {agent} dort anzumelden, ohne es mit magpie zu verbinden.",
"Not signed in": "Nicht angemeldet",
File diff suppressed because one or more lines are too long
+14 -4
View File
@@ -247,6 +247,9 @@ type providerJSON struct {
// Claude's, the accounts are kept to Claude Code's own sign-in and
// serve no request through magpie (myduso on Discord)
SwitchOnly bool `json:"switchOnly,omitempty"`
// RestartApp: magpie restarts the Codex app's app-server for an
// account change it makes by itself (provider.Provider.RestartApp)
RestartApp bool `json:"restartApp,omitempty"`
// CapStop and CapCareful: how its accounts end at their caps
// (plugins#349), set on their own with capstop and capcareful
CapStop bool `json:"capStop,omitempty"`
@@ -686,7 +689,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL,
Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)),
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate,
RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()),
AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM,
@@ -1969,9 +1972,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
in.RefreshEvery, in.AutoInclude = old.RefreshEvery, old.AutoInclude
in.KeepLogin = old.KeepLogin // set on its own, with keeplogin
in.KeepLoginAs = old.KeepLoginAs
in.SwitchOnly = old.SwitchOnly
in.CapStop, in.CapCareful = old.CapStop, old.CapCareful // capstop, capcareful
in.Off = old.Off // and this with off and on
in.SwitchOnly, in.RestartApp = old.SwitchOnly, old.RestartApp // switchonly, restartapp
in.CapStop, in.CapCareful = old.CapStop, old.CapCareful // capstop, capcareful
in.Off = old.Off // and this with off and on
if in.Contexts == nil {
in.Contexts = old.Contexts // a save that doesn't say
}
@@ -2202,6 +2205,13 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
return
}
agent.SyncCatalogSoon()
case "restartapp":
// the Codex app's app-server restarted for an account change
// magpie makes by itself, or left be (atom0964 on Discord)
if err := provider.SetRestartApp(in.ID, in.RestartApp); err != nil {
fail(rw, err)
return
}
case "capstop":
// a request ends at the accounts' caps, 429, or goes on to the
// fallbacks (plugins#349)
+120
View File
@@ -0,0 +1,120 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// atom0964 on Discord: with both of Codex's sign-in ticks off, magpie still
// restarted the Codex app (its app-server ended, which the ChatGPT app
// shows as an error and relaunches) whenever it switched Codex's account by
// itself. Now that is a tick of its own under Codex's accounts, off unless
// the user turns it on. Ticking it posts provider/restartapp, the redraw
// keeps it ticked, unticking posts it off; with one account it isn't shown.
// The page doesn't move. In English, Chinese, Japanese and German,
// Chromium and WebKit, at 1100 and 420 wide.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const codex = ({ restartApp = false, spare = true } = {}) => ({
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "", restartApp,
models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
account: {
agent: "codex", agentName: "Codex", user: "work@example.com", plan: "PLUS",
logins: [
{ user: "work@example.com", plan: "PLUS", active: true, on: true },
{ user: "spare@example.com", plan: "PRO", on: spare },
],
},
});
function serve(lang, first, posts) {
let list = [first];
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
const providers = () => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } });
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json(providers());
if (url.pathname === "/api/provider/restartapp") {
const body = route.request().postDataJSON();
posts.push(body);
list = [{ ...list[0], restartApp: body.restartApp }];
return json(providers());
}
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const label = {
en: "Restart the Codex app when magpie switches its account",
zh: "magpie 切换账号时自动重启 Codex 应用",
ja: "magpie がアカウントを切り替えたら Codex アプリを再起動する",
de: "Codex-App neu starten, wenn magpie das Konto wechselt",
};
const strings = [
"Restart the {agent} app when magpie switches its account",
"Off, the {agent} app stays on its account until you restart it.",
"magpie restarts the {agent} app when it switches accounts",
"magpie leaves the {agent} app running when it switches accounts",
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [1100, 420]) {
for (const lang of Object.keys(label)) {
const open = async (t, opts) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, codex(opts), posts));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "Codex" }).first().click();
await page.locator(".editor .acc").first().waitFor();
return { page, errors, posts };
};
test(`${engine} ${width} ${lang}: a tick has magpie restart the Codex app for its own switches`, async (t) => {
const { page, errors, posts } = await open(t, {});
const only = page.locator(".editor .accts .restart-app label");
assert.equal((await only.textContent()).trim(), label[lang]);
assert.ok(await only.getAttribute("title"), "it says what it does");
assert.equal(await only.locator("input").isChecked(), false);
if (lang === "en") {
const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings);
assert.deepEqual(missing, [], "every string has its translations");
}
await only.scrollIntoViewIfNeeded();
const box = await only.boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= width, `the tick fits across ${width}`);
const scrollers = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop).concat(document.scrollingElement.scrollTop));
const before = await scrollers();
await only.locator("input").click();
await page.waitForFunction(() => document.querySelector(".editor .accts .restart-app input")?.checked === true);
assert.deepEqual(posts, [{ id: "codex", restartApp: true }]);
assert.deepEqual(await scrollers(), before, "the page doesn't move");
await page.locator(".editor .accts .restart-app input").click();
await page.waitForFunction(() => document.querySelector(".editor .accts .restart-app input")?.checked === false);
assert.deepEqual(posts, [{ id: "codex", restartApp: true }, { id: "codex", restartApp: false }]);
assert.deepEqual(errors, []);
});
test(`${engine} ${width} ${lang}: restart-app is drawn ticked, and not at all with one account`, async (t) => {
const ticked = await open(t, { restartApp: true });
assert.equal(await ticked.page.locator(".editor .accts .restart-app input").isChecked(), true);
const one = await open(t, { spare: false });
assert.equal(await one.page.locator(".editor .accts .restart-app").count(), 0);
assert.deepEqual([...ticked.errors, ...one.errors], []);
});
}
}
}
+3 -2
View File
@@ -92,7 +92,8 @@ func RestoreGroups(gs []Group) error {
// from another computer: one not among them goes, one that came without
// keys keeps the keys it has here, and an access key or balance token it
// came without is kept too (KeepSecrets). Which account an agent is kept
// signed in to (KeepLogin, KeepLoginAs, SwitchOnly) is this computer's own:
// signed in to (KeepLogin, KeepLoginAs, SwitchOnly), and whether its app is
// restarted to follow (RestartApp), is this computer's own:
// one person signs in to a personal account at home and a work account at
// the office, and sync set each computer to the other's every day.
func Mirror(ps []Provider, gs []Group) error {
@@ -112,7 +113,7 @@ func Mirror(ps []Provider, gs []Group) error {
}
if h, ok := here[p.ID]; ok {
p = KeepSecrets(p, h, p.Key == "" && len(p.Keys) == 0)
p.KeepLogin, p.KeepLoginAs, p.SwitchOnly = h.KeepLogin, h.KeepLoginAs, h.SwitchOnly
p.KeepLogin, p.KeepLoginAs, p.SwitchOnly, p.RestartApp = h.KeepLogin, h.KeepLoginAs, h.SwitchOnly, h.RestartApp
} else {
p.KeepLoginAs = "" // an account signed in on the other computer
}
+31 -9
View File
@@ -266,6 +266,9 @@ var codexApp struct {
// switched: Codex's ChatGPT account changed since the app-servers were
// last listed (codexAppAccountSwitched)
switched bool
// auto: every switch since then magpie made by itself
// (SwitchWhenSpent), none the user made
auto bool
// spent: the app-servers are on an account used up, so a turn they
// left open can't be served by them any more: Codex was switched off
// it (SwitchWhenSpent, or by hand off one known held, noteCodexSwitch),
@@ -307,21 +310,23 @@ func CodexAppStuck() bool {
// one, listed ahead of the app's on the owner's Mac) or none when ps was
// slow, and then nothing was ended and the app stayed grey on the used-up
// account till the user restarted it (danzi002 on Discord).
func codexAppAccountSwitched() {
c := &codexApp
c.Lock()
defer c.Unlock()
c.switched = true
}
func codexAppAccountSwitched() { codexAppSwitched(false, false) }
// codexAppSpentSwitch is codexAppAccountSwitched for a switch off an
// account that was used up: a turn the app-server left open is restarted
// past too once it has gone quiet (codexTurnStuckAfter).
func codexAppSpentSwitch() {
func codexAppSpentSwitch() { codexAppSwitched(true, false) }
// codexAppSwitched notes a switch of Codex's account: spent, off one used
// up; byMagpie, made by magpie itself (SwitchWhenSpent), which restarts
// the app only with RestartApp on. One the user made among them restarts
// it all the same.
func codexAppSwitched(spent, byMagpie bool) {
c := &codexApp
c.Lock()
defer c.Unlock()
c.switched, c.spent = true, true
c.auto = byMagpie && (!c.switched || c.auto)
c.switched, c.spent = true, c.spent || spent
}
// KeepCodexAppOnItsProvider runs codexAppStep every codexAppEvery till
@@ -377,6 +382,23 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim
// quota ran out mid-turn would hold their restart, and the app's grey
// Send, for up to codexTurnWindow (xiaoq6285 on Discord)
into := changed && out && (!c.seen || !c.out)
// what changed magpie changed by itself: the used-up takeover in or
// out, and its own account switches. The ChatGPT app shows the end of
// its app-server as an error and relaunches (#4550), so that waits for
// the user to restart it unless they asked magpie to (RestartApp;
// atom0964 on Discord: both of Codex's sign-in ticks off, and magpie
// still restarted the app to switch accounts). A switch the user made,
// a Connect or a Disconnect is theirs, and restarts it.
byHand := c.switched && !c.auto || c.seen && c.route != route && c.out == out
if changed && !byHand && !codexRestartsApp() {
why := "magpie switched Codex's ChatGPT account"
if !c.switched {
why = "magpie became Codex's provider for its used-up account, or gave it back"
}
log.Printf("codex: %s; the Codex app's app-server is left running (Restart the Codex app to follow is off), and the app follows once it is restarted", why)
c.switched, c.auto = false, false
changed = false
}
if !changed {
c.seen, c.route, c.out = true, route, out
}
@@ -400,7 +422,7 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim
c.why = "where Codex's config sends it changed"
}
c.spent = c.spent || into
c.seen, c.route, c.out, c.switched = true, route, out, false
c.seen, c.route, c.out, c.switched, c.auto = true, route, out, false, false
c.stale, c.stuck = map[int]int{}, false
for _, p := range pids {
c.stale[p] = 0
+88 -3
View File
@@ -42,19 +42,22 @@ func stubCodexApp(t *testing.T) *codexAppStub {
t.Helper()
s := &codexAppStub{known: true, next: 100}
oldOn, oldList, oldEnd, oldTurn := CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunning
oldOpen, oldReopen, oldQuiet := CodexAppOpen, CodexAppReopen, codexSessionsQuiet
oldOpen, oldReopen, oldQuiet, oldRestarts := CodexAppOpen, CodexAppReopen, codexSessionsQuiet, codexRestartsApp
reset := func() {
codexApp.Lock()
codexApp.seen, codexApp.route, codexApp.stale, codexApp.stuck, codexApp.switched = false, "", nil, false, false
codexApp.seen, codexApp.route, codexApp.stale, codexApp.stuck, codexApp.switched, codexApp.auto = false, "", nil, false, false, false
codexApp.ended, codexApp.backBy, codexApp.spent, codexApp.why = nil, time.Time{}, false, ""
codexApp.Unlock()
}
t.Cleanup(func() {
CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunning = oldOn, oldList, oldEnd, oldTurn
CodexAppOpen, CodexAppReopen, codexSessionsQuiet = oldOpen, oldReopen, oldQuiet
CodexAppOpen, CodexAppReopen, codexSessionsQuiet, codexRestartsApp = oldOpen, oldReopen, oldQuiet, oldRestarts
reset()
})
reset()
// the user asked magpie to restart the app for its own changes too
// (RestartApp); TestCodexAppLeftRunningForMagpiesOwnChanges is without
codexRestartsApp = func() bool { return true }
// the app as tests find it: open, and never reopened
CodexAppOpen = func(context.Context) (bool, bool) { return true, true }
CodexAppReopen = func(context.Context) error {
@@ -1074,3 +1077,85 @@ func TestCodexSessionsQuietFor(t *testing.T) {
t.Fatal("a session last written 5 minutes ago: not quiet")
}
}
// With both of Codex's sign-in ticks off magpie switches Codex's ChatGPT
// account by itself (SwitchWhenSpent, and back at the reset), and becomes
// Codex's provider for a used-up account and gives it back. Ending the
// Codex app's app-server for any of them makes the ChatGPT app show an
// error and relaunch (#4550), which atom0964 on Discord could not turn
// off. Those leave the app running unless the user ticked RestartApp. A
// switch the user makes, and a Connect or Disconnect, still restart it.
func TestCodexAppLeftRunningForMagpiesOwnChanges(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
restarts := false
codexRestartsApp = func() bool { return restarts }
now := time.Now()
idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }
step := func() []int { return codexAppStep(context.Background(), now, idle) }
none := func(what string) {
t.Helper()
for range 2 {
if got := step(); got != nil {
t.Fatalf("%s: ended %v", what, got)
}
}
}
s.running = []int{60}
none("nothing changed")
codexAppSwitched(true, true)
none("magpie switched off the used-up account")
codexAppSwitched(false, true)
none("magpie switched back at the reset")
s.on = true
none("magpie became Codex's provider for the used-up account")
s.on = false
none("magpie gave Codex back its account")
// a switch the user made, alone or after one of magpie's
codexAppSwitched(false, true)
codexAppAccountSwitched()
if got := step(); !slices.Equal(got, []int{60}) {
t.Fatalf("switched by the user after magpie: ended %v, want [60]", got)
}
none("the new app-server read the account as it started")
codexAppAccountSwitched()
codexAppSwitched(false, true)
if got := step(); !slices.Equal(got, []int{100}) {
t.Fatalf("switched by the user, then magpie: ended %v, want [100]", got)
}
// a Connect: where Codex's config sends it changed, not by the takeover
s.route = "connected"
if got := step(); !slices.Equal(got, []int{101}) {
t.Fatalf("connected: ended %v, want [101]", got)
}
none("after the connect")
// ticked: magpie's own changes restart it as before
restarts = true
codexAppSwitched(true, true)
if got := step(); !slices.Equal(got, []int{102}) {
t.Fatalf("RestartApp on, magpie switched: ended %v, want [102]", got)
}
s.on = true
if got := step(); !slices.Equal(got, []int{103}) {
t.Fatalf("RestartApp on, magpie took over: ended %v, want [103]", got)
}
}
// At magpie's first look, an app opened before it on a used-up account
// was restarted at once; that is magpie's own change too, and waits for
// RestartApp.
func TestCodexAppFirstLookLeftRunning(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
codexRestartsApp = func() bool { return false }
now := time.Now()
s.running, s.on = []int{60}, true
for range 2 {
if got := codexAppStep(context.Background(), now, func() (int, time.Time) { return 0, now.Add(-time.Minute) }); got != nil {
t.Fatalf("first look on the used-up account: ended %v", got)
}
}
}
+6 -6
View File
@@ -164,7 +164,11 @@ const codexDaemonRecheck = 5 * time.Second
// noteCodexSwitch remembers, when Codex's account changes from one to
// another, the app-server left running on the one before.
func noteCodexSwitch(from, to string) {
func noteCodexSwitch(from, to string) { noteCodexSwitchBy(from, to, false) }
// noteCodexSwitchBy is noteCodexSwitch, byMagpie saying magpie made the
// switch by itself (switchLoginBy).
func noteCodexSwitchBy(from, to string, byMagpie bool) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// the Codex app's app-servers are found and restarted on
@@ -172,11 +176,7 @@ func noteCodexSwitch(from, to string) {
// A switch by hand off an account known held is one off a used-up
// account, as SwitchWhenSpent's is: a turn left open on it when quota
// ran out mid-turn is restarted past once quiet (xiaoq6285 on Discord)
if codexHeldKnown(from) {
codexAppSpentSwitch()
} else {
codexAppAccountSwitched()
}
codexAppSwitched(codexHeldKnown(from), byMagpie)
ps, err := listProcesses(ctx)
known := err == nil
codexDaemonMu.Lock()
+7 -3
View File
@@ -464,7 +464,7 @@ func SwitchWhenSpent(ctx context.Context, agent string) (string, error) {
}
// the first moved off, not one moved to on the way
r, _ := loginReturnOf(agent, from)
if err := switchLogin(agent, to); err != nil {
if err := switchLoginBy(agent, to, true); err != nil {
return "", err
}
if back {
@@ -483,12 +483,16 @@ func SwitchWhenSpent(ctx context.Context, agent string) (string, error) {
share, _ := loginSwitching(agent)
log.Printf("%s: %s has used %g%% or more of its allowance; signed it in to %s", agent, from, share, to)
if agent == "codex" {
codexAppSpentSwitch()
codexAppSwitched(true, true)
}
}
if agent == "codex" {
if was := CodexAppStale(); was != "" {
log.Printf("codex: the Codex app is still signed in to %s, and shows its limits, until its app-server is restarted once no Codex turn runs", was)
if codexRestartsApp() {
log.Printf("codex: the Codex app is still signed in to %s, and shows its limits, until its app-server is restarted once no Codex turn runs", was)
} else {
log.Printf("codex: the Codex app is still signed in to %s, and shows its limits, until it is restarted: magpie restarts it for a switch of its own only with \"Restart the Codex app to follow\" on", was)
}
}
}
// the models the agent is offered are the new account's plan's
+24
View File
@@ -65,6 +65,10 @@ func TestCodexSwitchedWhenUsedUp(t *testing.T) {
codexApp.switched, codexApp.spent = false, false
codexApp.Unlock()
})
// the sign-ins above were the user's switches, as if taken already
codexApp.Lock()
codexApp.switched, codexApp.spent, codexApp.auto = false, false, false
codexApp.Unlock()
if to := switched(); to != "spare@example.com" {
t.Fatalf("switched to %q", to)
}
@@ -76,6 +80,26 @@ func TestCodexSwitchedWhenUsedUp(t *testing.T) {
if !spent {
t.Fatal("the switch off a used-up account isn't marked spent for the Codex app")
}
// it is magpie's own: the Codex app is left running unless the user
// asked magpie to restart it (RestartApp; atom0964 on Discord)
codexApp.Lock()
auto := codexApp.auto
codexApp.Unlock()
if !auto {
t.Fatal("magpie's own switch is counted the user's: the Codex app would be restarted for it")
}
if codexRestartsApp() {
t.Fatal("the Codex app is restarted for magpie's own switches with RestartApp never set")
}
if err := SetRestartApp("codex", true); err != nil {
t.Fatal(err)
}
if !codexRestartsApp() {
t.Fatal("RestartApp set, and still not read")
}
if err := SetRestartApp("codex", false); err != nil {
t.Fatal(err)
}
var live codexAuth
readJSON(filepath.Join(home, ".codex", "auth.json"), &live)
if live.Tokens.RefreshToken != "r-spare" {
+7 -2
View File
@@ -1224,7 +1224,12 @@ func SwitchLogin(agent, user string) error {
return nil
}
func switchLogin(agent, user string) error {
func switchLogin(agent, user string) error { return switchLoginBy(agent, user, false) }
// switchLoginBy is switchLogin, byMagpie saying magpie made the switch by
// itself (SwitchWhenSpent) rather than the user: the Codex app is then
// restarted to follow it only when the user asked for that (RestartApp).
func switchLoginBy(agent, user string, byMagpie bool) error {
if pp, ok := pluginOfAgent(agent); ok {
return switchPluginLogin(pp, user)
}
@@ -1238,7 +1243,7 @@ func switchLogin(agent, user string) error {
}
from, err := switchSavedLogin(agent, user)
if err == nil && agent == "codex" && from != "" {
noteCodexSwitch(from, user)
noteCodexSwitchBy(from, user, byMagpie)
}
if err == nil && agent == "claude" {
// the account's own way out goes with it (#1807)
+4 -3
View File
@@ -18,12 +18,13 @@ func TestMirrorKeepsKeepLogin(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("PATH", h)
here := Provider{ID: "relay", Name: "Relay", Chat: "https://example.com/v1", Key: "sk-here",
KeepLogin: true, KeepLoginAs: "home@example.com"}
KeepLogin: true, KeepLoginAs: "home@example.com", RestartApp: true}
if err := Save(here); err != nil {
t.Fatal(err)
}
office := Provider{ID: "relay", Name: "Relay renamed", Chat: "https://example.com/v1", Key: "sk-here",
KeepLoginAs: "work@example.com", SwitchOnly: true}
// and whether the Codex app is restarted for magpie's own switches
fresh := Provider{ID: "other", Name: "Other", Chat: "https://example.org/v1", Key: "sk-other",
KeepLogin: true, KeepLoginAs: "work@example.com"}
if err := Mirror([]Provider{office, fresh}, nil); err != nil {
@@ -33,8 +34,8 @@ func TestMirrorKeepsKeepLogin(t *testing.T) {
if len(ps) != 2 {
t.Fatalf("providers: %+v", ps)
}
if got := ps[0]; got.Name != office.Name || !got.KeepLogin || got.KeepLoginAs != here.KeepLoginAs || got.SwitchOnly {
t.Fatalf("mirrored: name %q keepLogin %v as %q switchOnly %v, want the other's name and this computer's sign-in", got.Name, got.KeepLogin, got.KeepLoginAs, got.SwitchOnly)
if got := ps[0]; got.Name != office.Name || !got.KeepLogin || got.KeepLoginAs != here.KeepLoginAs || got.SwitchOnly || !got.RestartApp {
t.Fatalf("mirrored: name %q keepLogin %v as %q switchOnly %v restartApp %v, want the other's name and this computer's sign-in", got.Name, got.KeepLogin, got.KeepLoginAs, got.SwitchOnly, got.RestartApp)
}
if got := ps[1]; !got.KeepLogin || got.KeepLoginAs != "" {
t.Fatalf("new provider: keepLogin %v as %q, want kept on and no account from the other computer", got.KeepLogin, got.KeepLoginAs)
+11 -1
View File
@@ -166,6 +166,16 @@ type Provider struct {
// Code's own sign-in, which magpie still moves: the gateway serves no
// request on them (KeptToAgent; myduso on Discord).
SwitchOnly bool `json:"switchOnly,omitempty"`
// RestartApp, on Codex's subscription, has magpie restart the Codex
// app's own app-server when it changes Codex's account by itself: a
// switch off an account running out (SwitchWhenSpent) or back, and
// becoming Codex's provider for a used-up account or giving it back.
// The ChatGPT app shows an ended app-server as an error and relaunches
// (#4550), so it is off unless the user turns it on (atom0964 on
// Discord); the app then stays on its account until it is restarted,
// from the switch notice or by hand. A switch the user makes, and a
// Connect or Disconnect, restart it either way.
RestartApp bool `json:"restartApp,omitempty"`
// MaxConcurrency is how many requests may be out at the vendor at once
// on each of its keys or accounts (Discord, Lemon: a Codex account is
@@ -890,7 +900,7 @@ func withPicks(a, pk Provider) Provider {
func accountSettings(a, pk Provider) Provider {
a.PickedFrom, a.Delisted, a.DelistedAt = pk.PickedFrom, pk.Delisted, pk.DelistedAt
a.Models, a.Unlisted, a.Off, a.Fallback, a.Routing, a.Affinity, a.KeepLogin, a.KeepLoginAs, a.Contexts, a.Family = pk.Models, pk.Unlisted, pk.Off, pk.Fallback, pk.Routing, pk.Affinity, pk.KeepLogin, pk.KeepLoginAs, pk.Contexts, pk.Family
a.SwitchOnly = pk.SwitchOnly
a.SwitchOnly, a.RestartApp = pk.SwitchOnly, pk.RestartApp
a.Sink, a.NoModels, a.BestInFamily = pk.Sink, pk.NoModels, pk.BestInFamily
a.NativeCompaction = pk.NativeCompaction
a.PromptAsWritten = pk.PromptAsWritten
+32
View File
@@ -162,6 +162,38 @@ func SetSwitchOnly(id string, on bool) error {
return Save(*p)
}
// SetRestartApp has magpie restart the Codex app's app-server when it
// changes Codex's account by itself, or leave the app on its account till
// it is restarted (Provider.RestartApp).
func SetRestartApp(id string, on bool) error {
p, err := Find(id)
if err != nil {
return err
}
if p.ID != "codex" || p.Account == nil || p.Account.Agent != p.ID {
return fmt.Errorf("magpie restarts no app of %s's", p.Name)
}
p.RestartApp = on
return Save(*p)
}
// codexRestartsApp is whether the user had magpie restart the Codex app's
// app-server for a change it makes by itself (Provider.RestartApp). While
// providers.json can't be read it is unknown, and the app is left be: a
// restart missed is the user's to make, one made shows as a crash.
var codexRestartsApp = func() bool {
f, err := read()
if err != nil {
return false
}
for _, p := range f.Providers {
if p.ID == "codex" {
return p.RestartApp
}
}
return false
}
// SwitchOnly reports whether magpie only moves agent's own sign-in between
// its accounts, sending none of its requests through the gateway for
// account failover (Provider.SwitchOnly). While providers.json can't be