agent: Claude Science goes back on magpie after its app starts its own daemon
shuitunlulu_ on Discord: after magpie connected Claude Science, it went
back off magpie. The daemon reads the gateway only from its environment's
ANTHROPIC_BASE_URL. The 0.1.72 app (Electron) attaches its window to a
daemon running; with none it starts its own (`serve --stdio
--adopt-install`, launch_context app-child) in its own environment, which
has no such variable. Its "let the app run it instead", and the offer it
makes once it updated past the daemon, stop magpie's daemon to do the
same. The keeper only started a daemon when none ran, so the app's stayed.
KeepClaudeScience now puts magpie's daemon back on the port the other was
on (stop, serve --detached with the variable) in three cases: a daemon
magpie didn't start, one started for the gateway's old address, or its
own older than the program installed (`--version`, asked again only when
the file changed). It does this only when status says no session runs
(active_frames and active_conversations 0; a status without them counts
as busy). It never touches one launchd or systemd keeps, and does it at
most three times an hour. It reads operon.lock every 10s and asks status
when the lock's pid changed or a minute went by.
Run:
- go test ./internal/agent (mote): ok 261s
- gofmt -l, go vet for darwin, linux and windows (mote): clean
- Real Claude Science 0.1.72 on mote, the keeper driven through a
throwaway test (not committed) against the real claude-science:
- App attached to a terminal daemon: status parsed (idle, terminal),
the daemon was replaced on port 18481 and the new one has
ANTHROPIC_BASE_URL. shell.log says "adopted daemon restarted
(45446 → 89598) — following the successor", so the window carried on.
- App opened with no daemon: it started its own (app-child, port 8000,
no ANTHROPIC_BASE_URL in ps -E). The keeper replaced it on 8000 with
the variable, and the app showed its "stopped from the command line"
screen. Reopening the app attached it to magpie's daemon
(ADOPT-RUNNING).
- Broken by hand, each red: no idle check (the busy and unknown-status
cases), no retake cap, no version skew, no lock-pid trigger.
Not tried:
- The screen's "start it again in the app" button (read in main.js:
runInvariant adopts the daemon running; reopening the app did the
same).
- A daemon with a session running: one would need a Claude sign-in.
The fake covers it.
- The Windows attach shell, and Linux.
Reported-by: shuitunlulu_
This commit is contained in:
@@ -34,7 +34,7 @@ something else shows up as drift.
|
||||
| Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`), each model's tokens weighed at what magpie bills them where the agent asked for a model magpie wrote (a provider/model id resolves as the gateway resolves it and is weighed at that provider's price, `pricedWeights`, so a Claude model on Copilot has its 1-hour cache write at the 5-minute one Copilot bills, #3435), else at its maker's list ratios (`tune.WeightsFor`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings.<model>.autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated tokens against the setting now (fewer or more, the setting itself marked "Your setting now", hayden4608 on Discord), "Fewest tokens" beside the leanest, and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) |
|
||||
| Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. One whose agent keeps the model a new session starts on in a file apart from its provider list says so with `startup` (`config`, `format`, `model`, and `keys` written beside the model as they are) and has no `model`: PiG keeps its providers in `models.json` and `defaultProvider`/`defaultModel` in `settings.json` (str_ on Discord: its row only listed models, where Pi's picks the one it starts on). Its field is `model` again; picking one of magpie's writes `connect`'s keys into `config` and the model and `startup.keys` into `startup.config`, each file stashed under its own `plugin:<id>:<path>` (the startup one marked by its first string key, so a model picked in the agent among magpie's, with `defaultProvider` still `magpie`, reads as magpie's). A model of the agent's own picked in it while `connect`'s keys are still in `config` is `Beside`: connected, not drift, and Disconnect leaves that pick and takes the rest out. A magpie without `startup` reads the same module as connect only (`TestPluggedStartupModel`, `TestPluggedStartupOwnPickKept`, `TestPluggedStartupRestoreGone`). `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`; a routing group's, `provider.GroupEndpoints`, the APIs every member relays as it is; carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) |
|
||||
| Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL` and `--model` (no `--model` when the user gives one) while settings.json's model is still magpie's, and unchanged otherwise. PowerShell's asks `magpie agy env` for them, since the Windows app is a GUI program PowerShell doesn't wait for. `Typed` says the function is there; the row then says plain `agy` works in a new terminal, and the `Launch` command is for a terminal open before. agy has no settings-only route: 1.4.7 refuses to start without `GEMINI_API_KEY` in the environment even with a key on the custom model. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`pickedEfforts`, #1003). Antigravity's app has the same field while it is on magpie: its picker lists the gateway's models with no level of its own, so one of Antigravity's families of levels went at its default (MDX-Tom, #4838). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) |
|
||||
| Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer), each minute while magpie serves; it never stops one running. `Check` reads the daemon's `operon.lock`, not `status` (seconds for a 130 MB Bun program), and calls a daemon with another pid drift: the app's window, opened while none ran, starts its own without the variable. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). | [`claudescience.go`](../../internal/agent/claudescience.go), [`science.go`](../../internal/gateway/science.go) |
|
||||
| Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer). The app (0.1.72, Electron) attaches its window to a daemon running; with none it starts its own (`serve --stdio --adopt-install`, `launch_context` `app-child`) in its own environment, without the variable, and its "let the app run it instead" (and its offer once the app updated past the daemon) stops magpie's to do the same (shuitunlulu_ on Discord: Claude Science went back off magpie). So the keeper also puts magpie's daemon back, on the port the other was on, in place of one with another pid, one started for the gateway's old address, or its own older than the program installed (`--version`, asked again only when the file changed) (`scienceStale`), but only when `status` says no session runs in it (`active_frames` and `active_conversations` 0; a status without them is busy), never one launchd or systemd keeps (`launch_context`), and at most three times an hour (`scienceRetakes`). It reads `operon.lock` every 10 s and asks `status` when the lock's pid changed or a minute went by. A window on the daemon stopped shows the app's "stopped from the command line" screen, whose "start it again in the app" attaches it to magpie's. `Check` reads the daemon's `operon.lock`, not `status` (most of a second for a 130 MB Bun program), and calls a daemon with another pid drift until the keeper replaces it. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). | [`claudescience.go`](../../internal/agent/claudescience.go), [`science.go`](../../internal/gateway/science.go) |
|
||||
| Claude Code beside its own account | `claude-magpie` (baranwang on X) starts Claude Code through magpie while a plain `claude` stays on the user's own account, nothing switched back and forth. `magpie claude run [args…]` writes `<config>/claude-launch/settings.json` as `claude#launch`, an agent `claudeIn` makes at that folder (`place.dir`) and lists nowhere, so the Agents page, Check and Notice see only the user's settings.json: connected the first time as Connect would (`ConnectHow`), set again when the gateway's address or key moved (`claudeLaunchStale`, the LAN key included), synced after that, with `ANTHROPIC_API_KEY` and the cloud switches (`agentenv.ClaudeProviders`) blanked. It then runs `claude --settings <file> args…` as a child (not exec, so it can tidy after): Claude Code puts a --settings file's env and model over the user's settings.json, a claude.ai sign-in and the shell (tried on 2.1.318). `/model` saves to the user's settings.json, never the --settings file, so `ClaudeLaunchAfter` moves a magpie model picked there into the launch file and gives the user's file its model back while magpie isn't wired into it; it also undoes Claude Code's own one-time `opus` → `opus[1m]` rewrite (`migration_opus_to_opus1m`), which the launch file's 1M opus tier sets off. A Claude alias picked (`sonnet`) stays. On Unix a stopped child stops magpie too (^Z, fg), and its exit code is magpie's; on Windows magpie ignores Ctrl+C while claude runs. The command `claude-magpie` is a launcher beside the `magpie` command (`update.Launchers`): a `#!/bin/sh` `exec` of `Program()`, or on Windows a `.cmd` running `"%~dp0magpie"`. `AddCLI` writes it, and `magpie claude launcher add` puts it there for a command added before; a file by that name without `written by magpie` is never written over. StandIn falls back to the launch file's tiers. | [`claude_launch.go`](../../internal/agent/claude_launch.go), [`claude_launch_cli.go`](../../internal/cli/claude_launch_cli.go), [`claude_run_unix.go`](../../internal/cli/claude_run_unix.go), [`launcher.go`](../../internal/update/launcher.go) |
|
||||
|
||||
## Runtime path
|
||||
|
||||
+153
-11
@@ -16,9 +16,15 @@ package agent
|
||||
//
|
||||
// The daemon lives till it is stopped or the computer restarts, so while
|
||||
// it is connected magpie starts it again when it isn't running
|
||||
// (KeepClaudeScience), and says so when another one runs in its place —
|
||||
// the window, opened while none ran, starts its own without the variable
|
||||
// (Check).
|
||||
// (KeepClaudeScience). The app (0.1.72, Electron) attaches its window to
|
||||
// a daemon running; with none it starts its own (`serve --stdio
|
||||
// --adopt-install`) in its own environment, which has no such variable,
|
||||
// and its "let the app run it instead" (and the offer it makes when the
|
||||
// daemon is older than the app) stops magpie's to do the same. So the
|
||||
// keeper also puts magpie's daemon back in place of one it didn't start,
|
||||
// and of its own once the app updated past it, but only while no session
|
||||
// runs in it, and never one a service manager keeps (it would come back
|
||||
// at once); Check says so meanwhile.
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -29,6 +35,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -119,6 +126,24 @@ type scienceStatus struct {
|
||||
PID int `json:"pid"`
|
||||
Port int `json:"port"`
|
||||
Version string `json:"version"`
|
||||
Daemon struct {
|
||||
// nil when its status didn't say (an older build): unknown, so busy
|
||||
Frames *int `json:"active_frames"`
|
||||
Conversations *int `json:"active_conversations"`
|
||||
Context string `json:"launch_context"` // terminal, app-child, launchd, systemd
|
||||
} `json:"daemon"`
|
||||
}
|
||||
|
||||
// idle is whether no session runs in the daemon, as its status says.
|
||||
func (st scienceStatus) idle() bool {
|
||||
d := st.Daemon
|
||||
return d.Frames != nil && d.Conversations != nil && *d.Frames == 0 && *d.Conversations == 0
|
||||
}
|
||||
|
||||
// kept is whether a service manager (launchd, systemd) started the daemon
|
||||
// and would start it again, as it was, once stopped.
|
||||
func (st scienceStatus) kept() bool {
|
||||
return st.Daemon.Context == "launchd" || st.Daemon.Context == "systemd"
|
||||
}
|
||||
|
||||
// scienceDir is the daemon's data folder, ~/.claude-science. A var so
|
||||
@@ -305,7 +330,7 @@ func scienceCheck() string {
|
||||
return ""
|
||||
}
|
||||
if st.PID != m.PID {
|
||||
return fmt.Sprintf("%s's daemon (pid %d) was started without magpie's gateway", scienceName, st.PID)
|
||||
return fmt.Sprintf("%s's daemon (pid %d) was started without magpie's gateway (its window starts its own when none runs); magpie starts its own in its place once no session runs in it", scienceName, st.PID)
|
||||
}
|
||||
if m.URL != gateway.URL() {
|
||||
return fmt.Sprintf("%s's daemon was started for the gateway at %s", scienceName, m.URL)
|
||||
@@ -314,13 +339,15 @@ func scienceCheck() string {
|
||||
}
|
||||
|
||||
// KeepClaudeScience starts the daemon on the gateway, while Claude Science
|
||||
// is connected, whenever it isn't running: after a restart of the
|
||||
// computer, or after it was stopped. It never stops one running — one
|
||||
// magpie didn't start may be in the middle of a session — which Check
|
||||
// tells as drift instead.
|
||||
// is connected, whenever it isn't running (after a restart of the
|
||||
// computer, or after it was stopped), and in place of one running that
|
||||
// magpie didn't start or that is older than the program installed now
|
||||
// (scienceStale), once no session runs in it. It reads the lock file every
|
||||
// few seconds and asks status (most of a second of a 130 MB Bun program)
|
||||
// when the lock's pid changed or a minute went by.
|
||||
func KeepClaudeScience(ctx context.Context) {
|
||||
keepScienceOnce()
|
||||
tick := time.NewTicker(time.Minute)
|
||||
tick := time.NewTicker(scienceTick)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
@@ -332,6 +359,92 @@ func KeepClaudeScience(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// scienceTick is how often the keeper reads the lock file.
|
||||
const scienceTick = 10 * time.Second
|
||||
|
||||
// scienceKeep is what the keeper saw: the lock's pid when it last asked
|
||||
// status, and when; the program's version by its size and time; the
|
||||
// times it put its daemon in place of another.
|
||||
var scienceKeep struct {
|
||||
asked time.Time
|
||||
lockPID int
|
||||
bin string
|
||||
binSize int64
|
||||
binTime time.Time
|
||||
version string
|
||||
retook []time.Time
|
||||
}
|
||||
|
||||
// scienceRetakes is how many times in an hour the keeper puts its daemon
|
||||
// in place of another before it leaves the other running: one the user
|
||||
// keeps putting back is theirs.
|
||||
const scienceRetakes = 3
|
||||
|
||||
// scienceVersion is the version of the program at bin, "" unknown, asked
|
||||
// again only when the file changed (the app updated).
|
||||
func scienceVersion(bin string) string {
|
||||
fi, err := os.Stat(bin)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
k := &scienceKeep
|
||||
if k.bin == bin && k.binSize == fi.Size() && k.binTime.Equal(fi.ModTime()) {
|
||||
return k.version
|
||||
}
|
||||
out, err := scienceRun(nil, bin, "--version")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
// "claude-science 0.1.72 (release, public)"
|
||||
v := ""
|
||||
if f := strings.Fields(string(out)); len(f) > 1 {
|
||||
v = f[1]
|
||||
}
|
||||
k.bin, k.binSize, k.binTime, k.version = bin, fi.Size(), fi.ModTime(), v
|
||||
return v
|
||||
}
|
||||
|
||||
// olderVersion is whether dotted version a is older than b; false when
|
||||
// either doesn't read as one.
|
||||
func olderVersion(a, b string) bool {
|
||||
as, bs := strings.Split(a, "."), strings.Split(b, ".")
|
||||
for i := 0; i < len(as) || i < len(bs); i++ {
|
||||
var x, y int
|
||||
var err error
|
||||
if i < len(as) {
|
||||
if x, err = strconv.Atoi(as[i]); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if i < len(bs) {
|
||||
if y, err = strconv.Atoi(bs[i]); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if x != y {
|
||||
return x < y
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// scienceStale is why the daemon running isn't the one magpie keeps: one
|
||||
// it didn't start, one started for the gateway's old address, or its own
|
||||
// older than the program installed (the app updated, and would offer to
|
||||
// run its own instead); "" when it is.
|
||||
func scienceStale(bin string, st scienceStatus, m scienceMark, gw string) string {
|
||||
switch {
|
||||
case st.PID != m.PID:
|
||||
return fmt.Sprintf("pid %d isn't the one magpie started", st.PID)
|
||||
case m.URL != gw:
|
||||
return "it was started for the gateway at " + m.URL
|
||||
}
|
||||
if v := scienceVersion(bin); v != "" && olderVersion(st.Version, v) {
|
||||
return fmt.Sprintf("it runs %s and %s is installed", st.Version, v)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func keepScienceOnce() {
|
||||
if !scienceWired() {
|
||||
return
|
||||
@@ -342,16 +455,45 @@ func keepScienceOnce() {
|
||||
if bin == "" {
|
||||
return
|
||||
}
|
||||
if st, err := scienceState(bin); err != nil || st.Running {
|
||||
k := &scienceKeep
|
||||
lock, _ := scienceLock()
|
||||
if lock.PID == k.lockPID && time.Since(k.asked) < time.Minute {
|
||||
return
|
||||
}
|
||||
st, err := scienceState(bin)
|
||||
k.asked, k.lockPID = time.Now(), lock.PID
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
gw := gateway.URL()
|
||||
m, _ := readScienceMark()
|
||||
st, err := scienceServe(bin, gw, m.Port)
|
||||
port := m.Port
|
||||
if st.Running {
|
||||
why := scienceStale(bin, st, m, gw)
|
||||
// a session running in it would be cut off; a service would start
|
||||
// it again without the variable
|
||||
if why == "" || !st.idle() || st.kept() {
|
||||
return
|
||||
}
|
||||
cut := time.Now().Add(-time.Hour)
|
||||
k.retook = slices.DeleteFunc(k.retook, func(t time.Time) bool { return t.Before(cut) })
|
||||
if len(k.retook) >= scienceRetakes {
|
||||
return
|
||||
}
|
||||
k.retook = append(k.retook, time.Now())
|
||||
log.Printf("%s: starting its daemon on magpie's gateway again: %s", scienceName, why)
|
||||
if out, err := scienceRun(nil, bin, "stop"); err != nil {
|
||||
log.Printf("%s: claude-science stop: %v %s", scienceName, err, strings.TrimSpace(string(out)))
|
||||
return
|
||||
}
|
||||
port = st.Port
|
||||
}
|
||||
st, err = scienceServe(bin, gw, port)
|
||||
if err != nil {
|
||||
log.Printf("%s: starting its daemon on magpie's gateway: %v", scienceName, err)
|
||||
return
|
||||
}
|
||||
k.lockPID = st.PID
|
||||
if err := writeScienceMark(scienceMark{URL: gw, PID: st.PID, Port: st.Port}); err != nil {
|
||||
log.Printf("%s: %v", scienceName, err)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,10 @@ type fakeScience struct {
|
||||
pid, port int
|
||||
env []string // the environment the daemon running was started in
|
||||
calls []string
|
||||
// what its status says of the daemon running (nil: no daemon object,
|
||||
// as an older build), and the version of the program installed
|
||||
daemon map[string]any
|
||||
version, installed string
|
||||
}
|
||||
|
||||
func (f *fakeScience) run(env []string, _ string, args ...string) ([]byte, error) {
|
||||
@@ -30,11 +34,18 @@ func (f *fakeScience) run(env []string, _ string, args ...string) ([]byte, error
|
||||
if !f.running {
|
||||
return []byte(`{"running":false}`), nil
|
||||
}
|
||||
return json.Marshal(map[string]any{"running": true, "pid": f.pid, "port": f.port, "version": "0.1.62", "data_dir": "/x"})
|
||||
v := f.version
|
||||
if v == "" {
|
||||
v = "0.1.62"
|
||||
}
|
||||
return json.Marshal(map[string]any{"running": true, "pid": f.pid, "port": f.port, "version": v, "data_dir": "/x", "daemon": f.daemon})
|
||||
case "--version":
|
||||
return []byte("claude-science " + f.installed + " (release, public)\n"), nil
|
||||
case "stop":
|
||||
f.running, f.env = false, nil
|
||||
case "serve":
|
||||
f.running, f.pid, f.env, f.port = true, f.pid+1, env, 8000
|
||||
f.version, f.daemon = f.installed, map[string]any{"active_frames": 0, "active_conversations": 0, "launch_context": "terminal"}
|
||||
if i := slices.Index(args, "--port"); i > 0 {
|
||||
f.port = 0
|
||||
json.Unmarshal([]byte(args[i+1]), &f.port)
|
||||
@@ -68,8 +79,8 @@ func (f *fakeScience) base() (string, bool) {
|
||||
// ANTHROPIC_BASE_URL set to the gateway, on the port it was on, and by
|
||||
// nothing else; disconnected by restarting it without the variable, one
|
||||
// set in magpie's own environment too. A daemon magpie didn't start is
|
||||
// drift, never stopped behind the user's back; one not running is started
|
||||
// while it is connected.
|
||||
// drift, never stopped while a session runs in it; one not running is
|
||||
// started while it is connected.
|
||||
func TestClaudeScienceRestartsItsDaemon(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv(scienceVar, "https://elsewhere.example")
|
||||
@@ -79,6 +90,7 @@ func TestClaudeScienceRestartsItsDaemon(t *testing.T) {
|
||||
t.Cleanup(func() { scienceRun, scienceBin, scienceWait, scienceDir = oldRun, oldBin, oldWait, oldDir })
|
||||
scienceRun, scienceBin, scienceWait = f.run, func() string { return "/bin/claude-science" }, time.Second
|
||||
scienceDir = func() string { return f.dir }
|
||||
resetScienceKeep(t)
|
||||
a, err := Find(ScienceID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -109,9 +121,10 @@ func TestClaudeScienceRestartsItsDaemon(t *testing.T) {
|
||||
t.Errorf("launch %q", a.Launch())
|
||||
}
|
||||
|
||||
// the window, opened while none ran, started its own: drift, and the
|
||||
// keeper leaves it running
|
||||
// the window, opened while none ran, started its own, and a session
|
||||
// runs in it: drift, and the keeper leaves it running
|
||||
f.pid, f.env, f.calls = 77, nil, nil
|
||||
f.daemon = map[string]any{"active_frames": 1, "active_conversations": 1, "launch_context": "app-child"}
|
||||
f.lock()
|
||||
if d := a.Check(); !strings.Contains(d, "without magpie's gateway") {
|
||||
t.Errorf("a daemon magpie didn't start: check %q", d)
|
||||
@@ -192,3 +205,134 @@ func TestFindClaudeScience(t *testing.T) {
|
||||
t.Errorf("found %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func resetScienceKeep(t *testing.T) {
|
||||
scienceKeep.asked, scienceKeep.lockPID, scienceKeep.bin, scienceKeep.retook = time.Time{}, 0, "", nil
|
||||
t.Cleanup(func() {
|
||||
scienceKeep.asked, scienceKeep.lockPID, scienceKeep.bin, scienceKeep.retook = time.Time{}, 0, "", nil
|
||||
})
|
||||
}
|
||||
|
||||
// shuitunlulu_ on Discord: Claude Science went back off magpie after it
|
||||
// was connected. Its app (0.1.72) attaches its window to a daemon running,
|
||||
// and with none starts its own (launch_context app-child) without
|
||||
// ANTHROPIC_BASE_URL; its "let the app run it instead", and its offer once
|
||||
// the app updated past the daemon, do the same. The keeper puts magpie's
|
||||
// daemon back, on the port the other was on, once no session runs in it:
|
||||
// never a busy one, one whose status doesn't say, or one a service
|
||||
// manager would start again; and stops after a few in an hour.
|
||||
func TestClaudeScienceTakesBackFromItsApp(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
bin := filepath.Join(t.TempDir(), "claude-science")
|
||||
os.WriteFile(bin, []byte("0.1.72"), 0o755)
|
||||
f := &fakeScience{dir: t.TempDir(), running: true, pid: 40, port: 8123, installed: "0.1.72"}
|
||||
f.lock()
|
||||
oldRun, oldBin, oldWait, oldDir := scienceRun, scienceBin, scienceWait, scienceDir
|
||||
t.Cleanup(func() { scienceRun, scienceBin, scienceWait, scienceDir = oldRun, oldBin, oldWait, oldDir })
|
||||
scienceRun, scienceBin, scienceWait = f.run, func() string { return bin }, time.Second
|
||||
scienceDir = func() string { return f.dir }
|
||||
resetScienceKeep(t)
|
||||
if err := scienceOn(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ours := f.pid
|
||||
keep := func() {
|
||||
t.Helper()
|
||||
f.calls = nil
|
||||
scienceKeep.asked = time.Time{} // a minute went by
|
||||
keepScienceOnce()
|
||||
}
|
||||
keep()
|
||||
if f.pid != ours || slices.Contains(f.calls, "stop") {
|
||||
t.Fatalf("its own daemon, on the gateway and current, was restarted: %q", f.calls)
|
||||
}
|
||||
|
||||
// the app's window, opened while none ran, started its own
|
||||
app := func(daemon map[string]any) {
|
||||
f.pid, f.port, f.env, f.daemon = 900, 18481, nil, daemon
|
||||
f.lock()
|
||||
}
|
||||
busy := map[string]any{"active_frames": 1, "active_conversations": 1, "launch_context": "app-child"}
|
||||
app(busy)
|
||||
keep()
|
||||
if f.pid != 900 || slices.Contains(f.calls, "stop") {
|
||||
t.Errorf("a daemon a session runs in was stopped: %q", f.calls)
|
||||
}
|
||||
app(nil) // a status that doesn't say: unknown, left
|
||||
keep()
|
||||
if f.pid != 900 || slices.Contains(f.calls, "stop") {
|
||||
t.Errorf("a daemon whose status says nothing of its sessions was stopped: %q", f.calls)
|
||||
}
|
||||
app(map[string]any{"active_frames": 0, "active_conversations": 0, "launch_context": "launchd"})
|
||||
keep()
|
||||
if f.pid != 900 || slices.Contains(f.calls, "stop") {
|
||||
t.Errorf("a daemon launchd keeps was stopped: %q", f.calls)
|
||||
}
|
||||
idle := map[string]any{"active_frames": 0, "active_conversations": 0, "launch_context": "app-child"}
|
||||
app(idle)
|
||||
if d := scienceCheck(); !strings.Contains(d, "without magpie's gateway") {
|
||||
t.Errorf("check %q", d)
|
||||
}
|
||||
// the lock's pid changed: asked at once, not a minute later
|
||||
scienceKeep.asked = time.Now()
|
||||
scienceKeep.lockPID = ours
|
||||
f.calls = nil
|
||||
keepScienceOnce()
|
||||
if got, _ := f.base(); f.pid == 900 || got != gateway.URL() || f.port != 18481 {
|
||||
t.Errorf("not put back on the gateway on its port: %q, pid %d, base %q, port %d", f.calls, f.pid, got, f.port)
|
||||
}
|
||||
if m, _ := readScienceMark(); m.PID != f.pid || scienceCheck() != "" {
|
||||
t.Errorf("mark %+v, check %q", m, scienceCheck())
|
||||
}
|
||||
// and the lock unchanged within the minute: status isn't asked
|
||||
f.calls = nil
|
||||
keepScienceOnce()
|
||||
if len(f.calls) != 0 {
|
||||
t.Errorf("asked again with the lock unchanged: %q", f.calls)
|
||||
}
|
||||
|
||||
// the app updated: its program is newer than magpie's daemon
|
||||
f.installed = "0.1.73"
|
||||
os.WriteFile(bin, []byte("0.1.73 build"), 0o755)
|
||||
before := f.pid
|
||||
keep()
|
||||
if f.pid == before || f.version != "0.1.73" {
|
||||
t.Errorf("an older daemon of magpie's was left after the app updated: %q", f.calls)
|
||||
}
|
||||
keep()
|
||||
if slices.Contains(f.calls, "--version") {
|
||||
t.Errorf("the version asked again with the program unchanged: %q", f.calls)
|
||||
}
|
||||
|
||||
// put back three times in the hour (the app twice and the update):
|
||||
// one the user keeps putting back is theirs
|
||||
app(idle)
|
||||
keep()
|
||||
if f.pid == 900 {
|
||||
t.Fatalf("not put back a second time")
|
||||
}
|
||||
app(idle)
|
||||
keep()
|
||||
if f.pid != 900 || slices.Contains(f.calls, "stop") {
|
||||
t.Errorf("put back past %d in an hour: %q", scienceRetakes, f.calls)
|
||||
}
|
||||
|
||||
// disconnected: the app's own is left
|
||||
scienceKeep.retook = nil
|
||||
os.Remove(scienceMarkPath())
|
||||
keep()
|
||||
if f.pid != 900 || len(f.calls) != 0 {
|
||||
t.Errorf("touched while disconnected: %q", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOlderVersion(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
a, b string
|
||||
want bool
|
||||
}{{"0.1.72", "0.1.73", true}, {"0.1.9", "0.1.72", true}, {"0.1.72", "0.1.72", false}, {"0.2.0", "0.1.99", false}, {"", "0.1.72", false}, {"0.1.72", "", false}, {"x", "0.1.72", false}, {"0.1", "0.1.1", true}} {
|
||||
if got := olderVersion(c.a, c.b); got != c.want {
|
||||
t.Errorf("olderVersion(%q, %q) = %v", c.a, c.b, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user