Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

agent: the Codex app's Restart restarts only its app-server, its window stays

yetone791e27ec343a
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md
index 90603d9d2..3cd8da2c4 100644
--- a/docs/subsystems/agent-wiring.md
+++ b/docs/subsystems/agent-wiring.md
@@ -20,7 +20,7 @@ something else shows up as drift.
| What came before | The stash (`stash.json`) remembers what the config said before magpie pointed it at the gateway, so Disconnect restores it rather than guessing. | [`stash.go`](../../internal/agent/stash.go) |
| Disconnect and preview | `Disconnect` runs `Unwire`, then returns each field still on magpie to its default. Last it runs `Restore`: Pi and its kin (`piLike`: Pi, OmO, Prime Agent; and MothX, its one `settings.json`) copy `settings.json` and `models.json` aside (`*.before-magpie`, `beforeMagpie`) before magpie's first write, and put that copy back byte for byte where what Disconnect left is the same JSON; a file that wasn't there goes again when only empty objects are left in it. `DisconnectPreview` runs the real Disconnect on a copy under a temporary home, in a subprocess (`DryRunArg`), and diffs the files. The preview is never a second account of what Disconnect does. | [`applied.go`](../../internal/agent/applied.go), [`preview.go`](../../internal/agent/preview.go) |
| Keeping configs current | `Reseat` moves agents off a model magpie no longer serves (#200). `OnGateway` and `Rewire` write the new gateway address into every connected agent when the port changes. `Source` and `Stale` say what an unconnected agent runs on, and whether running copies still use the old list. | [`reseat.go`](../../internal/agent/reseat.go), [`rewire.go`](../../internal/agent/rewire.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
-| Restarting a desktop app | Claude Desktop and WorkBuddy (WorkBuddy AI on macOS) read magpie's settings only as they start (微雨南山 and stones on Discord). `AppBehind` names one running here that started more than a second before magpie last changed what it reads (`changedAt`, which puts a change no file's time shows, such as Claude Desktop's gateway model list, at when it is first seen); only for an agent connected in magpie or disconnected in it. The row's Restart asks first in magpie's own dialog (`confirmRestart`), then `POST /api/agents/restart/{id}` runs `RestartApp`. On macOS (`restartApps`, the bundle found by id under `appFolders`, its `CFBundleExecutable` matched in `pgrep`) it quits as ⌘Q does and waits for every process of the bundle (`reopenBundle`); one still open after `appQuitWait` (a "Save?" question) is left as it is and not opened again (`noticeRestartStillOpen`). On Windows (`claude.exe` under `AnthropicClaude` or its Store package, `WorkBuddy.exe` outside the WorkBuddy AI folder) its processes are asked to close (`taskkill` without `/F`); a tray app still there after `appCloseWait` has its tree ended, and it is opened again through its Store id or Squirrel's stub. The Codex app's own Restart (`ReopenCodexApp`) asks first too. Codex on Windows, WorkBuddy AI on Windows and Linux aren't restarted: their process names aren't known. | [`apprestart.go`](../../internal/agent/apprestart.go), [`apprestart_windows.go`](../../internal/agent/apprestart_windows.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
+| Restarting a desktop app | Claude Desktop and WorkBuddy (WorkBuddy AI on macOS) read magpie's settings only as they start (微雨南山 and stones on Discord). `AppBehind` names one running here that started more than a second before magpie last changed what it reads (`changedAt`, which puts a change no file's time shows, such as Claude Desktop's gateway model list, at when it is first seen); only for an agent connected in magpie or disconnected in it. The row's Restart asks first in magpie's own dialog (`confirmRestart`), then `POST /api/agents/restart/{id}` runs `RestartApp`. On macOS (`restartApps`, the bundle found by id under `appFolders`, its `CFBundleExecutable` matched in `pgrep`) it quits as ⌘Q does and waits for every process of the bundle (`reopenBundle`); one still open after `appQuitWait` (a "Save?" question) is left as it is and not opened again (`noticeRestartStillOpen`). On Windows (`claude.exe` under `AnthropicClaude` or its Store package, `WorkBuddy.exe` outside the WorkBuddy AI folder) its processes are asked to close (`taskkill` without `/F`); a tray app still there after `appCloseWait` has its tree ended, and it is opened again through its Store id or Squirrel's stub. The Codex app's own Restart (`ReopenCodexApp`) asks first too, then ends only the app-server that app runs for itself (`provider.RestartCodexApp`: under its bundle, never a `--listen` one), as a switch does; the app starts another and keeps its window. Quitting and opening it, as before, opened a new window (yoshi037070 on Discord, 10-27). Codex on Windows, WorkBuddy AI on Windows and Linux aren't restarted: their process names aren't known. | [`apprestart.go`](../../internal/agent/apprestart.go), [`apprestart_windows.go`](../../internal/agent/apprestart_windows.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
| Codex background compaction | Long conversations' Codex background compaction, in Codex's opened row on the Agents page (`CodexAsyncCompact`, `CodexAsyncCompactPercent`, #2490) writes `[features.async_compaction]` `enabled = true` and `model_async_compact_threshold_percent` (Codex 0.163 reads it only in that table) into each Codex config magpie routes, on every `Sync`. The table is written only when every Codex that reads the config is 0.163.0-alpha.8 or later (`codexReaders`: the CLI on PATH, the Mac app's bundled `codex-cli/codex-package.json`, the Windows Store app and an editor's `openai.chatgpt` extension, whose versions aren't known, a WSL distro's CLI): an older Codex takes every unknown `[features]` entry for a bool and won't load a config with the table ("invalid type: map, expected a boolean"). Otherwise, or with no Codex found, magpie writes the bare `[features]` `async_compaction = true`, which every Codex loads, and no threshold; a table magpie wrote before is taken out on the next `Sync`, and Settings' row names the Codex that held it (`CodexAsyncHeld`). Codex starts a background compaction only on a provider whose `capabilities.remote_compaction` is `"v2"`, which it gives OpenAI and Azure alone, so `[model_providers.magpie]` gets `capabilities = { remote_compaction = "v2" }` too, also when the user turned the feature on by hand (#2493); `putProvider` carries the table's capabilities over when it writes it again. What magpie wrote is in the stash under `codex.async`: a value the user set, or changed since, is never written over and stays when the switch goes off; a bare `async_compaction = true` the stash doesn't name as magpie's (`bool`), an inline or dotted table is the user's as written. | [`codex_async.go`](../../internal/agent/codex_async.go) |
| Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/<name>` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#<name>` on Windows, `omp#<name>@wsl:<distro>` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) |
| WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `<id>@wsl:<distro>`, edited through `\\wsl.localhost\<distro>`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Antigravity CLI is found by its own `~/.gemini/antigravity-cli` or its `agy` command (mimi001234 on Discord). Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-<agent>` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go) |
diff --git a/internal/agent/codex_app.go b/internal/agent/codex_app.go
index 70d582d72..4efdb585d 100644
--- a/internal/agent/codex_app.go
+++ b/internal/agent/codex_app.go
@@ -3,20 +3,21 @@ package agent
import (
"context"
"errors"
- "regexp"
"runtime"
"slices"
"strings"
"time"
"github.com/yetone/magpie/internal/proc"
+ "github.com/yetone/magpie/internal/provider"
)
// The Codex app on macOS keeps running, its app-server with it, when its
// window is closed, so a change to Codex's model list reaches it only once
-// it is quit and opened again. The Agents row's Restart does that for the
-// user (the owner, 10-23): it asks the app to quit, as ⌘Q does, waits for
-// every process of its bundle to end, and opens it again.
+// its app-server starts again. The Agents row's Restart does that for the
+// user (the owner, 10-23): it ends the app's own app-server, and the app
+// starts another and keeps its window. Quitting the app and opening it
+// again, as it did before, opened a new window (yoshi037070, 10-27).
// appQuit and appOpen ask macOS to quit a bundle and to open it; vars so
// tests don't touch a real app.
@@ -41,16 +42,17 @@ func cmdErr(out []byte, err error) error {
return err
}
-// ErrCodexAppStillOpen is a quit the app didn't finish: it may be asking
-// something in its window (a task still running).
-var ErrCodexAppStillOpen = errors.New("the Codex app is still open; it may be asking something in its window")
+// restartAppServer ends the app-server the app at a bundle runs for
+// itself; a var so tests don't end a real one.
+var restartAppServer = provider.RestartCodexApp
-// ReopenCodexApp quits the Codex desktop app at bundle and opens it again.
-// Only an app the Agents row lists as left on the old list is quit, never
-// a path a request names otherwise.
+// ReopenCodexApp restarts the app-server of the Codex desktop app at
+// bundle; the app starts a new one and its window stays. Only an app the
+// Agents row lists as left on the old list is touched, never a path a
+// request names otherwise.
func ReopenCodexApp(ctx context.Context, bundle string) error {
if runtime.GOOS != "darwin" {
- return errors.New("only the macOS Codex app is reopened by magpie")
+ return errors.New("only the macOS Codex app is restarted by magpie")
}
a, err := Find("codex")
if err != nil {
@@ -63,20 +65,5 @@ func reopenApp(ctx context.Context, a *Agent, bundle string) error {
if bundle == "" || !slices.ContainsFunc(a.StaleCopies(), func(c StaleCopy) bool { return c.Kind == "app" && c.Bundle == bundle }) {
return errors.New("that Codex app has the current list already")
}
- if err := appQuit(ctx, bundle); err != nil {
- return err
- }
- pat := regexp.QuoteMeta(bundle + "/Contents/")
- end := time.Now().Add(appQuitWait)
- for len(running(pat)) > 0 {
- if time.Now().After(end) {
- return ErrCodexAppStillOpen
- }
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-time.After(200 * time.Millisecond):
- }
- }
- return appOpen(ctx, bundle)
+ return restartAppServer(ctx, bundle)
}
diff --git a/internal/agent/codex_app_test.go b/internal/agent/codex_app_test.go
index 2d841399d..bb4f64934 100644
--- a/internal/agent/codex_app_test.go
+++ b/internal/agent/codex_app_test.go
@@ -11,9 +11,9 @@ import (
"time"
)
-// The Codex app's Restart quits only the app the row lists as left on the
-// old list, waits for its processes to end, and opens it again; an app
-// that doesn't end is said, and not opened a second time.
+// The Codex app's Restart restarts only the app-server of the app the row
+// lists as left on the old list. It never quits the app and opens it
+// again, which opened a new window (yoshi037070, 10-27).
func TestCodexAppReopen(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip(staleOnWindows)
@@ -29,16 +29,12 @@ func TestCodexAppReopen(t *testing.T) {
os.WriteFile(filepath.Join(dir, "config.toml"), []byte("model_provider = \"magpie\"\n"), 0o600)
const bundle = "/Applications/Codex.app"
- up := true
- wasRunning, wasQuit, wasOpen, wasWait := running, appQuit, appOpen, appQuitWait
- t.Cleanup(func() { running, appQuit, appOpen, appQuitWait = wasRunning, wasQuit, wasOpen, wasWait })
+ wasRunning, wasQuit, wasOpen, wasRestart := running, appQuit, appOpen, restartAppServer
+ t.Cleanup(func() { running, appQuit, appOpen, restartAppServer = wasRunning, wasQuit, wasOpen, wasRestart })
running = func(pat string) []runningProc {
- if !up {
- return nil
- }
ps := []runningProc{
{3 * time.Hour, bundle + "/Contents/MacOS/Codex"},
- {3 * time.Hour, bundle + "/Contents/Resources/codex app-server --listen stdio://"},
+ {3 * time.Hour, bundle + "/Contents/Resources/codex app-server"},
}
var out []runningProc
for _, p := range ps {
@@ -49,8 +45,9 @@ func TestCodexAppReopen(t *testing.T) {
return out
}
var did []string
- appQuit = func(_ context.Context, b string) error { did = append(did, "quit "+b); up = false; return nil }
+ appQuit = func(_ context.Context, b string) error { did = append(did, "quit "+b); return nil }
appOpen = func(_ context.Context, b string) error { did = append(did, "open "+b); return nil }
+ restartAppServer = func(_ context.Context, b string) error { did = append(did, "restart "+b); return nil }
a := codex(home)
if err := reopenApp(context.Background(), a, "/Applications/Other.app"); err == nil || len(did) > 0 {
@@ -59,18 +56,14 @@ func TestCodexAppReopen(t *testing.T) {
if err := reopenApp(context.Background(), a, bundle); err != nil {
t.Fatal(err)
}
- if got := strings.Join(did, ", "); got != "quit "+bundle+", open "+bundle {
- t.Fatalf("did %q", got)
+ if got := strings.Join(did, ", "); got != "restart "+bundle {
+ t.Fatalf("did %q, want only its app-server restarted", got)
}
- // the app asks something and stays open: said, not opened
- up, did = true, nil
- appQuit = func(_ context.Context, b string) error { did = append(did, "quit "+b); return nil }
- appQuitWait = 300 * time.Millisecond
- if err := reopenApp(context.Background(), a, bundle); !errors.Is(err, ErrCodexAppStillOpen) {
- t.Fatalf("still open: %v", err)
- }
- if got := strings.Join(did, ", "); got != "quit "+bundle {
- t.Fatalf("did %q", got)
+ // a restart that fails is said
+ did = nil
+ restartAppServer = func(context.Context, string) error { return errors.New("didn't end") }
+ if err := reopenApp(context.Background(), a, bundle); err == nil || len(did) > 0 {
+ t.Fatalf("failed restart: %v, did %v", err, did)
}
}
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index 8fff727dc..74108defb 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -1870,24 +1870,22 @@ function daemonRestart() {
return go;
}
-// asked first: what runs in the app stops
-const confirmRestart = (name) => confirmAction(t("Restart {agent}?", { agent: name }), t("magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.", { agent: name }), t("Restart"));
+const confirmRestart = (name, why) => confirmAction(t("Restart {agent}?", { agent: name }), why || t("magpie quits {agent} and opens it again, so it reads the new settings. Anything running in it stops.", { agent: name }), t("Restart"));
-// appReopen is the Restart beside the Codex app left on the old list: magpie
-// asks, then quits it, as ⌘Q does, and opens it again
+// appReopen: ends the Codex app's app-server, not its window
function appReopen(bundle) {
const go = el("button", "ag-quiet accent", t("Restart"));
go.type = "button";
go.title = bundle;
go.onclick = async () => {
- if (!(await confirmRestart(t("The Codex app")))) return;
+ if (!(await confirmRestart(t("The Codex app"), t("Only its app-server restarts, for the new settings; its window stays. A running turn stops.")))) return;
go.disabled = true;
go.classList.add("busy");
try {
await api("codex/app/reopen", { bundle });
state = await api("state");
renderAgents();
- status(t("The Codex app reopened"));
+ status(t("Codex app-server restarted"));
} catch (e) {
go.disabled = false;
go.classList.remove("busy");
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index 5ecae7d4b..ceb674b66 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -1848,7 +1848,8 @@ const I18N = {
"Later": "稍后",
"Restart": "重启",
"Codex's background service restarted": "Codex 的后台服务已重启",
- "The Codex app reopened": "Codex 应用已重新打开",
+ "Codex app-server restarted": "Codex 的 app-server 已重启",
+ "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} 并重新打开,让它读取新设置。其中正在运行的任务会停止。",
"The Codex app": "Codex 应用",
@@ -5868,7 +5869,8 @@ const I18N = {
"Later": "稍後",
"Restart": "重啟",
"Codex's background service restarted": "Codex 的後臺服務已重啟",
- "The Codex app reopened": "Codex 應用已重新打開",
+ "Codex app-server restarted": "Codex 的 app-server 已重新啟動",
+ "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} 並重新打開,讓它讀取新設定。其中正在執行的工作會停止。",
"The Codex app": "Codex 應用",
@@ -9865,7 +9867,8 @@ const I18N = {
"Later": "後で",
"Restart": "再起動",
"Codex's background service restarted": "Codex のバックグラウンドサービスを再起動しました",
- "The Codex app reopened": "Codex アプリを開き直しました",
+ "Codex app-server restarted": "Codex の app-server を再起動しました",
+ "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} を終了してから開き直し、新しい設定を読み込ませます。その中で実行中の作業は止まります。",
"The Codex app": "Codex アプリ",
@@ -13892,7 +13895,8 @@ const I18N = {
"Later": "Später",
"Restart": "Neu starten",
"Codex's background service restarted": "Hintergrunddienst von Codex neu gestartet",
- "The Codex app reopened": "Codex-App neu geöffnet",
+ "Codex app-server restarted": "App-Server von Codex neu gestartet",
+ "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.",
"The Codex app": "Die Codex-App",
diff --git a/internal/gui/tests/agent-stale-copies.test.cjs b/internal/gui/tests/agent-stale-copies.test.cjs
index 6ab4f4f82..56fff6aab 100644
--- a/internal/gui/tests/agent-stale-copies.test.cjs
+++ b/internal/gui/tests/agent-stale-copies.test.cjs
@@ -194,14 +194,16 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
}
// the Codex app's line has a Restart of its own (the owner, 10-23): magpie
-// asks, then quits the app named by its bundle and opens it again
+// asks, then restarts only the app-server of the app named by its bundle,
+// and says its window stays (yoshi037070: a quit and open opened a new one)
const appName = { en: "The Codex app", zh: "Codex 应用", "zh-TW": "Codex 應用", ja: "Codex アプリ", de: "Die Codex-App" };
const cancelSays = { en: "Cancel", zh: "取消", "zh-TW": "取消", ja: "キャンセル", de: "Abbrechen" };
-const reopened = { en: "The Codex app reopened", zh: "Codex 应用已重新打开", "zh-TW": "Codex 應用已重新打開", ja: "Codex アプリを開き直しました", de: "Codex-App neu geöffnet" };
+const reopened = { en: "Codex app-server restarted", zh: "Codex 的 app-server 已重启", "zh-TW": "Codex 的 app-server 已重新啟動", ja: "Codex の app-server を再起動しました", de: "App-Server von Codex neu gestartet" };
+const windowStays = { en: "window stays", zh: "窗口保持不变", "zh-TW": "視窗保持不變", ja: "ウィンドウはそのまま", de: "Fenster bleibt offen" };
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 [980, 440]) {
- test(`${engine} ${lang} ${width}px: the app's line reopens it`, async (t) => {
+ test(`${engine} ${lang} ${width}px: the app's line restarts its app-server`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width, height: 800 } });
@@ -235,6 +237,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const ask = page.locator("dialog.action-confirm[open]");
await ask.waitFor();
assert.ok((await ask.locator("h2").textContent()).includes(appName[lang]), await ask.locator("h2").textContent());
+ assert.ok((await ask.textContent()).includes(windowStays[lang]), await ask.textContent());
await ask.locator("button", { hasText: cancelSays[lang] }).click();
await ask.waitFor({ state: "detached" });
assert.deepEqual(asked, []);
diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.go
index 42baeed0c..52e89614d 100644
--- a/internal/provider/codex_app_server.go
+++ b/internal/provider/codex_app_server.go
@@ -9,6 +9,7 @@ import (
"log"
"os"
"path/filepath"
+ "slices"
"strings"
"sync"
"time"
@@ -338,3 +339,51 @@ func sessionTurnOpen(path string) bool {
ended := max(bytes.LastIndex(b, []byte(`"type":"task_complete"`)), bytes.LastIndex(b, []byte(`"type":"turn_aborted"`)))
return started > ended
}
+
+// codexAppGoneWait is how long RestartCodexApp waits for the app-servers
+// it ended to be gone; a var for tests.
+var codexAppGoneWait = 10 * time.Second
+
+// RestartCodexApp restarts the app-server the Codex desktop app at bundle
+// (/Applications/ChatGPT.app) runs for itself, as codexAppStep does: it is
+// ended as a clean exit, and the app starts another, which reads Codex's
+// config and model list afresh, while the app's window, threads and drafts
+// stay as they are. The Agents row's Restart quit the app and opened it
+// again, which opened a new window (yoshi037070 on Discord, 10-27). An
+// app-server another program runs from the bundle (--listen) is left
+// alone. It waits until the ones ended are gone, and errs when none ran.
+func RestartCodexApp(ctx context.Context, bundle string) error {
+ ps, err := listProcesses(ctx)
+ if err != nil {
+ return err
+ }
+ in := strings.TrimSuffix(bundle, "/") + "/Contents/"
+ var ended []int
+ for _, p := range ps {
+ if !strings.HasPrefix(strings.TrimSpace(p.Args), in) || !isCodexAppOwnServer(p.Args) {
+ continue
+ }
+ if err := endCodexAppServer(p.PID); err != nil {
+ return err
+ }
+ ended = append(ended, p.PID)
+ }
+ if len(ended) == 0 {
+ return errors.New("the Codex app's app-server isn't running")
+ }
+ end := time.Now().Add(codexAppGoneWait)
+ for {
+ ps, err := listProcesses(ctx)
+ if err == nil && !slices.ContainsFunc(ps, func(p proc.Process) bool { return slices.Contains(ended, p.PID) }) {
+ return nil
+ }
+ if time.Now().After(end) {
+ return errors.New("the Codex app's app-server didn't end")
+ }
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(200 * time.Millisecond):
+ }
+ }
+}
diff --git a/internal/provider/codex_app_server_test.go b/internal/provider/codex_app_server_test.go
index fdab13466..88959e4c8 100644
--- a/internal/provider/codex_app_server_test.go
+++ b/internal/provider/codex_app_server_test.go
@@ -456,3 +456,48 @@ func TestCodexAppServerRestartedOnAccountSwitch(t *testing.T) {
t.Fatalf("still said to be on %q after its restart", got)
}
}
+
+// The Agents row's Restart ends only the app-server the app at the bundle
+// runs for itself, and leaves its window, the app itself, another
+// program's --listen server and another bundle's alone (yoshi037070: a
+// quit and open opened a new window).
+func TestRestartCodexAppEndsOnlyItsServer(t *testing.T) {
+ const bundle = "/Applications/ChatGPT.app"
+ ps := []proc.Process{
+ {PID: 1, Args: bundle + "/Contents/MacOS/ChatGPT"},
+ {PID: 2, Args: bundle + "/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex -c features.code_mode_host=true app-server --analytics-default-enabled"},
+ {PID: 3, Args: bundle + "/Contents/Resources/codex app-server --listen ws://127.0.0.1:4500"},
+ {PID: 4, Args: "/Applications/Codex.app/Contents/Resources/codex app-server"},
+ {PID: 5, Args: "/opt/homebrew/bin/codex app-server"},
+ {PID: 6, Args: bundle + "/Contents/Resources/codex exec-server --remote x"},
+ }
+ oldList, oldEnd, oldWait := listProcesses, endCodexAppServer, codexAppGoneWait
+ t.Cleanup(func() { listProcesses, endCodexAppServer, codexAppGoneWait = oldList, oldEnd, oldWait })
+ listProcesses = func(context.Context) ([]proc.Process, error) { return slices.Clone(ps), nil }
+ var ended []int
+ endCodexAppServer = func(pid int) error {
+ ended = append(ended, pid)
+ ps = slices.DeleteFunc(ps, func(p proc.Process) bool { return p.PID == pid })
+ return nil
+ }
+ if err := RestartCodexApp(context.Background(), bundle); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(ended, []int{2}) {
+ t.Fatalf("ended %v, want only the app's own app-server 2", ended)
+ }
+
+ // none running: said
+ ended = nil
+ if err := RestartCodexApp(context.Background(), "/Applications/Other.app"); err == nil || len(ended) > 0 {
+ t.Fatalf("no app-server: %v, ended %v", err, ended)
+ }
+
+ // one that doesn't end: said, not waited on forever
+ ps = append(ps, proc.Process{PID: 7, Args: bundle + "/Contents/Resources/codex app-server"})
+ endCodexAppServer = func(pid int) error { ended = append(ended, pid); return nil }
+ codexAppGoneWait = 300 * time.Millisecond
+ if err := RestartCodexApp(context.Background(), bundle); err == nil {
+ t.Fatal("an app-server that stays: no error")
+ }
+}