diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 04df6d995..33f9ef706 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13640,6 +13640,7 @@ function renderAccounts(a, p) { const pv = a.agent === "codex" ? providers || {} : {}; if (pv.codexDaemon) list.append(renderCodexDaemon(pv.codexDaemon)); if (pv.codexApp) list.append(renderCodexApp(pv.codexApp)); + if (pv.codexProjects) import("./codexprojects.js").then(() => list.append(codexProjectsNote(codexNote, accountAction)), () => {}); if (signing?.agent === a.agent) list.append(renderSigning(sub)); else { list.append(addRow(t(sub.single && sub.plugin ? "Sign in again" : sub.single ? "Sign in to another {name} account" : "Add another {name} account", { name: sub.name }), () => startSignIn(a.agent))); diff --git a/internal/gui/assets/codexprojects.js b/internal/gui/assets/codexprojects.js new file mode 100644 index 000000000..26c4a168c --- /dev/null +++ b/internal/gui/assets/codexprojects.js @@ -0,0 +1,15 @@ +// The notice under Codex's accounts when the open Codex app shows fewer +// projects than the accounts have (linsm66 on X): a switch while it ran +// loaded the new account's list from the app's memory, and a file written +// under it is lost. Quitting and opening it again brings them back, and +// magpie never quits it unasked. app.js imports this when the providers +// state says so (codexProjects), so the core doesn't carry it. + +window.codexProjectsNote = function (codexNote, accountAction) { + const box = codexNote("", t("The Codex app shows fewer projects than you have"), + t("Quit the Codex app and open it again to get your projects back. magpie shares them between your accounts while it is closed.")); + const ok = el("button", "text", t("Got it")); + ok.onclick = () => accountAction("codex/daemon/dismiss-projects", {}); + box.append(ok); + return box; +}; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 2f75d4a81..9a349fc98 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -878,6 +878,8 @@ const I18N = { "{app}'s own {agent}, started {when}: quit {app} and open it again.": "{when}启动的 {app} 自带的 {agent}:完全退出 {app} 再打开。", "A {agent} in a terminal, started {when}: quit it and start it again.": "{when}在终端里启动的 {agent}:退出后重新启动。", "Got it": "知道了", + "The Codex app shows fewer projects than you have": "Codex 应用显示的项目比你拥有的少", + "Quit the Codex app and open it again to get your projects back. magpie shares them between your accounts while it is closed.": "请退出 Codex 应用后重新打开,项目就会回来。magpie 会在它关闭时让你的各个账号共用同一份项目。", "In {agent}": "在 {agent} 里", "also for small background tasks": "也用于后台小任务", "the default tier": "默认档位", @@ -5920,6 +5922,8 @@ const I18N = { "{app}'s own {agent}, started {when}: quit {app} and open it again.": "{when}啟動的 {app} 內建的 {agent}:完全結束 {app} 再開啟。", "A {agent} in a terminal, started {when}: quit it and start it again.": "{when}在終端機裡啟動的 {agent}:結束後重新啟動。", "Got it": "知道了", + "The Codex app shows fewer projects than you have": "Codex 應用程式顯示的專案比你擁有的少", + "Quit the Codex app and open it again to get your projects back. magpie shares them between your accounts while it is closed.": "請結束 Codex 應用程式後重新開啟,專案就會回來。magpie 會在它關閉時讓你的各個帳號共用同一份專案。", "In {agent}": "在 {agent} 裡", "also for small background tasks": "也用於後臺小任務", "the default tier": "預設檔位", @@ -10927,6 +10931,8 @@ const I18N = { "{app}'s own {agent}, started {when}: quit {app} and open it again.": "{when}に起動した {app} 内蔵の {agent}:{app} を終了して開き直してください。", "A {agent} in a terminal, started {when}: quit it and start it again.": "{when}にターミナルで起動した {agent}:終了して起動し直してください。", "Got it": "了解", + "The Codex app shows fewer projects than you have": "Codex アプリに表示されるプロジェクトが、お持ちのものより少なくなっています", + "Quit the Codex app and open it again to get your projects back. magpie shares them between your accounts while it is closed.": "Codex アプリを終了してもう一度開くと、プロジェクトが戻ります。アプリが閉じている間、magpie がアカウント間でプロジェクトを共有します。", "In {agent}": "{agent} 内", "also for small background tasks": "小さなバックグラウンドタスクにも使用", "the default tier": "デフォルトの階層", @@ -15952,6 +15958,8 @@ const I18N = { "{app}'s own {agent}, started {when}: quit {app} and open it again.": "Das eigene {agent} von {app}, gestartet {when}: {app} beenden und wieder öffnen.", "A {agent} in a terminal, started {when}: quit it and start it again.": "Ein {agent} im Terminal, gestartet {when}: beenden und neu starten.", "Got it": "Verstanden", + "The Codex app shows fewer projects than you have": "Die Codex-App zeigt weniger Projekte, als Sie haben", + "Quit the Codex app and open it again to get your projects back. magpie shares them between your accounts while it is closed.": "Beenden Sie die Codex-App und öffnen Sie sie erneut, dann sind Ihre Projekte wieder da. magpie teilt sie zwischen Ihren Konten, solange die App geschlossen ist.", "In {agent}": "In {agent}", "also for small background tasks": "auch für kleine Hintergrundaufgaben", "the default tier": "die Standardstufe", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 9c8f5128c..dbc93e344 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -702,6 +702,9 @@ type providersJSON struct { // after Codex was switched to another, until it is quit and opened // again (provider.CodexAppStale) CodexApp string `json:"codexApp,omitempty"` + // CodexProjects says the open Codex app shows fewer projects than + // Codex's accounts have, after a switch (provider.CodexAppProjectsShort) + CodexProjects bool `json:"codexProjects,omitempty"` // Plugins are the providers the plugins sign in to, for the add sheet Plugins []pluginSubJSON `json:"plugins"` // OnPlugins are the built-in subscriptions moved onto their plugins, @@ -1406,6 +1409,7 @@ func providersState() providersJSON { s.Gateway.Archive = archiveState() s.CodexDaemon = provider.CodexDaemonStale() s.CodexApp = provider.CodexAppStale() + s.CodexProjects = provider.CodexAppProjectsShort() s.Plugins = pluginSubs() s.Fetching = provider.FetchingNew() return s @@ -2973,6 +2977,8 @@ func providerRoutes(mux *http.ServeMux, w Windows) { provider.DismissCodexDaemon() case "dismiss-app": provider.DismissCodexApp() + case "dismiss-projects": + provider.DismissCodexAppProjects() 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) diff --git a/internal/gui/tests/codex-app-projects-short.test.cjs b/internal/gui/tests/codex-app-projects-short.test.cjs new file mode 100644 index 000000000..c8e322061 --- /dev/null +++ b/internal/gui/tests/codex-app-projects-short.test.cjs @@ -0,0 +1,88 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A switch while the Codex app runs shows the new account's projects from +// the app's memory, and none when they were never shared (linsm66 on X). +// magpie never quits the app unasked: Codex's accounts say the app shows +// fewer projects than there are, and that quitting and opening it again +// brings them back, until "Got it" is clicked. 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"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const codex = { + id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "smart", + models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { + agent: "codex", agentName: "Codex", user: "spare@example.com", plan: "PLUS", + logins: [ + { user: "spare@example.com", plan: "PLUS", active: true, on: true }, + { user: "spent@example.com", plan: "PLUS", on: true }, + ], + }, +}; + +function serve(lang, posted) { + let short = true; + const providers = () => ({ providers: [codex], presets: [], excluded: [], gateway: { running: true, window: true }, ...(short ? { codexProjects: true } : {}) }); + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + 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/codex/daemon/dismiss-projects") { posted.push(url.pathname); short = false; 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 keys = [ + "The Codex app shows fewer projects than you have", + "Quit the Codex app and open it again to get your projects back. magpie shares them between your accounts while it is closed.", + "Got it", +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [900, 480]) { + test(`${engine} ${lang} ${width}px: Codex's accounts say the open app shows fewer projects`, 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); + page.setDefaultNavigationTimeout(60000); + 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 text = await box.textContent(); + if (lang === "en") assert.match(text, /Quit the Codex app and open it again/); + else { + const missing = await page.evaluate(([l, ks]) => ks.filter((k) => !I18N[l][k]), [lang, keys]); + assert.deepEqual(missing, [], `every string has its ${lang}`); + assert.doesNotMatch(text, /Quit the Codex app/); + } + assert.equal(await box.locator("button").count(), 1, "only Got it: magpie quits nothing"); + 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(); + await box.waitFor({ state: "detached" }); + assert.deepEqual(posted, ["/api/codex/daemon/dismiss-projects"]); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index ecda57470..44fea2c05 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -173,9 +173,10 @@ test("compat.js is the first of the page's own scripts", async () => { // plugincounts.js (Discover's counts) when the Plugins page loads; // navicons.js (the sidebar lists' marks) with the first list drawn; // autoswitchtip.js when a provider's accounts draw their switch; + // codexprojects.js when the open Codex app shows fewer projects; // the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/provider/codex_projects.go b/internal/provider/codex_projects.go index b6ffe71e0..a25a6ea83 100644 --- a/internal/provider/codex_projects.go +++ b/internal/provider/codex_projects.go @@ -825,7 +825,125 @@ func codexProjectsStep(ctx context.Context) { return } if open, known := codexAppOpenNow(ctx); !known || open { + if open { + codexProjectsLook(codexHome()) + } return // carried once it is closed: what it has open it writes over } + codexProjectsClosed() CodexAppClosed() } + +// codexProjectsShort says whether the Codex app, open, shows fewer +// projects than its identities have together: the folders of the owner's +// local projects (the identity the app is on, whose list is the file's +// own) against those parked under the other identities. owner is that +// identity's key; ok is false when the file isn't the shape magpie knows +// or has no per-identity state. +func codexProjectsShort(home string) (owner string, short, ok bool) { + raw, err := os.ReadFile(codexGlobalStatePath(home)) + if err != nil { + return "", false, false + } + var top map[string]json.RawMessage + if json.Unmarshal(raw, &top) != nil || top == nil { + return "", false, false + } + var r struct { + Owner *string `json:"owner"` + Inactive map[string]json.RawMessage `json:"inactive"` + } + if rs, has := top[codexRendererKey]; !has || json.Unmarshal(rs, &r) != nil || r.Owner == nil || *r.Owner == "" { + return "", false, false + } + folders := func(g map[string]json.RawMessage) (map[string]bool, bool) { + lp, _, err := codexLocalProjects(g) + if err != nil { + return nil, false + } + out := map[string]bool{} + for _, p := range lp { + if k := codexRootKey(p); k != "" { + out[k] = true + } + } + return out, true + } + mine, good := folders(top) + if !good { + return "", false, false + } + for h, v := range r.Inactive { + if h == *r.Owner { + continue + } + var s struct { + Globals map[string]json.RawMessage `json:"globals"` + } + if json.Unmarshal(v, &s) != nil { + return "", false, false + } + theirs, good := folders(s.Globals) + if !good { + return "", false, false + } + for k := range theirs { + if !mine[k] { + short = true + } + } + } + return *r.Owner, short, true +} + +// codexProjectsHint is whether the open Codex app has been left showing +// fewer projects than its identities have, after the account it is on +// changed (a switch while it ran: it loads the new identity's list from +// memory, and a file written under it is lost). A project the user +// removed on the account they are on is no switch, and says nothing. +var codexProjectsHint struct { + sync.Mutex + owner string + short bool + hushed bool +} + +// codexProjectsLook is one look at the open app's file, from the loop. +func codexProjectsLook(home string) { + owner, short, ok := codexProjectsShort(home) + codexProjectsHint.Lock() + defer codexProjectsHint.Unlock() + h := &codexProjectsHint + switch { + case !ok: + return + case h.owner != "" && owner != h.owner: + h.short, h.hushed = short, false // the app changed account + case !short: + h.short = false + } + h.owner = owner +} + +// codexProjectsClosed forgets the hint: a closed app is shared and loads +// every identity's projects as it opens. +func codexProjectsClosed() { + codexProjectsHint.Lock() + codexProjectsHint.owner, codexProjectsHint.short, codexProjectsHint.hushed = "", false, false + codexProjectsHint.Unlock() +} + +// CodexAppProjectsShort says the open Codex app shows fewer projects than +// its accounts have, until it is quit and opened again. +func CodexAppProjectsShort() bool { + codexProjectsHint.Lock() + defer codexProjectsHint.Unlock() + return codexProjectsHint.short && !codexProjectsHint.hushed +} + +// DismissCodexAppProjects stops saying so. +func DismissCodexAppProjects() { + codexProjectsHint.Lock() + codexProjectsHint.hushed = true + codexProjectsHint.Unlock() +} diff --git a/internal/provider/codex_projects_test.go b/internal/provider/codex_projects_test.go index 701ebae8b..3e3ee234b 100644 --- a/internal/provider/codex_projects_test.go +++ b/internal/provider/codex_projects_test.go @@ -440,3 +440,80 @@ func anyStrings(v any) []string { } return out } + +// linsm66 on X: "为什么codex在触发自动更换账号后侧边栏已有的项目文件夹会消失呢". +// A switch while the Codex app runs loads the new account's list from the +// app's memory, so a list not shared before (the app never closed since) +// shows nothing, and a file written under the app is lost. magpie can't +// quit the app unasked; it says so, until the app is closed and shared. +func TestCodexAppProjectsShortAfterALiveSwitch(t *testing.T) { + home := t.TempDir() + t.Setenv("CODEX_HOME", home) + a, b := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b") + path := codexStateFixture(t, home, a, b) + t.Cleanup(codexProjectsClosed) + codexProjectsClosed() + + app := codexAppLaunch(t, path) + app.signIn(a) + app.save(t, path) + codexProjectsLook(home) + if CodexAppProjectsShort() { + t.Fatal("the app on the account that has the projects is short of none") + } + app.signIn(b) // the auto switch: auth.json, the app-server's restart + app.save(t, path) + codexProjectsLook(home) + if !CodexAppProjectsShort() { + t.Fatal("the app now shows b's empty list; magpie should say so") + } + DismissCodexAppProjects() + if CodexAppProjectsShort() { + t.Fatal("Got it should hush it") + } + // back on a: nothing is missing, and a hush is no more + app.signIn(a) + app.save(t, path) + codexProjectsLook(home) + if CodexAppProjectsShort() { + t.Fatal("a has every project") + } + // the app closed and shared: a switch then loses nothing + codexProjectsClosed() + if _, err := shareCodexProjects(home, [][]byte{a, b}, filepath.Join(t.TempDir(), "r.json")); err != nil { + t.Fatal(err) + } + app = codexAppLaunch(t, path) + app.signIn(a) + app.save(t, path) + codexProjectsLook(home) + app.signIn(b) + app.save(t, path) + codexProjectsLook(home) + if CodexAppProjectsShort() { + t.Fatal("b has the shared list; nothing is missing") + } +} + +// A project the user removed on the account they are on is not a switch. +func TestCodexAppProjectsRemovedByHandIsNoHint(t *testing.T) { + home := t.TempDir() + t.Setenv("CODEX_HOME", home) + a, b := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b") + path := codexStateFixture(t, home, a, b) + t.Cleanup(codexProjectsClosed) + codexProjectsClosed() + // b parked with a folder a doesn't have + var st map[string]any + bs, _ := os.ReadFile(path) + _ = json.Unmarshal(bs, &st) + inact := st[codexRendererKey].(map[string]any)["inactive"].(map[string]any) + inact[codexRendererOwner(b)].(map[string]any)["globals"] = map[string]any{"local-projects": map[string]any{ + "p-x": map[string]any{"id": "p-x", "rootPaths": []string{"/Users/me/x"}}}} + bs, _ = json.Marshal(st) + _ = os.WriteFile(path, bs, 0o644) + codexProjectsLook(home) // short, but the first look is no switch + if CodexAppProjectsShort() { + t.Fatal("no switch seen, no hint") + } +}