agents: the Codex app left on the old list has a Restart that quits and reopens it
The owner (10-23): the Agents row said "quit it with ⌘Q and open it again" and asked for a one-click restart. The app copy's line now has a Restart beside it, like the daemon's. magpie asks the app to quit (osascript "tell application <bundle> to quit", as ⌘Q does), waits up to 30s for every process under the bundle to end, then opens it again. If the app doesn't end in time (for example, it asks something in its window), that is reported and the app is not opened a second time. Only a bundle that StaleCopies lists as an app left on the old list is quit. StaleCopy now carries the app's Bundle. POST /api/codex/app/reopen refuses any other path. This is macOS only; elsewhere the route says so. Run: - go test ./internal/agent -run 'TestCodexAppReopen|TestCodexStale': ok. TestCodexAppReopen went red with the listed-bundle check broken by hand. - go test ./internal/gui -run TestCodexDaemon: ok. - GUI: agent-stale-copies + i18n-keys, chromium and webkit, en zh zh-TW ja de, 980 and 440px: 83 of 83 pass. - Real osascript quit by bundle path and open, on a stand-in .app in the scratchpad: quit ended its process, and open started it again. - gofmt -l clean; GOOS=linux go vet ./internal/agent and GOOS=windows go vet ./internal/agent ./internal/gui: ok. Not tried: quitting the real Codex app (it is the owner's live one), and the full suite.
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
)
|
||||
|
||||
// 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.
|
||||
|
||||
// appQuit and appOpen ask macOS to quit a bundle and to open it; vars so
|
||||
// tests don't touch a real app.
|
||||
var (
|
||||
appQuit = func(ctx context.Context, bundle string) error {
|
||||
out, err := proc.CommandContext(ctx, "osascript", "-e", `tell application "`+strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(bundle)+`" to quit`).CombinedOutput()
|
||||
return cmdErr(out, err)
|
||||
}
|
||||
appOpen = func(ctx context.Context, bundle string) error {
|
||||
out, err := proc.CommandContext(ctx, "open", bundle).CombinedOutput()
|
||||
return cmdErr(out, err)
|
||||
}
|
||||
)
|
||||
|
||||
// appQuitWait is how long a quit app's processes have to end.
|
||||
var appQuitWait = 30 * time.Second
|
||||
|
||||
func cmdErr(out []byte, err error) error {
|
||||
if err != nil && len(strings.TrimSpace(string(out))) > 0 {
|
||||
return errors.New(strings.TrimSpace(string(out)))
|
||||
}
|
||||
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")
|
||||
|
||||
// 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.
|
||||
func ReopenCodexApp(ctx context.Context, bundle string) error {
|
||||
if runtime.GOOS != "darwin" {
|
||||
return errors.New("only the macOS Codex app is reopened by magpie")
|
||||
}
|
||||
a, err := Find("codex")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return reopenApp(ctx, a, bundle)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"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.
|
||||
func TestCodexAppReopen(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip(staleOnWindows)
|
||||
}
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
t.Setenv("CODEX_HOME", "")
|
||||
dir := filepath.Join(home, ".codex")
|
||||
os.MkdirAll(dir, 0o755)
|
||||
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 })
|
||||
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://"},
|
||||
}
|
||||
var out []runningProc
|
||||
for _, p := range ps {
|
||||
if strings.Contains(pat, "codex") && strings.Contains(p.cmd, "codex ") || strings.Contains(pat, `Codex\.app/Contents/`) {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
var did []string
|
||||
appQuit = func(_ context.Context, b string) error { did = append(did, "quit "+b); up = false; return nil }
|
||||
appOpen = func(_ context.Context, b string) error { did = append(did, "open "+b); return nil }
|
||||
a := codex(home)
|
||||
|
||||
if err := reopenApp(context.Background(), a, "/Applications/Other.app"); err == nil || len(did) > 0 {
|
||||
t.Fatalf("an app not listed: %v, did %v", err, did)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -191,9 +191,12 @@ type StaleCopy struct {
|
||||
// subcommand the daemon spawns beside itself, no copy to reopen) or
|
||||
// "cli"; "" for other agents; "embedded" is another app's own Codex,
|
||||
// named by App
|
||||
Kind string `json:"kind,omitempty"`
|
||||
App string `json:"app,omitempty"`
|
||||
Since time.Time `json:"since"`
|
||||
Kind string `json:"kind,omitempty"`
|
||||
App string `json:"app,omitempty"`
|
||||
// Bundle is the desktop app's own, for "app": what the row's Restart
|
||||
// quits and opens again
|
||||
Bundle string `json:"bundle,omitempty"`
|
||||
Since time.Time `json:"since"`
|
||||
}
|
||||
|
||||
// StaleCopies are the copies Stale counts. Reopening one kind doesn't end
|
||||
@@ -243,8 +246,11 @@ func (a *Agent) StaleCopies() []StaleCopy {
|
||||
// is no Codex to quit (#1461)
|
||||
continue
|
||||
}
|
||||
if c.Kind == "embedded" {
|
||||
switch c.Kind {
|
||||
case "embedded":
|
||||
c.App = app
|
||||
case "app":
|
||||
c.Bundle = app
|
||||
}
|
||||
if app != "" {
|
||||
if i, ok := apps[app]; ok {
|
||||
|
||||
@@ -1830,6 +1830,29 @@ function daemonRestart() {
|
||||
return go;
|
||||
}
|
||||
|
||||
// appReopen is the Restart beside the Codex app left on the old list: magpie
|
||||
// quits it, as ⌘Q does, and opens it again
|
||||
function appReopen(bundle) {
|
||||
const go = el("button", "ag-quiet accent", t("Restart"));
|
||||
go.type = "button";
|
||||
go.title = bundle;
|
||||
go.onclick = async () => {
|
||||
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"));
|
||||
} catch (e) {
|
||||
go.disabled = false;
|
||||
go.classList.remove("busy");
|
||||
status(e.message, "err");
|
||||
}
|
||||
};
|
||||
return go;
|
||||
}
|
||||
|
||||
// connectPanel: a connected agent's row, opened
|
||||
function connectPanel(a, { fields, fieldBtn }) {
|
||||
const box = el("div", "ag-exp");
|
||||
@@ -1883,6 +1906,7 @@ function connectPanel(a, { fields, fieldBtn }) {
|
||||
// session is on it: with one on, here, when the user says (open
|
||||
// sessions of Codex 0.162 reconnect to the new one)
|
||||
if (c.kind === "daemon" && a.id === "codex") l.append(daemonRestart());
|
||||
if (c.kind === "app" && a.id === "codex" && c.bundle) l.append(appReopen(c.bundle));
|
||||
parts.push(l);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1774,6 +1774,7 @@ const I18N = {
|
||||
"Later": "稍后",
|
||||
"Restart": "重启",
|
||||
"Codex's background service restarted": "Codex 的后台服务已重启",
|
||||
"The Codex app reopened": "Codex 应用已重新打开",
|
||||
"{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.": "{agent} 的登录信息,读自其自身文件;在那里退出登录,此供应商随之消失。",
|
||||
"Models": "模型",
|
||||
"Endpoints": "端点",
|
||||
@@ -5652,6 +5653,7 @@ const I18N = {
|
||||
"Later": "稍後",
|
||||
"Restart": "重啟",
|
||||
"Codex's background service restarted": "Codex 的後臺服務已重啟",
|
||||
"The Codex app reopened": "Codex 應用已重新打開",
|
||||
"{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.": "{agent} 的登入資訊,讀自其自身檔案;在那裡退出登入,此供應商隨之消失。",
|
||||
"Models": "模型",
|
||||
"Endpoints": "端點",
|
||||
@@ -9507,6 +9509,7 @@ const I18N = {
|
||||
"Later": "後で",
|
||||
"Restart": "再起動",
|
||||
"Codex's background service restarted": "Codex のバックグラウンドサービスを再起動しました",
|
||||
"The Codex app reopened": "Codex アプリを開き直しました",
|
||||
"{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.": "{agent} のサインイン(そのファイルから読み込み)。そちらでサインアウトするとこのプロバイダは消えます。",
|
||||
"Models": "モデル",
|
||||
"Endpoints": "エンドポイント",
|
||||
@@ -13392,6 +13395,7 @@ 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",
|
||||
"{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.": "Die Anmeldung von {agent}, aus dessen eigenen Dateien gelesen. Melden Sie sich dort ab, verschwindet dieser Anbieter.",
|
||||
"Models": "Modelle",
|
||||
"Endpoints": "Endpunkte",
|
||||
|
||||
@@ -2078,6 +2078,22 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
}
|
||||
writeJSON(rw, providersState())
|
||||
})
|
||||
// The Codex desktop app left on the model list before a change (the
|
||||
// Agents row's Restart): quit it and open it again.
|
||||
mux.HandleFunc("POST /api/codex/app/reopen", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Bundle string }
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
||||
defer cancel()
|
||||
if err := agent.ReopenCodexApp(ctx, in.Bundle); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, map[string]bool{"ok": true})
|
||||
})
|
||||
// A provider's several keys: add one, put one in use, name or remove it.
|
||||
mux.HandleFunc("POST /api/keys/{action}", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
|
||||
@@ -192,3 +192,47 @@ 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
|
||||
// quits the app named by its bundle and opens it again
|
||||
const reopened = { en: "The Codex app reopened", zh: "Codex 应用已重新打开", "zh-TW": "Codex 應用已重新打開", ja: "Codex アプリを開き直しました", de: "Codex-App neu geöffnet" };
|
||||
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) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await browser.newPage({ viewport: { width, height: 800 } });
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
let agent = { ...codex, stale: 1, staleCopies: [{ kind: "app", bundle: "/Applications/Codex.app", since: days(3) }] };
|
||||
const asked = [];
|
||||
const fake = serve(lang);
|
||||
await page.route("**/*", async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.pathname === "/api/codex/app/reopen") {
|
||||
asked.push(route.request().postDataJSON());
|
||||
agent = { ...agent, stale: 0, staleCopies: [] };
|
||||
return route.fulfill({ json: { ok: true } });
|
||||
}
|
||||
if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [agent], profiles: [], settings: { lang, theme: "light" } } });
|
||||
return fake(route);
|
||||
});
|
||||
await page.goto("http://magpie.test/?view=agents");
|
||||
await page.locator(`${row} .ag-conn`).waitFor();
|
||||
await page.locator(`${row} .ag-link`).click();
|
||||
const go = page.locator(`${row} .ag-stale-copy button`);
|
||||
await go.waitFor();
|
||||
assert.equal((await go.textContent()).trim(), restartSays[lang]);
|
||||
const box = await go.boundingBox();
|
||||
assert.ok(box.x + box.width <= width, "past the window");
|
||||
await go.click();
|
||||
await page.waitForFunction((r) => !document.querySelector(r + " .ag-stale-copy"), row);
|
||||
assert.deepEqual(asked, [{ bundle: "/Applications/Codex.app" }]);
|
||||
assert.equal(await page.locator("#status").textContent(), reopened[lang]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user