diff --git a/internal/agent/codex_app.go b/internal/agent/codex_app.go index baaaead2e..cf98ec376 100644 --- a/internal/agent/codex_app.go +++ b/internal/agent/codex_app.go @@ -156,3 +156,34 @@ func codexAppReopen(ctx context.Context) error { } return a.restartWin(ctx, codexWinApp, c) } + +// CodexAppInstalled says whether the Codex desktop app is installed here +// and magpie can open it: ChatGPT.app or Codex.app on macOS, the Store +// app on Windows. Linux's package has no launcher magpie starts. +func CodexAppInstalled() bool { + if !restartOnMac && !restartOnWindows { + return false + } + return (&Agent{ID: "codex"}).AppVersion() != "" +} + +// OpenCodexApp opens the Codex desktop app, which brings its window up +// when it is running already (Yink88564391 on X). On macOS it opens the +// bundle whose Info.plist says com.openai.codex; on Windows it starts the +// Store package's app by its AppUserModelID, as a restart does. +func OpenCodexApp(ctx context.Context) error { + switch { + case restartOnMac: + app := desktopApps["codex"] + for _, bundle := range macBundles(app) { + if info, ok := bundleInfo(bundle); ok && info.hasID && info.id == app.id { + return appOpen(ctx, bundle) + } + } + case restartOnWindows: + if CodexAppInstalled() { + return winLaunch(winProc{aumid: codexWinAUMID}) + } + } + return errors.New("the Codex app is not installed here") +} diff --git a/internal/agent/codex_app_open_test.go b/internal/agent/codex_app_open_test.go new file mode 100644 index 000000000..fe5747f5b --- /dev/null +++ b/internal/agent/codex_app_open_test.go @@ -0,0 +1,46 @@ +package agent + +import ( + "context" + "path/filepath" + "testing" +) + +// Codex's Open button (Yink88564391 on X): on a Mac it opens the bundle +// whose Info.plist says com.openai.codex, never the ChatGPT chat app's +// of the same name; on Windows it starts the Store package's app; with no +// app installed it opens nothing and says so. +func TestOpenCodexApp(t *testing.T) { + restartSandbox(t) + apps := filepath.Join(t.TempDir(), "Applications") + appFolders = func() []string { return []string{apps} } + var opened []string + appOpen = func(_ context.Context, b string) error { opened = append(opened, b); return nil } + var launched []winProc + winLaunch = func(p winProc) error { launched = append(launched, p); return nil } + + restartOnMac = true + if CodexAppInstalled() || OpenCodexApp(context.Background()) == nil || len(opened) != 0 { + t.Fatalf("no app installed, yet installed=%v opened=%q", CodexAppInstalled(), opened) + } + installApp(t, apps, "ChatGPT.app", codexAppPlist("com.openai.chat", "1.2026.280")) + if CodexAppInstalled() || OpenCodexApp(context.Background()) == nil || len(opened) != 0 { + t.Fatalf("the chat app taken for Codex's: opened %q", opened) + } + installApp(t, apps, "Codex.app", codexAppPlist("com.openai.codex", "26.930.31730")) + if !CodexAppInstalled() { + t.Fatal("Codex.app not seen") + } + if err := OpenCodexApp(context.Background()); err != nil || len(opened) != 1 || opened[0] != filepath.Join(apps, "Codex.app") { + t.Fatalf("opened %q (%v)", opened, err) + } + + // Linux has no launcher magpie starts + restartOnMac = false + if CodexAppInstalled() || OpenCodexApp(context.Background()) == nil { + t.Fatal("offered to open the app where magpie cannot") + } + if len(launched) != 0 { + t.Fatalf("launched %v off Windows", launched) + } +} diff --git a/internal/gui/agent_open_test.go b/internal/gui/agent_open_test.go index 7f3ede970..21391a06a 100644 --- a/internal/gui/agent_open_test.go +++ b/internal/gui/agent_open_test.go @@ -1,6 +1,7 @@ package gui import ( + "context" "encoding/json" "net/http" "net/http/httptest" @@ -122,3 +123,71 @@ func TestAgentCommandNeedsAProgram(t *testing.T) { t.Errorf("agy: %q", run) } } + +// Codex's Open button (Yink88564391 on X) opens the desktop app where one +// is installed and the setting codexOpen doesn't say terminal; the row menu's +// Open in terminal still opens the terminal; a value the setting can't +// take is refused. +func TestCodexOpenButton(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the stand-in codex is a POSIX script") + } + sandboxHome(t) + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "codex"), []byte("#!/bin/sh\necho codex-cli 0.1.0\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+"/usr/bin:/bin") + proc.Forget() + t.Cleanup(proc.Forget) + var apps, terms []string + wasApp, wasTerm := codexAppOpener, agentTerminal + t.Cleanup(func() { codexAppOpener, agentTerminal = wasApp, wasTerm }) + codexAppOpener = func(context.Context) error { apps = append(apps, "app"); return nil } + agentTerminal = func(run, label, choice string) error { terms = append(terms, run); return nil } + wasInst := codexAppInstalled + t.Cleanup(func() { codexAppInstalled = wasInst }) + codexAppInstalled = func() bool { return true } + + h := Handler(nil, nil) + post := func(path string, body any) int { + t.Helper() + b, _ := json.Marshal(body) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(string(b)))) + return rec.Code + } + row := func() agentJSON { + for _, a := range state().Agents { + if a.ID == "codex" { + return a + } + } + return agentJSON{} + } + + if !row().OpenApp { + t.Fatal("app installed and no choice, yet the Open button is not the app's") + } + if code := post("/api/agents/open", map[string]any{"agent": "codex"}); code != http.StatusNoContent || len(apps) != 1 { + t.Fatalf("Open: %d, apps %v", code, apps) + } + if code := post("/api/settings/codex-open", map[string]string{"open": "browser"}); code == http.StatusOK { + t.Fatal("an Open that opens a browser was accepted") + } + if code := post("/api/settings/codex-open", map[string]string{"open": "terminal"}); code != http.StatusOK { + t.Fatalf("terminal: %d", code) + } + if row().OpenApp { + t.Fatal("terminal chosen, yet the button is the app's") + } + post("/api/agents/open", map[string]any{"agent": "codex"}) + if len(apps) != 1 { + t.Fatalf("terminal chosen, yet the app opened: %v", apps) + } + post("/api/settings/codex-open", map[string]string{"open": "app"}) + post("/api/agents/open", map[string]any{"agent": "codex", "terminal": true}) + if len(apps) != 1 { + t.Fatalf("Open in terminal opened the app: %v", apps) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 2abb320c4..e12dff2ed 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -265,6 +265,9 @@ type agentJSON struct { // copies; Terminal: and opens in a terminal, this system having one Command string `json:"command,omitempty"` Terminal bool `json:"terminal,omitempty"` + // OpenApp: its Open button opens the desktop app, not a terminal + // (Codex, by the setting codexOpen, Yink88564391 on X) + OpenApp bool `json:"openApp,omitempty"` } // clientJSON is an agent, or another client the gateway knows, as a @@ -2190,6 +2193,20 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } writeJSON(rw, settingsState()) }) + // what the Open button of Codex's Agents row opens: "", "app" or + // "terminal" (Yink88564391 on X) + mux.HandleFunc("POST /api/settings/codex-open", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ Open string } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if err := provider.SetCodexOpen(in.Open); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) // Warm up now: one Codex or Claude account's warm-up sent at once, and // why it failed mux.HandleFunc("POST /api/warm-now", func(rw http.ResponseWriter, r *http.Request) { @@ -3240,6 +3257,7 @@ func state() stateJSON { // as agentCommand makes it, Launch asked once aj.Command = agentLine(a, aj.Launch, runtime.GOOS) aj.Terminal = terminalHere() && aj.Command != "" + aj.OpenApp = a.ID == "codex" && codexOpensApp() if a.Native != nil { native := a.Native.Read() aj.Native = &native diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 5ae47f41f..1429e0bbe 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -5045,6 +5045,12 @@ body.window .row + .row.agent.conn > .who { min-height: 41px; } /* the line abov .row.agent.conn > .field.launch + .field.ag-start { margin-left: 0; } .ag-add { flex: none; height: 24px; padding: 0 10px; border: 0; border-radius: 6px; background: var(--pill); color: var(--fg); font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; } .ag-add:hover { background: var(--pill-hover); } +.ag-openapp { flex: none; height: 24px; padding: 0 10px; border: 0; border-radius: 6px; background: var(--pill); color: var(--fg); font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; transition: background .15s ease, transform .12s cubic-bezier(.23, 1, .32, 1); } +.ag-openapp:hover { background: var(--pill-hover); } +.ag-openapp:active { transform: scale(.97); } +.ag-openapp:focus-visible { outline: 1.5px solid var(--accent); outline-offset: 1px; } +.row.agent.conn > .ag-openapp { margin-left: 8px; align-self: center; } +.row.agent.conn > .who + .ag-openapp { margin-left: auto; } .ag-cant { flex: none; font-size: 12px; color: var(--faint); } .ag-conn-gap { flex: none; width: 32px; margin-left: 10px; } .row.agent.conn.unplugged .ag-handle .ic { opacity: .7; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index e16b9f16c..3348396ac 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1573,6 +1573,7 @@ function connectRow(a, row, who, { fields, extras, fieldBtn, sw, kind }) { // only way it takes magpie: on the row, before the model const launch = a.wired && fields.querySelector(".field.launch"); if (launch) row.append(launch); + if (a.id === "codex" && (a.openApp || a.terminal) && !web) row.append(openButton(a)); if (start) row.append(startButton(a, start, fieldBtn)); // Claude Desktop's: which models its own menu lists else if (menuFromList(a)) row.append(menuButton(a)); @@ -3808,7 +3809,7 @@ function openAgentMenu(anchor, a, inFold, at) { const i = shown.findIndex((x) => x.id === a.id); const reapply = !a.cliMissing && (a.drift || a.fields.some((f) => optionFor(f, f.value)?.ref)); // coolmantou, lileo0668 - const o = a.terminal && mode != "panel" && !web, term = [...o ? [{ name: "Open in terminal", icon: LAUNCH_GLYPH, sep: !0, run: () => api("agents/open", { agent: a.id }).catch(statusErr) }] : [], ...a.command ? [{ name: "Copy launch command", icon: COPY_ICON, sep: !o, run: () => copy(a.command, t("Launch command")) }] : []]; + const o = a.terminal && mode != "panel" && !web, term = [...o ? [{ name: "Open in terminal", icon: LAUNCH_GLYPH, sep: !0, run: () => api("agents/open", { agent: a.id, terminal: !0 }).catch(statusErr) }] : [], ...a.command ? [{ name: "Copy launch command", icon: COPY_ICON, sep: !o, run: () => copy(a.command, t("Launch command")) }] : []]; const acts = inFold && isHidden(a) ? [{ name: "Show", icon: EYE, run: () => setAgentHidden(a, false) }] : inFold @@ -4039,6 +4040,15 @@ function agentPrefsButton(a) { return b; } +// openButton opens Codex from its row: the desktop app, or the CLI in a +// terminal by the setting Open Codex with (Yink88564391 on X) +function openButton(a) { + const b = el("button", "ag-openapp", t("Open")); + b.type = "button"; + b.title = b.ariaLabel = t(a.openApp ? "Open the Codex app" : "Open Codex in a terminal"); + b.onclick = (ev) => { ev.stopPropagation(); api("agents/open", { agent: a.id }).catch(statusErr); }; + return b; +} // launchButton copies the command that starts an agent on magpie, for one // that takes the gateway only from its environment (agy) function launchButton(a) { @@ -21176,7 +21186,7 @@ function renderAlerts(s, keep) { // AGENT_PREFS: an agent's own settings rows, by its id (openAgentPrefs) const AGENT_PREFS = { - codex: ["codexAgentsV1Row", "codexSubagentModelRow", "codexServiceTierRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"], + codex: ["codexAgentsV1Row", "codexOpenRow", "codexSubagentModelRow", "codexServiceTierRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"], claude: ["fullContextRow"], grok: ["fullContextRow"], }; @@ -21317,6 +21327,7 @@ function renderAgentPrefs() { if (held.length) box.append(el("div", "hint codex-async-held", codexHeld(held))); $("#codexAsyncSegs").replaceChildren(box); renderCodexServiceTier(s); + renderCodexOpen(s); renderCodexTitles(s); renderCodexDescriptions(s); renderCodexPredictions(s); @@ -21421,6 +21432,21 @@ function renderCodexServiceTier(s) { $("#codexServiceTierPick").replaceChildren(b); } +// what Codex's Open button opens (Yink88564391 on X) +const CODEX_OPENS = [{ v: "", name: "Automatic" }, { v: "app", name: "Codex app" }, { v: "terminal", name: "Terminal" }]; +function renderCodexOpen(s) { + const cur = CODEX_OPENS.find((o) => o.v === (s.codexOpen || "")) || CODEX_OPENS[0]; + const b = el("button", "rt-cond on", t(cur.name)); + b.type = "button"; + b.setAttribute("aria-label", t("Open Codex with")); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(b, CODEX_OPENS, cur.v, (open) => open !== cur.v && prefWrite(api("settings/codex-open", { open })), "Open Codex with", "sess-menu"); + }; + $("#codexOpenPick").replaceChildren(b); +} + // Codex's descriptions: as sent, off, or a model function renderCodexDescriptions(s) { codexSidePick(s, "codexDescriptions", "Codex thread descriptions", "no description, nothing sent", "codex-descriptions"); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 2e37dfa70..f57b3b10f 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -21,6 +21,10 @@ const I18N = { "Resume gateway": "恢复网关", "Paused, agents are disconnected and use their own settings": "暂停时各 agent 断开连接,用回它们自己的配置", "{agent} couldn't be disconnected: {error}": "{agent} 断开失败:{error}", + "Open Codex with": "打开 Codex 的方式", + "Terminal": "终端", + "Open the Codex app": "打开 Codex 应用", + "Open Codex in a terminal": "在终端中打开 Codex", "Codex service tier": "Codex 服务层级", "As Codex asks": "按 Codex 的请求", "/fast in Codex": "Codex 里的 /fast", @@ -5160,6 +5164,10 @@ const I18N = { "Resume gateway": "恢復閘道", "Paused, agents are disconnected and use their own settings": "暫停時各 agent 中斷連線,改用它們自己的設定", "{agent} couldn't be disconnected: {error}": "{agent} 中斷連線失敗:{error}", + "Open Codex with": "開啟 Codex 的方式", + "Terminal": "終端機", + "Open the Codex app": "開啟 Codex 應用程式", + "Open Codex in a terminal": "在終端機中開啟 Codex", "Codex service tier": "Codex 服務層級", "As Codex asks": "依 Codex 的請求", "/fast in Codex": "Codex 裡的 /fast", @@ -10284,6 +10292,10 @@ const I18N = { "Resume gateway": "ゲートウェイを再開", "Paused, agents are disconnected and use their own settings": "一時停止中はエージェントの接続を解除し、それぞれ元の設定を使います", "{agent} couldn't be disconnected: {error}": "{agent} の接続を解除できませんでした: {error}", + "Open Codex with": "Codex を開く方法", + "Terminal": "ターミナル", + "Open the Codex app": "Codex アプリを開く", + "Open Codex in a terminal": "ターミナルで Codex を開く", "Codex service tier": "Codex のサービスティア", "As Codex asks": "Codex の指定どおり", "/fast in Codex": "Codex の /fast", @@ -15410,6 +15422,10 @@ const I18N = { "Resume gateway": "Zugangspunkt fortsetzen", "Paused, agents are disconnected and use their own settings": "Pausiert werden Agenten getrennt und nutzen ihre eigenen Einstellungen", "{agent} couldn't be disconnected: {error}": "{agent} konnte nicht getrennt werden: {error}", + "Open Codex with": "Codex öffnen mit", + "Terminal": "Terminal", + "Open the Codex app": "Codex-App öffnen", + "Open Codex in a terminal": "Codex im Terminal öffnen", "Codex service tier": "Codex-Servicestufe", "As Codex asks": "Wie Codex es anfragt", "/fast in Codex": "/fast in Codex", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 157fc1b9a..c6164ec1c 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -568,6 +568,10 @@
Codex background compaction
Codex 0.163 and later summarise while a turn goes on, past the share of the window typed (65% when empty); a value set in its own config stays
+
+
Open Codex with
+
+
Codex service tier
diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 5d97cb2b6..9b65bdacb 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -18,7 +18,7 @@ import ( // `git log -L` of this file. const ( appScriptBudget = 1_086_267 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had - coreScriptBudget = 1_264_432 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to + coreScriptBudget = 1_265_544 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to ) // codeBytes is how many bytes of b are code: its blank lines, its lines diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index a0970c367..a26df3bbe 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -416,11 +416,28 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { // is made here from the agent as detected (agentCommand), and the page // sends only its id. mux.HandleFunc("POST /api/agents/open", func(rw http.ResponseWriter, r *http.Request) { - var in struct{ Agent string } + var in struct { + Agent string + // Terminal asks for the terminal even where the Open button + // opens the app (the row menu's Open in terminal) + Terminal bool + } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { fail(rw, err) return } + if in.Agent == "codex" && !in.Terminal && codexOpensApp() { + if isWeb(w) { + fail(rw, errors.New("opening an app is only for the desktop app")) + return + } + if err := codexAppOpener(r.Context()); err != nil { + fail(rw, err) + return + } + rw.WriteHeader(http.StatusNoContent) + return + } if !terminalHere() || isWeb(w) { fail(rw, errors.New("opening a terminal is only for the desktop app")) return @@ -1190,6 +1207,20 @@ func agentCommand(a *agent.Agent) string { return agentLine(a, launch, runtime.GOOS) } +// codexOpensApp says whether Codex's Open button opens the desktop app: +// the app where one is installed, unless the setting codexOpen asks for the +// terminal (Yink88564391 on X). +func codexOpensApp() bool { + return settings.Load().CodexOpen != "terminal" && codexAppInstalled() +} + +// codexAppInstalled and codexAppOpener are the agent package's, vars so a +// test doesn't open a real app. +var ( + codexAppInstalled = agent.CodexAppInstalled + codexAppOpener = agent.OpenCodexApp +) + // agentLine is agentCommand with a's Launch already asked, for goos. func agentLine(a *agent.Agent, launch, goos string) string { if a.WSL != "" { diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index 0456d85e7..8e2eb9438 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -176,6 +176,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { CodexAutoReview: "fake/m1", CodexSubagentModel: "codex/gpt-6-astra", CodexServiceTier: "priority", + CodexOpen: "terminal", DesktopSubagentModel: "fake/m2", DesktopGateway: "https://192.168.1.20:3425", DshCompactModel: "fake/m1", diff --git a/internal/gui/tests/agent-open-terminal.test.cjs b/internal/gui/tests/agent-open-terminal.test.cjs index 80d3e625e..46a1e6df6 100644 --- a/internal/gui/tests/agent-open-terminal.test.cjs +++ b/internal/gui/tests/agent-open-terminal.test.cjs @@ -107,7 +107,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await item().click(); await sent; await page.locator(".pop.row-menu").waitFor({ state: "detached" }); - assert.deepEqual(posts.map(([p, b]) => [p, JSON.parse(b)]), [["/api/agents/open", { agent: "codex" }]], "the id and nothing else"); + assert.deepEqual(posts.map(([p, b]) => [p, JSON.parse(b)]), [["/api/agents/open", { agent: "codex", terminal: true }]], "the id, and the terminal asked for"); assert.deepEqual(errors, []); }); } diff --git a/internal/gui/tests/agent-prefs.test.cjs b/internal/gui/tests/agent-prefs.test.cjs index 30335b201..3b667fdd3 100644 --- a/internal/gui/tests/agent-prefs.test.cjs +++ b/internal/gui/tests/agent-prefs.test.cjs @@ -20,7 +20,7 @@ const { chromium, webkit } = require("playwright"); const { watchSettingsReads, agentRow, openAgentSettings } = require("./reader.cjs"); const assets = path.resolve(__dirname, "../assets"); -const CODEX = ["codexAgentsV1Row", "codexServiceTierRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"]; +const CODEX = ["codexAgentsV1Row", "codexOpenRow", "codexServiceTierRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"]; function settingsPayload(over) { return { @@ -103,7 +103,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.goto("http://magpie.test/?view=agents"); await openAgentSettings(page, "codex"); const codexBox = '.row.agent[data-id="codex"] .ag-prefs'; - assert.deepEqual(await shownIn(page, codexBox), CODEX, `${lang} ${width}: Codex's nine`); + assert.deepEqual(await shownIn(page, codexBox), CODEX, `${lang} ${width}: Codex's ten`); assert(await page.locator(codexBox).evaluate((b) => b.scrollWidth <= b.clientWidth + 1), `${lang} ${width}: the rows fit the opened row`); await noSideScroll(page, `${lang} ${width} Codex`); await openAgentSettings(page, "claude"); @@ -131,7 +131,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await link.getByRole("button", { name: w.open, exact: true }).click(); await sheet(page).waitFor(); assert.equal(await sheet(page).locator(".ehead").textContent(), w.sheet); - assert.deepEqual(await shownIn(page, "#modal .editor.agent-prefs"), CODEX, `${lang} ${width}: the sheet has Codex's nine`); + assert.deepEqual(await shownIn(page, "#modal .editor.agent-prefs"), CODEX, `${lang} ${width}: the sheet has Codex's ten`); assert(await page.locator("#view-agents").isVisible(), "Open goes to the Agents page"); await page.keyboard.press("Escape"); await page.locator("#modal").waitFor({ state: "hidden" }); diff --git a/internal/gui/tests/codex-open-button.test.cjs b/internal/gui/tests/codex-open-button.test.cjs new file mode 100644 index 000000000..27e25900d --- /dev/null +++ b/internal/gui/tests/codex-open-button.test.cjs @@ -0,0 +1,152 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Codex's Open button (Yink88564391 on X): Codex's row on the Agents page has a +// visible Open button beside its model, not only the row menu's Open in +// terminal. It opens the desktop app where one is installed (openApp) and +// the CLI in a terminal otherwise; either way it posts agents/open with the +// id alone, while the menu's Open in terminal asks for the terminal. A row +// of any other agent, the web build and a Codex with nothing to open have no +// button. Codex's settings have "Open Codex with" (Automatic, Codex app, +// Terminal), an app menu, which posts settings/codex-open. Every language, +// Chromium and WebKit, wide and narrow; no backend, the API is faked here. +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 { watchSettingsReads, agentRow, openAgentSettings } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); + +function server(lang, web, codex, posted) { + let cur = { theme: "light", lang, version: "0.1.400", titleModels: [], codexOpen: "" }; + return async (route) => { + const req = route.request(), url = new URL(req.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:${web}};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [{ ...agentRow("codex", "Codex"), ...codex }, { ...agentRow("claude", "Claude Code"), terminal: true, command: "claude" }], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/agents/open") { posted.push(["open", req.postDataJSON()]); return route.fulfill({ status: 204, body: "" }); } + if (url.pathname === "/api/settings/codex-open") { + const body = req.postDataJSON(); + posted.push(["codex-open", body]); + cur = { ...cur, codexOpen: body.open }; + return json(cur); + } + if (url.pathname === "/api/settings") return json(cur); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + 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)]; + try { + await route.fulfill({ body: await fs.readFile(file), contentType }); + } catch { + await route.fulfill({ status: 404, body: "" }); + } + }; +} + +const W = { + en: { open: "Open", app: "Open the Codex app", term: "Open Codex in a terminal", name: "Open Codex with", auto: "Automatic", capp: "Codex app", cterm: "Terminal" }, + zh: { open: "打开", app: "打开 Codex 应用", term: "在终端中打开 Codex", name: "打开 Codex 的方式", auto: "自动", capp: "Codex 应用", cterm: "终端" }, + "zh-TW": { open: "開啟", app: "開啟 Codex 應用程式", term: "在終端機中開啟 Codex", name: "開啟 Codex 的方式", auto: "自動", capp: "Codex 應用程式", cterm: "終端機" }, + ja: { open: "開く", app: "Codex アプリを開く", term: "ターミナルで Codex を開く", name: "Codex を開く方法", auto: "自動", capp: "Codex アプリ", cterm: "ターミナル" }, + de: { open: "Öffnen", app: "Codex-App öffnen", term: "Codex im Terminal öffnen", name: "Codex öffnen mit", auto: "Automatisch", capp: "Codex-App", cterm: "Terminal" }, +}; +const engines = process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]; +const langs = process.env.LANGS ? process.env.LANGS.split(",") : Object.keys(W); + +async function start(engine, t, lang, width, web, codex) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 720 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posted = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, web, codex, posted)); + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=agents"); + await page.locator('.row.agent[data-id="codex"]').waitFor(); + return { page, errors, posted }; +} + +for (const engine of engines) { + for (const lang of langs) { + for (const width of [900, 400]) { + const w = W[lang]; + test(`${engine} ${lang} ${width}px: Codex's row has an Open button that opens the app`, async (t) => { + const { page, errors, posted } = await start(engine, t, lang, width, false, { terminal: true, command: "codex", openApp: true }); + const btn = page.locator('.row.agent[data-id="codex"] .ag-openapp'); + await btn.waitFor(); + assert.equal((await btn.textContent()).trim(), w.open); + assert.equal(await btn.getAttribute("title"), w.app); + assert.equal(await page.locator('.row.agent[data-id="claude"] .ag-openapp').count(), 0, "another agent's row"); + const box = await btn.boundingBox(), row = await page.locator('.row.agent[data-id="codex"]').boundingBox(); + assert(box.width > 0 && box.x >= row.x && box.x + box.width <= row.x + row.width, `the button leaves the row: ${JSON.stringify([box, row])}`); + // it does not sit on the model picker or the switch + for (const sel of [".ag-start", ".ag-conn"]) { + const o = await page.locator(`.row.agent[data-id="codex"] ${sel}`).first().boundingBox(); + if (o) assert(box.x + box.width <= o.x + 1 || o.x + o.width <= box.x + 1 || box.y + box.height <= o.y + 1 || o.y + o.height <= box.y + 1, `Open overlaps ${sel}`); + } + assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "the page scrolls sideways"); + const sent = page.waitForResponse((r) => new URL(r.url()).pathname === "/api/agents/open"); + await btn.click(); + await sent; + assert.deepEqual(posted, [["open", { agent: "codex" }]], "the id alone"); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}px: with no app the button opens the terminal`, async (t) => { + const { page, errors, posted } = await start(engine, t, lang, width, false, { terminal: true, command: "codex" }); + const btn = page.locator('.row.agent[data-id="codex"] .ag-openapp'); + await btn.waitFor(); + assert.equal(await btn.getAttribute("title"), w.term); + const sent = page.waitForResponse((r) => new URL(r.url()).pathname === "/api/agents/open"); + await btn.click(); + await sent; + assert.deepEqual(posted, [["open", { agent: "codex" }]]); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}px: Open Codex with is picked from the app menu`, async (t) => { + const { page, errors, posted } = await start(engine, t, lang, width, false, { terminal: true, command: "codex", openApp: true }); + await openAgentSettings(page); + const row = page.locator('.row.agent[data-id="codex"] #codexOpenRow'); + const pick = page.locator("#codexOpenPick button"); + await pick.waitFor(); + assert.equal((await row.locator(".name").textContent()).trim(), w.name); + assert.equal((await pick.textContent()).trim(), w.auto); + assert.equal(await page.locator("select").count(), 0, "a native select"); + await page.locator('.row.agent[data-id="claude"] .ag-link').click(); + await page.locator('.row.agent[data-id="claude"] .ag-prefs').waitFor(); + assert.equal(await page.locator('.row.agent[data-id="claude"] #codexOpenRow').count(), 0, "the row in Claude Code's settings"); + await openAgentSettings(page); + await pick.scrollIntoViewIfNeeded(); + for (const [label, open] of [[w.cterm, "terminal"], [w.capp, "app"], [w.auto, ""]]) { + await pick.click(); + const menu = page.locator(".proto-menu"); + await menu.waitFor(); + assert.deepEqual((await menu.locator(".pm-item .pm-name").allTextContents()).map((s) => s.trim()), [w.auto, w.capp, w.cterm]); + const mb = await menu.boundingBox(); + assert(mb.x >= 0 && mb.x + mb.width <= width, `the menu runs off the window: ${JSON.stringify(mb)}`); + await menu.locator(".pm-item").filter({ has: page.locator(".pm-name", { hasText: new RegExp("^" + label + "$") }) }).click(); + await page.locator("#codexOpenPick button", { hasText: new RegExp("^\\s*" + label + "\\s*$") }).waitFor(); + assert.deepEqual(posted.at(-1), ["codex-open", { open }]); + } + assert.equal(posted.length, 3, JSON.stringify(posted)); + assert.deepEqual(errors, []); + }); + } + } + + test(`${engine}: the web build and a Codex with nothing to open have no Open button`, async (t) => { + let { page, errors } = await start(engine, t, "en", 900, true, { terminal: true, command: "codex", openApp: true }); + assert.equal(await page.locator('.row.agent[data-id="codex"] .ag-openapp').count(), 0, "the web build"); + assert.deepEqual(errors, []); + ({ page, errors } = await start(engine, t, "en", 900, false, {})); + assert.equal(await page.locator('.row.agent[data-id="codex"] .ag-openapp').count(), 0, "nothing to open"); + assert.deepEqual(errors, []); + }); +} diff --git a/internal/provider/codex_tier.go b/internal/provider/codex_tier.go index 7659e16b9..0b3b47610 100644 --- a/internal/provider/codex_tier.go +++ b/internal/provider/codex_tier.go @@ -33,3 +33,18 @@ func SetCodexServiceTier(tier string) error { s.CodexServiceTier = tier return settings.Save(s) } + +// SetCodexOpen sets what the Open button of Codex's Agents row opens: "", +// "app" or "terminal" (Yink88564391 on X). +func SetCodexOpen(v string) error { + v = strings.TrimSpace(v) + if !slices.Contains(settings.CodexOpens, v) { + return fmt.Errorf("Codex's Open button must open one of %q, not %q", settings.CodexOpens[1:], v) + } + s := settings.Load() + if s.CodexOpen == v { + return nil + } + s.CodexOpen = v + return settings.Save(s) +} diff --git a/internal/settings/codex_open_test.go b/internal/settings/codex_open_test.go new file mode 100644 index 000000000..6e8f3dfe3 --- /dev/null +++ b/internal/settings/codex_open_test.go @@ -0,0 +1,13 @@ +package settings + +import "testing" + +// The Open button's choice for Codex is this computer's own: another +// computer's sync does not carry it in. +func TestCodexOpenIsThisComputers(t *testing.T) { + from := Settings{CodexOpen: "app"} + from.KeepOwn(Settings{CodexOpen: "terminal"}) + if from.CodexOpen != "terminal" { + t.Fatalf("a sync replaced the computer's own choice: %q", from.CodexOpen) + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 9f4573bbf..114c3123b 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -50,6 +50,9 @@ const CodexSubagentLead = "lead" // sentinel codex-rs itself uses for that (SERVICE_TIER_DEFAULT_REQUEST_VALUE). const CodexTierStandard = "default" +// CodexOpens are the values CodexOpen may take, "" for the default. +var CodexOpens = []string{"", "app", "terminal"} + // CodexServiceTiers are the values CodexServiceTier may take, "" (as // Codex asks) first. var CodexServiceTiers = []string{"", CodexTierStandard, "priority", "ultrafast"} @@ -846,6 +849,11 @@ type Settings struct { // Ultra Fast). Codex's words, as codex-rs ServiceTier::request_value // sends them; its Flex is not offered, the ChatGPT backend takes none. CodexServiceTier string `json:"codexServiceTier,omitempty"` + // CodexOpen is what the Open button of Codex's Agents row opens + // (Yink88564391 on X): "app" the Codex desktop app, "terminal" the CLI + // in a terminal. "" is the app where one is installed, else the + // terminal. It belongs to this computer. + CodexOpen string `json:"codexOpen,omitempty"` // DesktopSubagentModel is the model the gateway puts Claude Desktop's // subagent tool turns on. "" leaves them on the model their lead asks // for; tool-less helpers and the lead's own turns are never moved. @@ -1667,6 +1675,7 @@ func (s *Settings) KeepOwn(cur Settings) { s.RouterNote, s.RouterAllTools = cur.RouterNote, cur.RouterAllTools s.FetchPrivate = cur.FetchPrivate s.SessionTerminal = cur.SessionTerminal + s.CodexOpen = cur.CodexOpen s.PanelShortcut = cur.PanelShortcut s.RedactModel, s.RedactModelName, s.RedactModelScore = cur.RedactModel, cur.RedactModelName, cur.RedactModelScore s.RedactModelOff, s.RedactModelAuto = cur.RedactModelOff, cur.RedactModelAuto @@ -2570,6 +2579,10 @@ func saveOwn(s Settings, recording, reads bool) error { if !slices.Contains(CodexServiceTiers, s.CodexServiceTier) { return fmt.Errorf("Codex's service tier must be one of %q, not %q", CodexServiceTiers[1:], s.CodexServiceTier) } + s.CodexOpen = strings.TrimSpace(s.CodexOpen) + if !slices.Contains(CodexOpens, s.CodexOpen) { + return fmt.Errorf("Codex's Open button must open one of %q, not %q", CodexOpens[1:], s.CodexOpen) + } s.RedactRouteTo = strings.TrimSpace(s.RedactRouteTo) if s.RedactRouteTo != "" && !strings.Contains(s.RedactRouteTo, "/") { return fmt.Errorf("the model for requests masking would change must be a model's id such as ollama/qwen3, not %q", s.RedactRouteTo) diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index 2eec4115c..c64eb0889 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -373,6 +373,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err // and the models Codex's and Desktop's subagents are put on, set // in their Agents rows in.CodexSubagentModel = cur.CodexSubagentModel + in.CodexOpen = cur.CodexOpen // set on its own (codex-open) in.DesktopSubagentModel = cur.DesktopSubagentModel in.DesktopGateway = cur.DesktopGateway // Desktop's address, set in its row in.CodexServiceTier = cur.CodexServiceTier // codex-service-tier