diff --git a/internal/agent/codex_app.go b/internal/agent/codex_app.go index 4efdb585d..57ce2282f 100644 --- a/internal/agent/codex_app.go +++ b/internal/agent/codex_app.go @@ -67,3 +67,35 @@ func reopenApp(ctx context.Context, a *Agent, bundle string) error { } return restartAppServer(ctx, bundle) } + +// What the Restart on Codex's "the Codex app is still signed in as" notice +// says when it didn't go through (tNotice). +var ( + noticeSwitchAppGone = newNotice("The {agent} app isn't running any more. It opens on the new account.") + noticeSwitchAppNoEnd = newNotice("magpie couldn't restart the {agent} app's app-server. Quit the app and open it again.") + noticeSwitchAppNotBack = newNotice("The {agent} app's app-server ended, but the app didn't start another. Quit the app and open it again.") + noticeSwitchAppUnknown = newNotice("magpie couldn't tell whether the {agent} app restarted. Quit the app and open it again.") +) + +// restartSwitchedApp restarts the Codex app's app-server; a var so tests +// don't end a real one. +var restartSwitchedApp = provider.RestartSwitchedCodexApp + +// RestartSwitchedCodexApp restarts the Codex desktop app's app-server +// after Codex's account was switched, so the app is on the new account +// (provider.RestartSwitchedCodexApp), and says in the reader's language +// what went wrong when it didn't. +func RestartSwitchedCodexApp(ctx context.Context) error { + err := restartSwitchedApp(ctx) + switch { + case err == nil: + return nil + case errors.Is(err, provider.ErrCodexAppGone): + return errors.New(noticeSwitchAppGone.say("agent", "Codex")) + case errors.Is(err, provider.ErrCodexAppNoEnd): + return errors.New(noticeSwitchAppNoEnd.say("agent", "Codex")) + case errors.Is(err, provider.ErrCodexAppNotBack): + return errors.New(noticeSwitchAppNotBack.say("agent", "Codex")) + } + return errors.New(noticeSwitchAppUnknown.say("agent", "Codex")) +} diff --git a/internal/agent/codex_app_test.go b/internal/agent/codex_app_test.go index bb4f64934..abe5a7e38 100644 --- a/internal/agent/codex_app_test.go +++ b/internal/agent/codex_app_test.go @@ -9,6 +9,8 @@ import ( "strings" "testing" "time" + + "github.com/yetone/magpie/internal/provider" ) // The Codex app's Restart restarts only the app-server of the app the row @@ -67,3 +69,30 @@ func TestCodexAppReopen(t *testing.T) { t.Fatalf("failed restart: %v, did %v", err, did) } } + +// The Restart on Codex's "the Codex app is still signed in as" notice says +// what went wrong in a notice the GUI translates, and an error it doesn't +// know (a failed listing) is "couldn't tell", never success. +func TestRestartSwitchedCodexAppSays(t *testing.T) { + old := restartSwitchedApp + t.Cleanup(func() { restartSwitchedApp = old }) + for _, c := range []struct { + err error + want notice + }{ + {provider.ErrCodexAppGone, noticeSwitchAppGone}, + {provider.ErrCodexAppNoEnd, noticeSwitchAppNoEnd}, + {provider.ErrCodexAppNotBack, noticeSwitchAppNotBack}, + {errors.New("ps: timed out"), noticeSwitchAppUnknown}, + } { + restartSwitchedApp = func(context.Context) error { return c.err } + err := RestartSwitchedCodexApp(context.Background()) + if err == nil || err.Error() != c.want.say("agent", "Codex") { + t.Errorf("%v: said %v, want %q", c.err, err, c.want.say("agent", "Codex")) + } + } + restartSwitchedApp = func(context.Context) error { return nil } + if err := RestartSwitchedCodexApp(context.Background()); err != nil { + t.Fatal(err) + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 1b0c61a9d..f97c918da 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13431,10 +13431,8 @@ function renderAccounts(a, p) { return list; } -// renderCodexDaemon: Codex's background app-server read the sign-in when it -// started, so after a switch the Codex sessions that attach to it are still -// on the account before (user) until it restarts. magpie doesn't restart it -// unasked: that ends the Codex sessions running on it. +// renderCodexDaemon: Codex's background app-server, on the account before a +// switch (user); a restart ends its sessions, so only on a press function renderCodexDaemon(user) { const box = codexNote("", t("Codex's background service is still signed in as {user}", { user }), t("Restart it to use the new account. Running Codex sessions will be interrupted.")); @@ -13447,16 +13445,20 @@ function renderCodexDaemon(user) { return box; } -// renderCodexApp: the Codex desktop app reads the sign-in only when it -// opens, so after a switch it stays on the account before (user): it shows -// that account's limits and, once they are spent, sends in no thread. Only -// quitting and opening it again moves it; magpie doesn't quit it unasked. +// renderCodexApp: the Codex app, on the account before a switch (user) till +// its app-server restarts; Restart does it now, asked first (nb5p_hQ on X) function renderCodexApp(user) { const box = codexNote("", t("The Codex app is still signed in as {user}", { user }), t("It shows that account's usage limits until it is quit and opened again. Quit it and open it again to use the new account.")); const ok = el("button", "text", t("Got it")); ok.onclick = () => accountAction("codex/daemon/dismiss-app", {}); - box.append(ok); + const go = el("button", "text primary", t("Restart")); + go.onclick = async () => { + if (!(await confirmRestart(t("The Codex app"), t("Its app-server restarts and signs in to the new account; its window stays. A running turn stops.")))) return; + go.classList.add("busy"); + accountAction("codex/daemon/restart-app", {}, t("Codex app-server restarted"), true, tNotice); + }; + box.append(ok, go); return box; } @@ -13641,18 +13643,10 @@ function quotaError(err, q) { // it with (accessKeyCard, #1821): the card used to be left out unsaid if (/^this plan's usage is read with the account's access key: give its SecretId/.test(err)) return t("This plan's usage needs the account's SecretId and SecretKey — give them in the provider's settings"); if (/^this plan's usage is read with the account's access key/.test(err)) return t("This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings"); - // ZCode with no GLM Coding Plan and no Start Plan left: the account has - // nothing to spend, which is not a reading that failed (#1001). Both the - // built-in (zcodeStartQuota, internal/provider/zcode_start.go) and the - // plugin (NO_START, packages/zcode) put these words on the card — the - // same string, byte for byte — and neither names a way out: the - // "subscribe at …" wording is in the sign-in errors (zcodeSignedIn / - // signedIn), which never reach this card. So the action is said here, on - // the card. "has ended" would also be wrong for an account that never - // started one, hence "no free Start Plan". "could not be read" is the - // other one: that is a reading that failed. The match is anchored on the whole - // card sentence, so the sign-in errors — which name the address themselves — - // and "could not be read" are left alone. + // ZCode with no GLM Coding Plan and no Start Plan left: nothing to spend, + // not a failed read (#1001). The plugin's card (NO_START, packages/zcode) + // names no way out, so it is said here; anchored on the whole sentence so + // the sign-in errors and "could not be read" are left alone. if (/^this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started$/.test(err)) return t("ZCode: no GLM Coding Plan, and no free Start Plan — subscribe to a GLM Coding Plan to use this account"); // an OpenCode Go key's windows (planWindows, planquota.go): Go is the // subscribing member's, in their workspace, so a key from anyone else @@ -14408,7 +14402,7 @@ function runsOutText(w, when = resetClock) { // accountAction changes which account a provider uses, or which it has, // and leaves its editor open on the result. -async function accountAction(path, body, okMsg, confirmed = false) { +async function accountAction(path, body, okMsg, confirmed = false, say = (m) => m) { const key = path === "keys/remove" && providers?.providers?.find((p) => p.id === body.id)?.keyList?.find((k) => k.id === body.ref); if (!confirmed && (path === "login/forget" || path === "keys/remove") && !await confirmRemoval(body.user || key?.name || key?.masked || body.ref, "This account or key will stop being used for requests. You will need to add it again to use it.")) return false; @@ -14420,7 +14414,7 @@ async function accountAction(path, body, okMsg, confirmed = false) { saidMoved(okMsg); return true; } catch (e) { - if (!editorError(e.message, "err")) status(e.message, "err"); + if (!editorError(say(e.message), "err")) status(say(e.message), "err"); document.querySelector(".editor .busy")?.classList.remove("busy"); return false; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 6736cc690..d97de74fa 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1929,6 +1929,11 @@ const I18N = { "Restart": "重启", "Codex's background service restarted": "Codex 的后台服务已重启", "Codex app-server restarted": "Codex 的 app-server 已重启", + "Its app-server restarts and signs in to the new account; its window stays. A running turn stops.": "它的 app-server 会重启并登录新账号;窗口保持不变。正在运行的回合会停止。", + "The {agent} app isn't running any more. It opens on the new account.": "{agent} 应用已不在运行。再次打开时会使用新账号。", + "magpie couldn't restart the {agent} app's app-server. Quit the app and open it again.": "magpie 无法重启 {agent} 应用的 app-server。请退出应用并重新打开。", + "The {agent} app's app-server ended, but the app didn't start another. Quit the app and open it again.": "{agent} 应用的 app-server 已结束,但应用没有启动新的。请退出应用并重新打开。", + "magpie couldn't tell whether the {agent} app restarted. Quit the app and open it again.": "magpie 无法确认 {agent} 应用是否已重启。请退出应用并重新打开。", "Only its app-server restarts, for the new settings; its window stays. A running turn stops.": "只重启它的 app-server,以读取新设置;窗口保持不变。正在运行的回合会停止。", "Restart {agent}?": "重启 {agent}?", "magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.": "magpie 会退出 {agent} 并重新打开,让它读取新设置。其中正在运行的任务会停止。", @@ -6066,6 +6071,11 @@ const I18N = { "Restart": "重啟", "Codex's background service restarted": "Codex 的後臺服務已重啟", "Codex app-server restarted": "Codex 的 app-server 已重新啟動", + "Its app-server restarts and signs in to the new account; its window stays. A running turn stops.": "它的 app-server 會重新啟動並登入新帳號;視窗保持不變。正在執行的回合會停止。", + "The {agent} app isn't running any more. It opens on the new account.": "{agent} 應用已不在執行。再次打開時會使用新帳號。", + "magpie couldn't restart the {agent} app's app-server. Quit the app and open it again.": "magpie 無法重新啟動 {agent} 應用的 app-server。請結束應用並重新打開。", + "The {agent} app's app-server ended, but the app didn't start another. Quit the app and open it again.": "{agent} 應用的 app-server 已結束,但應用沒有啟動新的。請結束應用並重新打開。", + "magpie couldn't tell whether the {agent} app restarted. Quit the app and open it again.": "magpie 無法確認 {agent} 應用是否已重新啟動。請結束應用並重新打開。", "Only its app-server restarts, for the new settings; its window stays. A running turn stops.": "只重新啟動它的 app-server,以讀取新設定;視窗保持不變。正在執行的回合會停止。", "Restart {agent}?": "重新啟動 {agent}?", "magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.": "magpie 會結束 {agent} 並重新打開,讓它讀取新設定。其中正在執行的工作會停止。", @@ -10180,6 +10190,11 @@ const I18N = { "Restart": "再起動", "Codex's background service restarted": "Codex のバックグラウンドサービスを再起動しました", "Codex app-server restarted": "Codex の app-server を再起動しました", + "Its app-server restarts and signs in to the new account; its window stays. A running turn stops.": "app-server を再起動して新しいアカウントでサインインさせます。ウィンドウはそのままです。実行中のターンは止まります。", + "The {agent} app isn't running any more. It opens on the new account.": "{agent} アプリはもう実行されていません。次に開くと新しいアカウントを使います。", + "magpie couldn't restart the {agent} app's app-server. Quit the app and open it again.": "magpie は {agent} アプリの app-server を再起動できませんでした。アプリを終了して開き直してください。", + "The {agent} app's app-server ended, but the app didn't start another. Quit the app and open it again.": "{agent} アプリの app-server は終了しましたが、アプリが新しいものを起動しませんでした。アプリを終了して開き直してください。", + "magpie couldn't tell whether the {agent} app restarted. Quit the app and open it again.": "magpie は {agent} アプリが再起動したか確認できませんでした。アプリを終了して開き直してください。", "Only its app-server restarts, for the new settings; its window stays. A running turn stops.": "app-server だけを再起動して新しい設定を読み込ませます。ウィンドウはそのままです。実行中のターンは止まります。", "Restart {agent}?": "{agent} を再起動しますか?", "magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.": "magpie は {agent} を終了してから開き直し、新しい設定を読み込ませます。その中で実行中の作業は止まります。", @@ -14324,6 +14339,11 @@ const I18N = { "Restart": "Neu starten", "Codex's background service restarted": "Hintergrunddienst von Codex neu gestartet", "Codex app-server restarted": "App-Server von Codex neu gestartet", + "Its app-server restarts and signs in to the new account; its window stays. A running turn stops.": "Sein App-Server startet neu und meldet sich mit dem neuen Konto an; das Fenster bleibt offen. Ein laufender Turn wird angehalten.", + "The {agent} app isn't running any more. It opens on the new account.": "Die {agent}-App läuft nicht mehr. Beim nächsten Öffnen nutzt sie das neue Konto.", + "magpie couldn't restart the {agent} app's app-server. Quit the app and open it again.": "magpie konnte den App-Server der {agent}-App nicht neu starten. Beenden Sie die App und öffnen Sie sie erneut.", + "The {agent} app's app-server ended, but the app didn't start another. Quit the app and open it again.": "Der App-Server der {agent}-App wurde beendet, aber die App hat keinen neuen gestartet. Beenden Sie die App und öffnen Sie sie erneut.", + "magpie couldn't tell whether the {agent} app restarted. Quit the app and open it again.": "magpie konnte nicht feststellen, ob die {agent}-App neu gestartet wurde. Beenden Sie die App und öffnen Sie sie erneut.", "Only its app-server restarts, for the new settings; its window stays. A running turn stops.": "Nur sein App-Server startet neu, um die neuen Einstellungen zu lesen; das Fenster bleibt offen. Ein laufender Turn wird angehalten.", "Restart {agent}?": "{agent} neu starten?", "magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.": "magpie beendet {agent} und öffnet es erneut, damit es die neuen Einstellungen liest. Was darin gerade läuft, wird angehalten.", @@ -16664,6 +16684,10 @@ const NOTICES = [ "{agent} is still open; it may be asking something in its window. Answer it there, or quit it, then open it again.", "{agent} is still running. Quit it, then open it again.", "{agent} quit, but didn't open again. Open it yourself.", + "The {agent} app isn't running any more. It opens on the new account.", + "magpie couldn't restart the {agent} app's app-server. Quit the app and open it again.", + "The {agent} app's app-server ended, but the app didn't start another. Quit the app and open it again.", + "magpie couldn't tell whether the {agent} app restarted. Quit the app and open it again.", ]; // The active language: a ?locale= URL parameter wins, then the saved diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 4260b9532..935b4665a 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -2174,6 +2174,15 @@ func providerRoutes(mux *http.ServeMux, w Windows) { provider.DismissCodexDaemon() case "dismiss-app": provider.DismissCodexApp() + case "restart-app": + // the Codex app left on the account before: its app-server + // restarted now, after the user said yes (nb5p_hQ on X) + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute) + defer cancel() + if err := agent.RestartSwitchedCodexApp(ctx); err != nil { + fail(rw, err) + return + } default: http.NotFound(rw, r) return diff --git a/internal/gui/tests/codex-app-stale.test.cjs b/internal/gui/tests/codex-app-stale.test.cjs index 3769d52af..1056fafc0 100644 --- a/internal/gui/tests/codex-app-stale.test.cjs +++ b/internal/gui/tests/codex-app-stale.test.cjs @@ -4,7 +4,9 @@ // limits and, once they are spent, sends in no thread (CavillZhang on X). // Codex's accounts say so, with the account the app is on and what moves it // (quit and open it again), until the app reopens or "Got it" is clicked. -// In every language, Chromium and WebKit, wide and narrow. +// Its Restart (nb5p_hQ on X) asks first in magpie's own dialog, then has +// magpie restart the app's app-server; one that fails says why in the +// reader's language. In every language, Chromium and WebKit, wide and narrow. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -24,7 +26,9 @@ const codex = { }, }; -function serve(lang, posted) { +const notBack = "The Codex app's app-server ended, but the app didn't start another. Quit the app and open it again."; + +function serve(lang, posted, fail) { let app = "spent@example.com"; const providers = () => ({ providers: [codex], presets: [], excluded: [], gateway: { running: true, window: true }, ...(app ? { codexApp: app } : {}) }); const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; @@ -36,6 +40,12 @@ function serve(lang, posted) { if (url.pathname === "/api/state") return json(state); if (url.pathname === "/api/providers") return json(providers()); if (url.pathname === "/api/codex/daemon/dismiss-app") { posted.push(url.pathname); app = ""; return json(providers()); } + if (url.pathname === "/api/codex/daemon/restart-app") { + posted.push(url.pathname); + if (fail) return route.fulfill({ status: 500, json: { error: notBack } }); + app = ""; + 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({}); @@ -49,6 +59,12 @@ const keys = [ "The Codex app is still signed in as {user}", "It shows that account's usage limits until it is quit and opened again. Quit it and open it again to use the new account.", "Got it", + "Restart", + "Restart {agent}?", + "The Codex app", + "Its app-server restarts and signs in to the new account; its window stays. A running turn stops.", + "Codex app-server restarted", + "The {agent} app's app-server ended, but the app didn't start another. Quit the app and open it again.", ]; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -77,11 +93,71 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const fits = await box.evaluate((b) => [...b.querySelectorAll("*")].every((e) => e.getBoundingClientRect().right <= b.getBoundingClientRect().right + 0.5)); assert.ok(fits, "nothing in the notice runs past it"); assert.equal(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), true, "no sideways scroll"); - await box.locator("button").click(); + for (const b of await box.locator("button").all()) { + const r = await b.boundingBox(); + assert.ok(r.x >= 0 && r.x + r.width <= width, "a button past the window: " + JSON.stringify(r)); + } + await box.locator("button:not(.primary)").click(); await box.waitFor({ state: "detached" }); assert.deepEqual(posted, ["/api/codex/daemon/dismiss-app"]); assert.deepEqual(errors, []); }); + + test(`${engine} ${lang} ${width}px: Restart asks first, then restarts the Codex app's app-server`, async (t) => { + 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); + const errors = [], posted = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posted)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Codex" }).first().click(); + const box = page.locator(".editor .signing.daemon"); + await box.waitFor(); + const go = box.locator("button.primary"); + assert.equal((await go.textContent()).trim(), await page.evaluate((l) => (l === "en" ? "Restart" : I18N[l].Restart), lang)); + const ask = page.locator("dialog.action-confirm[open]"); + await go.click(); + await ask.waitFor(); + assert.doesNotMatch(await ask.textContent(), /\{\w+\}/); + const dlg = await ask.boundingBox(); + assert.ok(dlg.x >= 0 && dlg.x + dlg.width <= width, "the dialog past the window"); + await page.keyboard.press("Escape"); + await ask.waitFor({ state: "detached" }); + assert.deepEqual(posted, [], "Escape restarts nothing"); + await go.click(); + await ask.locator("button.primary").click(); + await box.waitFor({ state: "detached" }); + assert.deepEqual(posted, ["/api/codex/daemon/restart-app"]); + assert.deepEqual(errors, []); + }); } + + test(`${engine} ${lang}: a Restart that fails says why, in the reader's language`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = [], posted = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posted, true)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Codex" }).first().click(); + const box = page.locator(".editor .signing.daemon"); + await box.waitFor(); + await box.locator("button.primary").click(); + await page.locator("dialog.action-confirm[open] button.primary").click(); + const said = page.locator(".editor .editor-error"); + await said.waitFor(); + const text = (await said.textContent()).trim(); + assert.ok(text.includes("Codex"), text); + if (lang === "en") assert.ok(text.includes(notBack), text); + else assert.ok(!text.includes(notBack), "not translated: " + text); + assert.equal(await box.count(), 1, "the notice stays for another try"); + assert.equal(await box.locator("button.primary.busy").count(), 0, "not left spinning"); + assert.deepEqual(posted, ["/api/codex/daemon/restart-app"]); + assert.deepEqual(errors, []); + }); } } diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.go index 3f0c85b55..fbce7425c 100644 --- a/internal/provider/codex_app_server.go +++ b/internal/provider/codex_app_server.go @@ -492,3 +492,90 @@ func RestartCodexAppWhenIdle(ctx context.Context, wait time.Duration) (ended int } return ended, left, nil } + +// codexAppBackWait is how long RestartSwitchedCodexApp waits for the Codex +// app to start a new app-server after the old one ended; a var for tests. +var codexAppBackWait = 20 * time.Second + +// What RestartSwitchedCodexApp found when it couldn't restart the app's +// app-server; the agent package says each in the reader's language. +var ( + ErrCodexAppGone = errors.New("the Codex app isn't running") + ErrCodexAppNoEnd = errors.New("the Codex app's app-server couldn't be ended") + ErrCodexAppNotBack = errors.New("the Codex app didn't start another app-server") +) + +// RestartSwitchedCodexApp is the Restart on Codex's accounts' "the Codex +// app is still signed in as" notice (nb5p_hQ on X): it restarts the app's +// own app-servers now, as codexAppStep does once no Codex turn runs, so +// the app reads the account Codex was switched to; the user said yes to +// cutting a running turn short. Each is ended as a clean exit, which the +// app answers by starting another (its window, threads and drafts stay; +// quitting the app and opening it again opened a new window, yoshi037070); +// it is never killed, as the app shows a kill as a crash. It waits until +// the ended ones are gone and a new one runs, and errs when either doesn't +// happen in time: a listing that fails is unknown, never success. +func RestartSwitchedCodexApp(ctx context.Context) error { + home := codexHome() + list := func() ([]int, error) { + lctx, cancel := context.WithTimeout(ctx, codexAppListWait) + defer cancel() + return codexAppServersOn(lctx, home) + } + pids, err := list() + if err != nil { + return err + } + if len(pids) == 0 { + DismissCodexApp() + return ErrCodexAppGone + } + for _, p := range pids { + if err := endCodexAppServer(p); err != nil { + log.Printf("codex: restarting the Codex app's app-server %d for the account switched to: %v", p, err) + return ErrCodexAppNoEnd + } + } + // waitFor lists the app-servers until ok holds of them, for at most limit + waitFor := func(limit time.Duration, ok func([]int) bool) (bool, error) { + end := time.Now().Add(limit) + for { + now, err := list() + if err == nil && ok(now) { + return true, nil + } + if time.Now().After(end) { + return false, err + } + select { + case <-ctx.Done(): + return false, ctx.Err() + case <-time.After(200 * time.Millisecond): + } + } + } + gone, err := waitFor(codexAppGoneWait, func(now []int) bool { + return !slices.ContainsFunc(now, func(p int) bool { return slices.Contains(pids, p) }) + }) + if !gone { + if ctx.Err() != nil { + return ctx.Err() + } + if err != nil { + return err + } + return ErrCodexAppNoEnd + } + back, err := waitFor(codexAppBackWait, func(now []int) bool { return len(now) > 0 }) + if !back { + if ctx.Err() != nil { + return ctx.Err() + } + if err != nil { + return err + } + return ErrCodexAppNotBack + } + DismissCodexApp() + return nil +} diff --git a/internal/provider/codex_app_switch_restart_test.go b/internal/provider/codex_app_switch_restart_test.go new file mode 100644 index 000000000..14c5d767a --- /dev/null +++ b/internal/provider/codex_app_switch_restart_test.go @@ -0,0 +1,180 @@ +package provider + +import ( + "bufio" + "context" + "errors" + "os" + "slices" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// The Restart on the Codex app's "still signed in as" notice (nb5p_hQ on +// X) ends the app's app-servers now, a running turn or not, waits for +// the app to start another, and says so when it doesn't: none running, +// one that can't be ended or stays, none back, a listing that fails. +func TestRestartSwitchedCodexApp(t *testing.T) { + s := stubCodexApp(t) + oldGone, oldBack := codexAppGoneWait, codexAppBackWait + codexAppGoneWait, codexAppBackWait = 300*time.Millisecond, 300*time.Millisecond + t.Cleanup(func() { + codexAppGoneWait, codexAppBackWait = oldGone, oldBack + DismissCodexApp() + }) + ctx := context.Background() + + if err := RestartSwitchedCodexApp(ctx); !errors.Is(err, ErrCodexAppGone) { + t.Fatalf("no app running: %v", err) + } + + codexDaemonMu.Lock() + codexAppLeft = leftDaemon{pid: 7, user: "spent@x"} + codexDaemonMu.Unlock() + s.running, s.turnOpen = []int{7, 8}, true + if err := RestartSwitchedCodexApp(ctx); err != nil { + t.Fatal(err) + } + if !slices.Equal(s.ended, []int{7, 8}) { + t.Fatalf("ended %v, want both of the app's app-servers, a turn open or not (the user said yes)", s.ended) + } + codexDaemonMu.Lock() + left := codexAppLeft + codexDaemonMu.Unlock() + if left.user != "" { + t.Fatalf("still said to be on %q after its restart", left.user) + } + + s.endErr = proc.ErrDenied + if err := RestartSwitchedCodexApp(ctx); !errors.Is(err, ErrCodexAppNoEnd) { + t.Fatalf("denied: %v", err) + } + s.endErr = nil + + // one that doesn't end + endCodexAppServer = func(int) error { return nil } + if err := RestartSwitchedCodexApp(ctx); !errors.Is(err, ErrCodexAppNoEnd) { + t.Fatalf("one that stays: %v", err) + } + + // ended, and the app starts none: said, not success + endCodexAppServer = func(pid int) error { + s.running = slices.DeleteFunc(s.running, func(p int) bool { return p == pid }) + return nil + } + if err := RestartSwitchedCodexApp(ctx); !errors.Is(err, ErrCodexAppNotBack) { + t.Fatalf("none back: %v", err) + } + + // the listing fails: unknown, not success + s.running, s.listErr = []int{9}, errors.New("ps failed") + if err := RestartSwitchedCodexApp(ctx); err == nil || errors.Is(err, ErrCodexAppGone) { + t.Fatalf("a failed listing: %v", err) + } +} + +// TestCodexSwitchAppHelper is TestRestartSwitchedCodexAppReal's fake +// app-server: it waits to be ended. +func TestCodexSwitchAppHelper(t *testing.T) { + if os.Getenv("MAGPIE_CODEX_SWITCH_HELPER") != "1" { + return + } + os.Stdout.WriteString("running\n") + time.Sleep(30 * time.Second) +} + +// fakeCodexApp runs a real process as the Codex app's app-server, and +// starts another when it ends, as the app does; every one it started ends +// with the test. +type fakeCodexApp struct { + t *testing.T + mu sync.Mutex + pid int + started []int + back bool +} + +func (f *fakeCodexApp) start() { + ctx, cancel := context.WithCancel(context.Background()) + cmd := proc.CommandContext(ctx, os.Args[0], "-test.run=^TestCodexSwitchAppHelper$") + // TMPDIR is this test's: given no testenv.Marker, the helper makes a + // test home of its own there, which it never removes once ended + cmd.Env = []string{"MAGPIE_CODEX_SWITCH_HELPER=1", "TMPDIR=" + f.t.TempDir(), "HOME=" + f.t.TempDir()} + out, _ := cmd.StdoutPipe() + if err := cmd.Start(); err != nil { + cancel() + f.t.Error(err) // may run on the fake app's goroutine: no Fatal + return + } + done := make(chan struct{}) + f.t.Cleanup(func() { cancel(); <-done }) + if line, _ := bufio.NewReader(out).ReadString('\n'); line != "running\n" { + f.t.Errorf("the helper: %q", line) + cancel() + _ = cmd.Wait() + close(done) + return + } + pid := cmd.Process.Pid + f.mu.Lock() + f.pid = pid + f.started = append(f.started, pid) + f.mu.Unlock() + go func() { + _ = cmd.Wait() + f.mu.Lock() + if f.pid == pid { + f.pid = 0 + } + back := f.back && ctx.Err() == nil + f.mu.Unlock() + close(done) + if back { + // the app notices its app-server gone and starts another + time.Sleep(50 * time.Millisecond) + f.start() + } + }() +} + +// With a real process for the app-server, ended by proc.End as the +// Restart ends the real one, the Restart waits for the one the app starts +// next, and says so when the app starts none. +func TestRestartSwitchedCodexAppReal(t *testing.T) { + stubCodexApp(t) + oldGone, oldBack := codexAppGoneWait, codexAppBackWait + codexAppGoneWait, codexAppBackWait = 5*time.Second, 2*time.Second + t.Cleanup(func() { codexAppGoneWait, codexAppBackWait = oldGone, oldBack }) + f := &fakeCodexApp{t: t, back: true} + codexAppServersOn = func(context.Context, string) ([]int, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.pid == 0 { + return nil, nil + } + return []int{f.pid}, nil + } + endCodexAppServer = proc.End + f.start() + first := f.started[0] + if err := RestartSwitchedCodexApp(context.Background()); err != nil { + t.Fatal(err) + } + f.mu.Lock() + now := f.pid + f.mu.Unlock() + if now == 0 || now == first { + t.Fatalf("app-server %d after the restart, first %d: want a new one", now, first) + } + + // the app doesn't start another: said + f.mu.Lock() + f.back = false + f.mu.Unlock() + if err := RestartSwitchedCodexApp(context.Background()); !errors.Is(err, ErrCodexAppNotBack) { + t.Fatalf("none back: %v", err) + } +}