agent: the Codex row asks for a reopen only when Codex's models change
Qyburn3 on X ("为什么我每天好多次要重启"): the Agents row of a Codex
app already connected said 已接入 · 退出并重开 Codex 应用后生效 several
times a day.
Cause: StaleCopies counts a running copy as behind when a digest of
what magpie writes for Codex changed after it started. That digest took
magpie-desktop-models.json byte for byte. Beside the ChatGPT sign-in
(since add927e60) that file holds the ChatGPT backend's entries as
sent (base_instructions, comp_hash, available_in_plans...), asked for
again each hour, and each entry's details follow magpie's version and
models.dev, so a rewrite with the same models moved the digest and the
row asked for a reopen. The same digest drives KeepCodexDaemonCurrent,
so the CLI's app-server daemon was restarted for it too.
Fix: of Codex's two lists (magpie-models.json, magpie-desktop-models.json)
the digest takes which models they hold, slug and visibility in no
order (listedModels), beside the wiring keys and magpie's table as
before. A list that doesn't parse is still taken whole. A digest an older
magpie stashed is kept at its time when it matches the files as they are
(readsBefore), so the update itself doesn't ask every user to reopen
once more. Claude Desktop's reads already hash model ids only. The file
is still written only when its bytes differ (deskList); a running Codex
keeps working on its startup copy, and new details reach it on its next
start.
Run at this head (ccbefe2a2 + this), through mote-run:
- go vet ./internal/agent, GOOS=linux and GOOS=windows: ok
- go test ./internal/agent -count=1 -timeout 45m: ok (147.6s)
- wsl-run go test ./internal/agent -run 'TestCodexStale|TestChangedAt': ok
- the real ~/.codex/magpie-desktop-models.json (35 models) through
listedModels in a throwaway test, with every base_instructions,
priority and comp_hash changed and two entries swapped: same part.
Broken by hand: with the old byte-for-byte reads,
TestCodexStaleNotForAListsDetails is red at "the same models, other
details: 1 stale, want 0"; with the readsBefore carry-over off, red at
"an older magpie's stash, nothing changed since: 1 stale, want 0".
Not tried: a real Codex app beside a real ChatGPT sign-in watched over a
day; whether a list that flips between two model sets (a plugin's
listing failing and coming back) still asks for a reopen each flip (it
does: only the last digest is kept). No GUI change, so no GUI run.
This commit is contained in:
@@ -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) |
|
||||
| Uninstall | `magpie uninstall` and Settings › About › Uninstall magpie take magpie off this computer, because deleting magpie's folders by hand left Codex's `openai_base_url` on a gateway that was gone, and every turn failed with a 502 (Jevik_AI on X). `Run` goes in this order. `System` removes the service, opening at login, the Start menu shortcut, `magpie://` links and the privacy model's helper. `Agents` ends Codex's account failover, runs each connected agent's `Disconnect`, or its offline disconnect for a closed app, so the restore keeps what the user changed by hand since. It then ports Codex's rollouts and restarts the Codex app's app-server. `Data` deletes magpie's folders, but keeps the Library while it holds skills, servers or hooks. The executable stays where the user put it. The CLI refuses while another magpie runs, and asks first unless given `--yes`. The app runs `System` and `Agents` from `POST /api/uninstall`. If anything failed, nothing else is removed. Otherwise `POST /api/uninstall/finish` starts a detached `magpie uninstall --data-after <pid>`, which deletes the files once the app has quit, since WebView2 holds its folder open until then. magpie web refuses both routes (`TestUninstall*`, `uninstall-settings.test.cjs`). Every line magpie writes into a TOML, YAML or env config has a `# magpie:` note above it saying how to undo it, so a config left behind still names magpie (`edit.Mark`, `TestMarkedLinesEveryAgent`). | [`uninstall.go`](../../internal/uninstall/uninstall.go), [`uninstall_cli.go`](../../internal/cli/uninstall_cli.go), [`gui/uninstall.go`](../../internal/gui/uninstall.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) |
|
||||
| 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. For Codex that is where its config sends it and which models its lists hold (`listedModels`, slug and visibility), not every byte of each entry: the Codex app's list carries the ChatGPT backend's entries as sent, asked for each hour, and a rewrite with the same models told the user to reopen the app several times a day (Qyburn3 on X). A digest an older magpie stashed over the same files is kept (`readsBefore`). | [`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`); one that has hidden every window and still runs after `appTrayGrace` (1s) is in the tray and has its tree ended at once (`waitClosed`, `winShown`: Claude Desktop hides its window in ~0.6s and keeps all its processes, so waiting the whole `appCloseWait` made a Restart ~12s where quitting by hand takes ~2s, CyberCaius on Discord, 10-29); one still showing a window (a question) gets `appCloseWait` before it is 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) |
|
||||
| Codex windows | Each magpie model's entry in Codex's catalog (`codexcat.entriesAt`, and `listedEntry` for a relay's own entry) says the model's whole window as `context_window`, which Codex shows (95% of it) as the conversation's context. Where Codex compacts goes in the entry's `auto_compact_token_limit`: the threshold set on the model or its provider, else Long conversations' (`settings.Working`, 272K by default), only when that is below the window; Full window writes none. Codex 0.165 compacts at the lesser of it and 90% of the window, and a `model_auto_compact_token_limit` the user put in config.toml comes before it. Until 10-30 the threshold went in `context_window` with the window as `max_context_window`, so a 1M model showed 258K in Codex (01huadalang on Discord); `max_context_window` stays a field magpie owns so `Keep` doesn't carry an old catalog's over. Codex's own models (`codex/`) keep their entry's window. `Tag` carries `catalogFormat`, so a Codex holding a list in the old shape asks again. `TestCodexCatalogCompactAt`, `TestCodexWindowShownCompactApart`. | [`codexcat.go`](../../internal/codexcat/codexcat.go) |
|
||||
|
||||
@@ -2,9 +2,12 @@ package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -253,3 +256,75 @@ func TestCodexStaleOnWindowsIsTheDaemonsLastCheck(t *testing.T) {
|
||||
t.Fatalf("an old check: %+v, want none", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Qyburn3 on X: "为什么我每天好多次要重启" — the Codex row said 已接入 ·
|
||||
// 退出并重开 Codex 应用后生效 several times a day for a Codex app already
|
||||
// connected. Beside the ChatGPT sign-in magpie writes the app's list
|
||||
// (magpie-desktop-models.json) with the backend's entries as it sends
|
||||
// them, asked for again each hour, and every entry's details follow
|
||||
// magpie's version and models.dev; each rewrite counted as a change to
|
||||
// reopen for. Only a change in which models the lists hold (or where the
|
||||
// config sends Codex) does; a stash an older magpie wrote over the same
|
||||
// files is taken as it is.
|
||||
func TestCodexStaleNotForAListsDetails(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)
|
||||
cfg := filepath.Join(dir, "config.toml")
|
||||
desk := filepath.Join(dir, "magpie-desktop-models.json")
|
||||
os.WriteFile(cfg, []byte("model = \"gpt-6-sol\"\nopenai_base_url = \"http://127.0.0.1:3425/backend-api/codex\"\nmodel_catalog_json = \""+tomlString(desk)+"\"\n\n"+
|
||||
"[model_providers.magpie]\nname = \"magpie\"\nbase_url = \"http://127.0.0.1:3425/v1\"\n"), 0o600)
|
||||
entry := func(slug, vis, instr string, prio int) string {
|
||||
return `{"slug":"` + slug + `","visibility":"` + vis + `","base_instructions":"` + instr + `","comp_hash":"` + instr + `","priority":` + strconv.Itoa(prio) + `}`
|
||||
}
|
||||
write := func(entries ...string) {
|
||||
os.WriteFile(desk, []byte(`{"models":[`+strings.Join(entries, ",")+`]}`), 0o644)
|
||||
}
|
||||
write(entry("gpt-6-sol", "list", "v1", 1), entry("codex-auto-review", "hide", "v1", 2), entry("ds/deepseek-v4-pro", "list", "magpie", 3))
|
||||
then := time.Now().Add(-2 * time.Hour)
|
||||
os.Chtimes(cfg, then, then)
|
||||
os.Chtimes(desk, then, then)
|
||||
|
||||
was := running
|
||||
t.Cleanup(func() { running = was })
|
||||
running = func(string) []runningProc {
|
||||
// the Codex app, opened an hour ago
|
||||
return []runningProc{{time.Hour, "/Applications/Codex.app/Contents/Resources/codex app-server --listen stdio://"}}
|
||||
}
|
||||
a := codex(home)
|
||||
if n := a.Stale(); n != 0 {
|
||||
t.Fatalf("opened after the list was written: %d stale, want 0", n)
|
||||
}
|
||||
|
||||
// the backend's entries come back with other details, in another
|
||||
// order, and magpie's entry is written with another priority
|
||||
write(entry("codex-auto-review", "hide", "v2", 1), entry("gpt-6-sol", "list", "v2", 2), entry("ds/deepseek-v4-pro", "list", "magpie 2", 4))
|
||||
if n := a.Stale(); n != 0 {
|
||||
t.Fatalf("the same models, other details: %d stale, want 0", n)
|
||||
}
|
||||
|
||||
// a model magpie serves now: the app opened before lacks it
|
||||
write(entry("codex-auto-review", "hide", "v2", 1), entry("gpt-6-sol", "list", "v2", 2), entry("ds/deepseek-v4-pro", "list", "magpie 2", 4), entry("ds/deepseek-v5", "list", "magpie", 5))
|
||||
if n := a.Stale(); n != 1 {
|
||||
t.Fatalf("a model added: %d stale, want 1", n)
|
||||
}
|
||||
|
||||
// an older magpie's stash, a digest of every byte, over the files as
|
||||
// they are: kept at its time, not a change first seen now
|
||||
old := sha256.Sum256([]byte(a.readsBefore()()))
|
||||
stash(map[string]string{"codex.started": hex.EncodeToString(old[:8]) + " " + strconv.FormatInt(then.UnixNano(), 10)})
|
||||
if n := a.Stale(); n != 0 {
|
||||
t.Fatalf("an older magpie's stash, nothing changed since: %d stale, want 0", n)
|
||||
}
|
||||
if n := codex(home).Stale(); n != 0 {
|
||||
t.Fatalf("asked again: %d stale, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,25 +110,23 @@ func (a *Agent) FailoverSaid() string {
|
||||
// writes the same files (Codex keeps each project's trust, a notice seen,
|
||||
// the model picked in its app in config.toml), and a copy started before
|
||||
// such a write has magpie's list all the same (#729).
|
||||
//
|
||||
// Of Codex's model lists only which models they hold counts, not every
|
||||
// byte of each entry: the Codex app's list (deskList) carries the ChatGPT
|
||||
// backend's entries as the backend sends them, asked for again each hour,
|
||||
// and every entry's details follow magpie's version and models.dev. A
|
||||
// copy running from before such a rewrite has the same models to pick
|
||||
// and works on, yet the row told the user to quit and reopen the Codex
|
||||
// app several times a day (Qyburn3 on X).
|
||||
func (a *Agent) startsWith() (pats []string, files []string, reads func() string) {
|
||||
switch a.ID {
|
||||
case "codex":
|
||||
list := filepath.Join(filepath.Dir(a.Path), "magpie-models.json")
|
||||
// the list written for the Codex app beside the sign-in (deskList)
|
||||
desk := filepath.Join(filepath.Dir(a.Path), "magpie-desktop-models.json")
|
||||
list, desk := codexLists(a.Path)
|
||||
return []string{`(^|/)codex( |$)`}, []string{a.Path, list, desk}, func() string {
|
||||
var b strings.Builder
|
||||
for _, k := range []string{"model_provider", "model_catalog_json", "openai_base_url"} {
|
||||
v, _ := edit.GetTOMLTop(a.Path, k)
|
||||
b.WriteString(k + "=" + v + "\n")
|
||||
}
|
||||
t, _ := edit.GetTOMLTable(a.Path, "model_providers."+magpieID)
|
||||
j, _ := json.Marshal(t)
|
||||
b.Write(j)
|
||||
c, _ := os.ReadFile(list)
|
||||
b.Write(c)
|
||||
d, _ := os.ReadFile(desk)
|
||||
b.Write(d)
|
||||
codexWiring(&b, a.Path)
|
||||
b.WriteString(listedModels(list))
|
||||
b.WriteString(listedModels(desk))
|
||||
return b.String()
|
||||
}
|
||||
case "claude":
|
||||
@@ -141,6 +139,73 @@ func (a *Agent) startsWith() (pats []string, files []string, reads func() string
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
// codexLists are the model lists magpie writes beside Codex's config at
|
||||
// path: its catalog as Codex's provider, and the Codex app's list beside
|
||||
// the sign-in (deskList).
|
||||
func codexLists(path string) (list, desk string) {
|
||||
dir := filepath.Dir(path)
|
||||
return filepath.Join(dir, "magpie-models.json"), filepath.Join(dir, "magpie-desktop-models.json")
|
||||
}
|
||||
|
||||
// codexWiring writes where Codex's config sends it, as magpie writes it:
|
||||
// its provider, its catalog's name, its base URL and magpie's table.
|
||||
func codexWiring(b *strings.Builder, path string) {
|
||||
for _, k := range []string{"model_provider", "model_catalog_json", "openai_base_url"} {
|
||||
v, _ := edit.GetTOMLTop(path, k)
|
||||
b.WriteString(k + "=" + v + "\n")
|
||||
}
|
||||
t, _ := edit.GetTOMLTable(path, "model_providers."+magpieID)
|
||||
j, _ := json.Marshal(t)
|
||||
b.Write(j)
|
||||
}
|
||||
|
||||
// listedModels is which models the Codex model list at path holds, each
|
||||
// slug with its visibility, in no order: what a copy started on it can
|
||||
// pick. A list that doesn't parse is taken whole, its every byte; none
|
||||
// there is "".
|
||||
func listedModels(path string) string {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var l struct {
|
||||
Models []struct {
|
||||
Slug string `json:"slug"`
|
||||
Visibility string `json:"visibility"`
|
||||
} `json:"models"`
|
||||
}
|
||||
if json.Unmarshal(raw, &l) != nil {
|
||||
return "\n" + string(raw)
|
||||
}
|
||||
ms := make([]string, 0, len(l.Models))
|
||||
for _, m := range l.Models {
|
||||
ms = append(ms, m.Slug+" "+m.Visibility)
|
||||
}
|
||||
slices.Sort(ms)
|
||||
return "\n" + filepath.Base(path) + ":" + strings.Join(ms, ",")
|
||||
}
|
||||
|
||||
// readsBefore is what an older magpie read of the files startsWith names,
|
||||
// for a digest it stashed to be taken as the one of now when nothing
|
||||
// changed since: Codex's lists byte for byte. Without it every Codex
|
||||
// started before the update was told to reopen once more. nil for an
|
||||
// agent whose part read the same then.
|
||||
func (a *Agent) readsBefore() func() string {
|
||||
if a.ID != "codex" {
|
||||
return nil
|
||||
}
|
||||
list, desk := codexLists(a.Path)
|
||||
return func() string {
|
||||
var b strings.Builder
|
||||
codexWiring(&b, a.Path)
|
||||
c, _ := os.ReadFile(list)
|
||||
b.Write(c)
|
||||
d, _ := os.ReadFile(desk)
|
||||
b.Write(d)
|
||||
return b.String()
|
||||
}
|
||||
}
|
||||
|
||||
// runningProc is a process found for an agent: how long it has run, and
|
||||
// its command line.
|
||||
type runningProc struct {
|
||||
@@ -176,6 +241,14 @@ func (a *Agent) changedAt(files []string, reads func() string) time.Time {
|
||||
if ok && err == nil && was == digest {
|
||||
return time.Unix(0, n)
|
||||
}
|
||||
// stashed by an older magpie, over the same files as they are now
|
||||
if ok && err == nil && a.readsBefore() != nil {
|
||||
old := sha256.Sum256([]byte(a.readsBefore()()))
|
||||
if was == hex.EncodeToString(old[:8]) {
|
||||
stash(map[string]string{key: digest + " " + at})
|
||||
return time.Unix(0, n)
|
||||
}
|
||||
}
|
||||
// a change no file's time shows (Claude Desktop's models are the
|
||||
// gateway's, not a file's) is put at when it is first seen
|
||||
if ok && err == nil && !mod.After(time.Unix(0, n)) {
|
||||
|
||||
Reference in New Issue
Block a user