Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
codex: the daemon magpie restarts asks macOS for folders in its own name, not magpie's (reformed9448 on Discord)
yetone531b44a9a82d
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex 7d7363756..9349aeac2 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -114,7 +114,7 @@ something else shows up as drift.- Listing never starts a stopped WSL distro. A stopped distro's agent shows what was last seen there (`asleep`, `wsl.json`); setting one of its fields writes its files, which starts the distro.- Codex's sign-in (`login`) is ChatGPT (`""`, the default), Always ChatGPT (`chatgpt`) or magpie API (`api`). With ChatGPT, magpie's models join Codex's own beside the sign-in (`openai_base_url`), and while the Codex app holds the ChatGPT account Codex is signed in to (`codexUsedUp`, `provider.CodexUsedUp`: OpenAI no longer allows the account and it has no credits left, a workspace still within its overage excepted), magpie is made Codex's provider (`codex.out`): the Codex app sends nothing at all on an account it holds, a magpie model's turn included (#540), and as a provider of its own magpie is past that. A window at 100% with credits left doesn't count, and Codex stays signed in. Sync puts it back beside the sign-in once the account has room. Always ChatGPT never does that: Codex stays in its ChatGPT state, and the Codex app may send nothing till the account has room, while Codex CLI's turns still reach magpie by the base URL, and its routing and other accounts serve them. With magpie API, Codex's `getAuthStatus` returns no token (its provider has no `requires_openai_auth`), so its Chrome control turns away; the option's note says to pick ChatGPT to keep it (#1824). While magpie is Codex's provider (magpie API, or `codex.out`), `Joined` reports false although the `codex.joined` mark stays for Sync's way back: the Agents row said Codex's own models stay in `/model` beside magpie's, the ChatGPT state the Codex app blocks sending in, and the app only leaves that state once it is restarted (#2267, `TestCodexProviderIsNotJoined`). A Codex that reaches the gateway from another machine (a WSL distro under NAT, or `MAGPIE_ADDR` pinned beyond loopback, `onAnotherMachine(at.gw())`) is wired as one with no ChatGPT sign-in (`chatGPT()` is false there): never joined or beside, since beside its sign-in it would send its ChatGPT token to `/backend-api/codex`, and from there the gateway takes a named key alone, so every request was a 401 (#2145, `TestCodexBeyondLoopbackNotJoined`). magpie is its provider and it sends `gwKey()`, the LAN sharing key; one of its own models picked goes straight to OpenAI on its sign-in.- Whether Codex is signed in to ChatGPT is read from its auth.json or keychain item (`codexChatGPTKnown`, `provider.CodexSignInKnown`). Codex rewrites auth.json in place when it refreshes its tokens (codex-rs `FileAuthStorage::save` opens it with truncate), so a read in that moment finds it empty or cut off, and a keychain read can fail for a moment. Such a read is unknown, and Codex is taken to be as magpie last wired it (joined, beside, or `codex.out`); only a sign-in that isn't there (no auth.json, no item) or holds no ChatGPT token is "not signed in". Taking an unknown read for "not signed in" made Sync or a pick move Codex from beside its sign-in to magpie as its provider, with no `codex.out` to bring it back, and the Codex app showed "magpie" for its account and magpie's catalog for its models, on and off (lucy on Discord, v0.1.1394; `TestCodexHalfWrittenAuthKeepsSignIn`, `TestCodexHalfWrittenAuthKeepsOut`, `TestCodexSignInKnown`).-- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next — never for a Codex that reaches the gateway from another machine, where that path takes a named key alone and the failed-over turn came back a 401 (#2145, `TestCodexFailoverBeyondLoopbackNotWritten`); Sync takes one it wrote before off again. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place.+- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next — never for a Codex that reaches the gateway from another machine, where that path takes a named key alone and the failed-over turn came back a 401 (#2145, `TestCodexFailoverBeyondLoopbackNotWritten`); Sync takes one it wrote before off again. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). Every restart magpie makes runs `codex app-server daemon restart` as its own responsible process on macOS (`proc.CombinedOutputOwn`, a disclaimed `posix_spawn`): the daemon works in the folder of each codex attached to it, and as magpie's child the first codex in ~/Desktop had macOS ask for the Desktop folder in magpie's name (reformed9448 on Discord; `TestRestartedCodexDaemonIsNotMagpies`). A magpie built without cgo (the CLI) still restarts it as its own child. A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place.- A Codex thread keeps the provider it was started on. While a magpie model is on, CC Switch's provider tables go through magpie too (`takeTables`), and get their own base URL back when Codex steps off magpie (`giveTables`, stash `codex.tables`). CC Switch's OpenAI mirror (a table of another id, `name = "OpenAI"`, `requires_openai_auth`, no `base_url`) isn't reached by `openai_base_url`, which takes only the built-in provider to magpie: a thread started on it and reopened went straight to ChatGPT, which refused the magpie model picked in it, and magpie never saw the request (#1796). While Codex goes to magpie by the base URL, `takeMirrors` gives each such mirror magpie's ChatGPT backend as its `base_url` (stash `codex.mirrors`), and `giveMirrors` takes it off again; a mirror a profile names, or one whose `base_url` was changed since, stays as it is. Moving the threads onto another provider is the Sessions page's Move (#887).- An agent's config is written in the form the installed version reads, taken from what that version declares, not the latest one. VSCodium has no Copilot Chat of its own, and the Marketplace's last one (0.48.1) has no Custom Endpoint provider, only OpenAI Compatible (`customoai`, #1014). magpie reads the provider list in the package.json of the `github.copilot-chat` installed under `~/.vscode-oss/extensions` (`vscodeChatOf`). It writes its group for `customendpoint` when that is declared, for `customoai` when only that is, with each model's window as `maxInputTokens` + `maxOutputTokens` and the token as `x-api-key` (that version drops an Authorization in `requestHeaders`). A missing or unreadable extension keeps `customendpoint`. Sync rewrites a group written for the other provider, and Check reports it, as it does a Copilot Chat declaring neither. That Copilot Chat registers its providers only while signed in to GitHub with a personal Copilot plan, which the Notice says.- Tuned settings are written only on the user's click, never by Sync or Connect. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Codex's window is the one magpie's catalog lists for each model it ran (typed, or the vendor's), and with none in config.toml it runs now at what magpie tells Codex (`provider.CompactFor`, else Long conversations in the agent's opened row, as `codexcat` writes it); a model of magpie's whose window isn't known caps nothing short of 1M (or the user's own larger value), never the largest prompt seen (zhemu on Discord: a 1M model at 750K was offered up to 410K), and only Codex's own models, outside the catalog, keep 272K or the largest prompt (`codexWindow`, `TestTuneWindowsAreTheUsers`). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest; with the compactions timed, it never advises a window that compacts more often than the one now, so never a longer wait: of the windows that compact no more often it takes the cheapest, and of those within 3% of that (`sameCost`, the same bar as changing at all) the one that compacts least, the larger of two that compact as often. Tokens and seconds share no unit the files measure, so the advice doesn't trade one for the other at a guessed rate; a cheaper window that waits longer is said with its wait in the row and the picker, for the user to choose. The wait per compaction is taken as the same at every window: the files time compactions only near the window the user ran with, too narrow to fit how it grows with the prompt. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.diff --git a/internal/proc/disclaim.go b/internal/proc/disclaim.gonew file mode 100644index 000000000..b210f2983--- /dev/null+++ b/internal/proc/disclaim.go@@ -0,0 +1,30 @@+package proc++import (+ "context"+ "os/exec"+)++// On macOS, a privacy prompt (Desktop, Documents, Downloads, a removable+// volume…) names the process responsible for the one asking, and a child+// is the responsibility of whoever started it, down through every process+// it starts in turn. So a long-lived process magpie starts for an agent —+// Codex's app-server daemon, which every codex run in a terminal attaches+// to and works in the folder it was run in — asks in magpie's name: the+// first `codex` in ~/Desktop had macOS say magpie wants the Desktop+// folder (reformed9448 on Discord). CombinedOutputOwn starts such a+// command as its own responsible process instead, as a terminal's would+// be asked about under the terminal's name rather than magpie's.++// CombinedOutputOwn runs cmd, as made by Command or CommandContext with+// ctx, to its end and returns its output, stdout and stderr together, as+// cmd.CombinedOutput does; stdin is the null device. On macOS (built with+// cgo) the command, and what it starts, answer for themselves to macOS's+// privacy prompts rather than to magpie. Elsewhere it is+// cmd.CombinedOutput.+func CombinedOutputOwn(ctx context.Context, cmd *exec.Cmd) ([]byte, error) {+ if cmd.Err != nil {+ return nil, cmd.Err+ }+ return combinedOutputOwn(ctx, cmd)+}diff --git a/internal/proc/disclaim_darwin.go b/internal/proc/disclaim_darwin.gonew file mode 100644index 000000000..71fb7dbce--- /dev/null+++ b/internal/proc/disclaim_darwin.go@@ -0,0 +1,169 @@+//go:build darwin && cgo++package proc++/*+#include <dlfcn.h>+#include <errno.h>+#include <fcntl.h>+#include <signal.h>+#include <spawn.h>+#include <stdlib.h>+#include <sys/types.h>++// responsibility_spawnattrs_setdisclaim (libSystem, macOS 10.14 on) has+// the child answer for itself to TCC; looked up, as it has no header.+static int magpie_spawn_own(const char *path, char *const argv[], char *const envp[], const char *dir, int out, pid_t *pid) {+ posix_spawnattr_t attr;+ posix_spawn_file_actions_t fa;+ int err = posix_spawnattr_init(&attr);+ if (err != 0) return err;+ err = posix_spawn_file_actions_init(&fa);+ if (err != 0) { posix_spawnattr_destroy(&attr); return err; }+ sigset_t none, all;+ sigemptyset(&none);+ sigfillset(&all);+ posix_spawnattr_setsigmask(&attr, &none);+ posix_spawnattr_setsigdefault(&attr, &all);+ // only stdin, stdout and stderr are passed on, none of magpie's own+ posix_spawnattr_setflags(&attr, POSIX_SPAWN_CLOEXEC_DEFAULT | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF);+ int (*disclaim)(posix_spawnattr_t *, int) = (int (*)(posix_spawnattr_t *, int))dlsym(RTLD_DEFAULT, "responsibility_spawnattrs_setdisclaim");+ if (disclaim != NULL) disclaim(&attr, 1);+ posix_spawn_file_actions_addopen(&fa, 0, "/dev/null", O_RDONLY, 0);+ posix_spawn_file_actions_adddup2(&fa, out, 1);+ posix_spawn_file_actions_adddup2(&fa, out, 2);+ if (dir != NULL) posix_spawn_file_actions_addchdir_np(&fa, dir);+ err = posix_spawn(pid, path, &fa, &attr, argv, envp);+ posix_spawn_file_actions_destroy(&fa);+ posix_spawnattr_destroy(&attr);+ return err;+}++static int magpie_responsible(pid_t pid) {+ pid_t (*f)(pid_t) = (pid_t (*)(pid_t))dlsym(RTLD_DEFAULT, "responsibility_get_pid_responsible_for_pid");+ if (f == NULL) return 0;+ pid_t r = f(pid);+ return r > 0 ? (int)r : 0;+}+*/+import "C"++import (+ "bytes"+ "context"+ "fmt"+ "io"+ "os"+ "os/exec"+ "syscall"+ "time"+ "unsafe"+)++// cStrings is ss as a NULL-ended C array, and its freeing.+func cStrings(ss []string) (**C.char, func()) {+ arr := (**C.char)(C.malloc(C.size_t(len(ss)+1) * C.size_t(unsafe.Sizeof(uintptr(0)))))+ view := unsafe.Slice(arr, len(ss)+1)+ for i, s := range ss {+ view[i] = C.CString(s)+ }+ view[len(ss)] = nil+ return arr, func() {+ for i := range ss {+ C.free(unsafe.Pointer(view[i]))+ }+ C.free(unsafe.Pointer(arr))+ }+}++// spawnOwn starts cmd as its own responsible process, its stdout and+// stderr on out.+func spawnOwn(cmd *exec.Cmd, out *os.File) (int, error) {+ env := cmd.Env+ if env == nil {+ env = os.Environ()+ }+ path := C.CString(cmd.Path)+ defer C.free(unsafe.Pointer(path))+ argv, freeArgv := cStrings(cmd.Args)+ defer freeArgv()+ envp, freeEnvp := cStrings(env)+ defer freeEnvp()+ var dir *C.char+ if cmd.Dir != "" {+ dir = C.CString(cmd.Dir)+ defer C.free(unsafe.Pointer(dir))+ }+ var pid C.pid_t+ if e := C.magpie_spawn_own(path, argv, envp, dir, C.int(out.Fd()), &pid); e != 0 {+ return 0, &os.PathError{Op: "posix_spawn", Path: cmd.Path, Err: syscall.Errno(e)}+ }+ return int(pid), nil+}++func combinedOutputOwn(ctx context.Context, cmd *exec.Cmd) ([]byte, error) {+ r, w, err := os.Pipe()+ if err != nil {+ return nil, err+ }+ pid, err := spawnOwn(cmd, w)+ w.Close()+ if err != nil {+ r.Close()+ return nil, err+ }+ var buf bytes.Buffer+ read := make(chan struct{})+ go func() {+ io.Copy(&buf, r)+ close(read)+ }()+ type exit struct {+ ws syscall.WaitStatus+ err error+ }+ waited := make(chan exit, 1)+ go func() {+ for {+ var ws syscall.WaitStatus+ _, err := syscall.Wait4(pid, &ws, 0, nil)+ if err != syscall.EINTR {+ waited <- exit{ws, err}+ return+ }+ }+ }()+ var x exit+ select {+ case x = <-waited:+ case <-ctx.Done():+ syscall.Kill(pid, syscall.SIGKILL)+ x = <-waited+ }+ // what it started may hold the output open; it is let go a moment+ // after, as CommandContext's WaitDelay does+ select {+ case <-read:+ case <-time.After(waitDelay):+ r.Close()+ <-read+ }+ r.Close()+ if err := ctx.Err(); err != nil {+ return buf.Bytes(), err+ }+ if x.err != nil {+ return buf.Bytes(), x.err+ }+ switch {+ case x.ws.Signaled():+ return buf.Bytes(), fmt.Errorf("signal: %v", x.ws.Signal())+ case x.ws.ExitStatus() != 0:+ return buf.Bytes(), fmt.Errorf("exit status %d", x.ws.ExitStatus())+ }+ return buf.Bytes(), nil+}++// Responsible is the process macOS holds responsible for pid, the one its+// privacy prompts name; 0 when that can't be told.+func Responsible(pid int) int { return int(C.magpie_responsible(C.pid_t(pid))) }diff --git a/internal/proc/disclaim_other.go b/internal/proc/disclaim_other.gonew file mode 100644index 000000000..4015cee5e--- /dev/null+++ b/internal/proc/disclaim_other.go@@ -0,0 +1,16 @@+//go:build !darwin || !cgo++package proc++import (+ "context"+ "os/exec"+)++func combinedOutputOwn(_ context.Context, cmd *exec.Cmd) ([]byte, error) {+ return cmd.CombinedOutput()+}++// Responsible is the process macOS holds responsible for pid, 0 when that+// can't be told (here, always).+func Responsible(pid int) int { return 0 }diff --git a/internal/proc/disclaim_test.go b/internal/proc/disclaim_test.gonew file mode 100644index 000000000..ff55c7008--- /dev/null+++ b/internal/proc/disclaim_test.go@@ -0,0 +1,98 @@+package proc++import (+ "context"+ "os"+ "os/exec"+ "runtime"+ "strconv"+ "strings"+ "testing"+ "time"+)++// startsLeft runs, through run, a shell that leaves a sleep running on its+// own (as `codex app-server daemon restart` leaves the daemon) and says its+// pid; the sleep ends with the test.+func startsLeft(t *testing.T, run func(*exec.Cmd) ([]byte, error)) int {+ t.Helper()+ cmd := CommandContext(context.Background(), "/bin/sh", "-c", "sleep 30 >/dev/null 2>&1 </dev/null & echo $!")+ out, err := run(cmd)+ if err != nil {+ t.Fatalf("%v: %s", err, out)+ }+ pid, err := strconv.Atoi(strings.TrimSpace(string(out)))+ if err != nil {+ t.Fatalf("output %q", out)+ }+ t.Cleanup(func() {+ if p, err := os.FindProcess(pid); err == nil {+ p.Kill()+ }+ })+ return pid+}++// What a command magpie leaves running asks macOS's privacy prompts in+// its own name, not magpie's (reformed9448 on Discord: the first codex in+// ~/Desktop, attached to the Codex daemon magpie had restarted, had macOS+// say magpie wants the Desktop folder).+func TestCombinedOutputOwnAnswersForItself(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("macOS's responsibility for a process")+ }+ self := Responsible(os.Getpid())+ if self == 0 {+ t.Skip("macOS doesn't say who is responsible for this process")+ }+ // started the plain way, what is left running is this process's+ // responsibility+ if got := Responsible(startsLeft(t, (*exec.Cmd).CombinedOutput)); got != self {+ t.Fatalf("a plain child's sleep answers to %d, want %d as this process does", got, self)+ }+ got := Responsible(startsLeft(t, func(c *exec.Cmd) ([]byte, error) { return CombinedOutputOwn(context.Background(), c) }))+ if got == 0 || got == self {+ t.Fatalf("the sleep answers to %d, this process to %d: want one of its own", got, self)+ }+}++func TestCombinedOutputOwnRuns(t *testing.T) {+ dir := t.TempDir()+ cmd := Command("/bin/sh", "-c", "pwd; echo \"$MAGPIE_T\"; echo err >&2; if [ -p /dev/stdin ]; then echo pipe; else echo other; fi; exit 3")+ cmd.Env = append(os.Environ(), "MAGPIE_T=v")+ cmd.Dir = dir+ out, err := CombinedOutputOwn(context.Background(), cmd)+ if err == nil || err.Error() != "exit status 3" {+ t.Errorf("err %v, want exit status 3", err)+ }+ real, _ := os.Readlink(dir)+ lines := strings.Fields(string(out))+ if len(lines) != 4 || (lines[0] != dir && lines[0] != real && !strings.HasSuffix(lines[0], dir)) || lines[1] != "v" || lines[2] != "err" || lines[3] != "other" {+ t.Errorf("output %q", out)+ }+ if out, err := CombinedOutputOwn(context.Background(), Command("/bin/sh", "-c", "echo ok")); err != nil || string(out) != "ok\n" {+ t.Errorf("%q, %v", out, err)+ }+ if _, err := CombinedOutputOwn(context.Background(), Command("/nonexistent/magpie-x")); err == nil {+ t.Error("a missing program ran")+ }+}++// The context ending ends the command, and the run with it.+func TestCombinedOutputOwnContext(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() {+ _, err := CombinedOutputOwn(ctx, CommandContext(ctx, "/bin/sh", "-c", "exec sleep 30"))+ done <- err+ }()+ cancel()+ select {+ case err := <-done:+ if err != context.Canceled {+ t.Errorf("err %v, want canceled", err)+ }+ case <-time.After(20 * time.Second):+ t.Fatal("still running after its context ended")+ }+}diff --git a/internal/provider/codex_daemon.go b/internal/provider/codex_daemon.goindex ab2f96aaa..9853b274d 100644--- a/internal/provider/codex_daemon.go+++ b/internal/provider/codex_daemon.go@@ -305,7 +305,11 @@ func restartCodexDaemon(ctx context.Context, home string) error {if err != nil {return err}- if out, err := cmd.CombinedOutput(); err != nil {+ // run as its own responsible process: the daemon it leaves running+ // works in the folder of every codex attached to it, and macOS would+ // otherwise ask for ~/Desktop and the like in magpie's name+ // (reformed9448 on Discord)+ if out, err := proc.CombinedOutputOwn(ctx, cmd); err != nil {if msg := lastLine(out); msg != "" {return errors.New("codex app-server daemon restart: " + msg)}diff --git a/internal/provider/codex_daemon_test.go b/internal/provider/codex_daemon_test.goindex 4881befec..a37876334 100644--- a/internal/provider/codex_daemon_test.go+++ b/internal/provider/codex_daemon_test.go@@ -7,6 +7,7 @@ import ("path/filepath""runtime""slices"+ "strconv""strings""testing""time"@@ -254,6 +255,47 @@ func TestRestartCodexDaemonFails(t *testing.T) {}}+// The daemon a restart leaves running answers for itself to macOS's+// privacy prompts, not to magpie: every codex attached to it works in its+// own folder, and the first one in ~/Desktop had macOS say magpie wants+// the Desktop folder (reformed9448 on Discord).+func TestRestartedCodexDaemonIsNotMagpies(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("macOS's responsibility for a process")+ }+ self := proc.Responsible(os.Getpid())+ if self == 0 {+ t.Skip("macOS doesn't say who is responsible for this process")+ }+ fakeCodex(t, 0)+ // a codex whose restart leaves a daemon (a sleep) running, and says+ // its pid+ dir := t.TempDir()+ left := filepath.Join(dir, "daemon.pid")+ exe := filepath.Join(dir, "codex")+ testenv.Program(t, exe, "#!/bin/sh\nsleep 30 >/dev/null 2>&1 </dev/null &\necho $! > '"+left+"'\n")+ codexExecutable = func() string { return exe }+ if err := RestartCodexDaemon(context.Background()); err != nil {+ t.Fatal(err)+ }+ b, err := os.ReadFile(left)+ if err != nil {+ t.Fatal(err)+ }+ pid, err := strconv.Atoi(strings.TrimSpace(string(b)))+ if err != nil {+ t.Fatalf("pid %q", b)+ }+ t.Cleanup(func() {+ if p, err := os.FindProcess(pid); err == nil {+ p.Kill()+ }+ })+ if got := proc.Responsible(pid); got == 0 || got == self {+ t.Fatalf("the daemon answers to %d, magpie to %d: want one of its own", got, self)+ }+}+// Switching Codex's account notes the daemon left on the one before; the// switch to the account Codex is on already changes nothing.func TestSwitchLoginNotesCodexDaemon(t *testing.T) {