[bug] Drift 误报:magpie 自己起的 Claude Code(订阅桥接 / 额度预热)写入 `~/.claude/history.jsonl`,被当成用户使用,反复提示 bypassed
环境
- magpie 0.1.2861(
magpie gui agents) - Claude Code 2.1.314(
/usr/bin/claude→/opt/claude-code/bin/claude) - Linux(Arch,kernel 7.2.11)
- Claude Code 的
~/.claude/settings.json已指向网关(ANTHROPIC_BASE_URL=http://127.0.0.1:3425) - 同时使用 Claude Desktop 接入 magpie,模型走 Claude 订阅(
provider: claude),有 3 个已保存的 Claude 账号并开启了额度预热
现象
Agents 页的 Claude Code 每天会多次出现:
Claude Code 最近绕过了 magpie,重新应用后请重启 Claude Code was used at 21:50 but none of its requests reached magpie — one started before magpie set it up still runs on its old config: restart it
但出现提示的时候,本机并没有用户自己启动的 Claude Code 在运行。点「重新接入」也没用,过一会儿又会出现。
原因
和 #3224 是同一个检测入口:Claude Code 的 LastUsed 取的是 ~/.claude/history.jsonl 里最新一条非斜杠命令的时间。但这次推进 LastUsed 的记录不是用户写的,而是 magpie 自己起的 claude 进程 写的。这些进程用的是默认配置目录 ~/.claude,它们发的消息会跟用户的输入一起写进同一个 history.jsonl,而且请求本来就直接发给 Anthropic,不经过网关。网关这边 agent: "claude" 的 lastSeen 不会更新,于是被判成 bypassed。
我遇到了两种触发:
1. 额度预热(21:50 那次)
history.jsonl:
{"display":"hi","timestamp":1793713835656,"project":"/tmp/magpie-claude-work-1000","sessionId":"f11ebda6-35a6-4842-a230-cbbfda5c07b2"}
对应 app.log:
2026/11/03 21:50:37 claude warm-up: <account>'s 5 hours window: Claude Code: You've hit your weekly limit · resets 12am (Asia/Shanghai)
这次预热因为周额度用完失败了,但 hi 已经写进了 history.jsonl。从当天的记录看,每次预热都会留下一条 /tmp/magpie-claude-work-1000 下的 hi(09:29、09:45、12:52、14:30、14:46、21:50 等)。
2. 订阅桥接(15:35 那次)
Claude Desktop 的会话由 magpie 起的桥接进程代跑:magpie claude-tui-helper /usr/bin/claude -p … --resume 225a7e0a-…,cwd 是用户的项目目录,进程环境里没有 CLAUDE_CONFIG_DIR。Desktop 用户发的消息会以用户项目作为 project 写进 history.jsonl:
{"display":"[Image #6][Pasted text #7 +3 lines]","timestamp":1793691330048,"project":"/home/saki/Documents/workspace/bdr","sessionId":"225a7e0a-ae66-49f6-976b-c3d5d32f40e5"}
同一时刻网关的 routing 日志记录的是 agent: "claude-desktop",不是 claude:
2026-11-03T15:35:30 agent=claude-desktop model=auto/claude-opus-5-5 provider=claude status=200
注意:这种情况下 project 是用户的真实目录,所以只按 /tmp/magpie-claude-* 过滤并不够。
网关这边的对照
当天 routing 日志里 agent: "claude" 只有两条,都是我手动在终端里跑 claude 测试的,而且都正常经过了网关:
2026-11-03T15:02:30 kiro/claude-opus-5.5 kiro 200
2026-11-03T21:53:03 kiro/claude-opus-5.5 kiro 200
所以 15:02 之后、21:53 之前的两次提示,LastUsed 都是被 magpie 自己的进程推进的。
观察到的一个不一致
同样是 claude-tui-helper 起的进程,15:48 起的那一个环境里带 CLAUDE_CONFIG_DIR=~/.config/magpie/claude-accounts/<id>,它的消息没有写进 ~/.claude/history.jsonl。13:52 / 13:57 起的两个(--resume 旧会话)以及预热进程用的则是默认 ~/.claude。看起来是否隔离取决于走的是哪个账号或哪条路径。
可能的修法(供参考)
- magpie 起的所有
claude进程(桥接、预热、/usage读取)都用独立的CLAUDE_CONFIG_DIR,不要写用户的~/.claude。这样也能顺带解决 #3983 里桥接会话混进用户会话列表的问题。 - 或者
LastUsed跳过 magpie 自己产生的记录:magpie 知道自己起过哪些sessionId(桥接的--resume/--session-id、预热的会话),可以按sessionId排除;只按project前缀判断,盖不住第 2 种情况。 - 至少预热失败(额度已满)时,不应该让这次调用被当成用户使用。
相关:#3224(exit 记录导致的同类误报)、#3983(桥接会话出现在用户会话列表里)。
take
AI-written; please keep the author (ggbdpq) or add Co-authored-by: ggbdpq <[email protected]>
What's wrong
Claude Code keeps showing "was used at … but none of its requests reached magpie" (Drift, kind bypassed) even though the user ran nothing themselves, and "Reconnect" doesn't stick — the notice comes back after a while.
Root cause
As @MEIZU16's analysis in this issue established (and #3224 mapped the same detection entry): Claude Code's LastUsed is the newest non-slash-command line of ~/.claude/history.jsonl, while the gateway's lastSeen for agent claude only moves on requests that reach magpie. But the lines that keep moving LastUsed here are written by Claude Code processes magpie itself started:
- a subscription warm-up ("hi" at Haiku) appends to the user's
history.jsonlwhatever its work folder is, and its request goes straight to Anthropic, never through the gateway; - the Claude Desktop bridge's helper runs in the user's own config directory whenever it resumes one of their sessions (
--resume, noCLAUDE_CONFIG_DIR), so the Desktop user's messages land in the samehistory.jsonlwith the user's real project asproject— while the gateway only ever sees agentclaude-desktopon those turns.
So LastUsed advances with no gateway traffic to answer it, and bypassed() fires. Filtering by the magpie-claude-work project prefix can't cover the bridge case (the reporter's second trace has a real user project). Thank you @MEIZU16 for the complete root-cause work and the sessionId suggestion this patch follows.
The fix
Every one of those runs has a session id magpie knows: the bridge reads it off the run's init message (helper or direct claude -p alike, resumed or new), a -p warm-up now tells claude its session up front (--session-id, the same flag the helper already passes for interactive runs), and a one-off interactive run's helper announces its own. The gateway keeps those ids (usage.OwnSession), and Claude Code's LastUsed passes history.jsonl lines that name one of them over (sessionId). The user's own lines count exactly as before; a real bypass still flags.
Patch (0001-agent-a-Claude-Code-run-magpie-started-itself-is-not-use.patch)
From 0db2a61f92a72348c875db34068e9d926742da27 Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Wed, 4 Nov 2026 00:22:40 +0800
Subject: [PATCH] agent: a Claude Code run magpie started itself is not use
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The bridge's sessions and a warm-up's run write the user's history.jsonl
as they go (the bridge's helper runs in the user's own config when it
resumes a session of theirs, a warm-up's "hi" lands there whatever its
work folder), and none of their requests reach the gateway as agent
claude's: the bridge's go as claude-desktop's, a warm-up's straight to
Anthropic. Drift took the newest such line for the user using Claude
Code behind magpie's back, and said bypassed until a newer line came or
the agent was set again — "Reconnect" fixed nothing, as the next warm-up
or bridge turn moved LastUsed again (#5100).
Every such run's session is one magpie knows: the bridge reads it off
the run's init, a warm-up's is told to claude up front (--session-id),
a one-off's helper says its own. The gateway keeps those ids
(usage.OwnSession), and Claude Code's LastUsed passes history.jsonl
lines that name one over. The user's own lines count as before.
Tests: TestClaudeDriftOwnSessions (a warm-up's line, the bridge's on the
user's own project, the user's own, and a run of magpie's above the
user's still says used at the user's time),
TestWarmClaudeSaysItsOwnSession, TestClaudeHelperSessionIsMagpiesOwn,
TestClaudeBridgeSessionIsMagpiesOwn.
Generated-by: GLM-5.3-Flash (ZCode)
---
internal/agent/applied.go | 17 ++++-
internal/agent/claude.go | 13 +++-
internal/agent/claude_own_sessions_test.go | 87 ++++++++++++++++++++++
internal/gateway/claude_resume_test.go | 19 +++++
internal/gateway/claude_subscription.go | 3 +
internal/gateway/claude_warmup.go | 17 ++++-
internal/gateway/claude_warmup_test.go | 39 ++++++++++
internal/usage/usage.go | 35 +++++++++
8 files changed, 224 insertions(+), 6 deletions(-)
create mode 100644 internal/agent/claude_own_sessions_test.go
diff --git a/internal/agent/applied.go b/internal/agent/applied.go
index 0b8fad061..b8e7ec676 100644
--- a/internal/agent/applied.go
+++ b/internal/agent/applied.go
@@ -995,9 +995,10 @@ func (a *Agent) reconnect(now map[string]string) (bool, error) {
// lastJSONLTime reads the newest Unix timestamp (seconds or milliseconds)
// under key in the last lines of a prompt log, passing over the lines whose
-// text (under textKey) is a slash command: those an agent answers itself.
-// Zero if there is none.
-func lastJSONLTime(path, key, textKey string) time.Time {
+// text (under textKey) is a slash command: those an agent answers itself —
+// and any a skip says to leave out: the lines of runs magpie started itself
+// are not the user's (#5100). Zero if there is none.
+func lastJSONLTime(path, key, textKey string, skip ...func(map[string]json.RawMessage) bool) time.Time {
f, err := os.Open(path)
if err != nil {
return time.Time{}
@@ -1019,6 +1020,16 @@ func lastJSONLTime(path, key, textKey string) time.Time {
if json.Unmarshal(m[textKey], &text) == nil && strings.HasPrefix(strings.TrimSpace(text), "/") {
continue
}
+ out := false
+ for _, s := range skip {
+ if s(m) {
+ out = true
+ break
+ }
+ }
+ if out {
+ continue
+ }
n, err := strconv.ParseInt(string(m[key]), 10, 64)
if err != nil {
continue
diff --git a/internal/agent/claude.go b/internal/agent/claude.go
index 8a664b7de..ecd60edba 100644
--- a/internal/agent/claude.go
+++ b/internal/agent/claude.go
@@ -21,6 +21,7 @@ import (
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
+ "github.com/yetone/magpie/internal/usage"
)
// Claude Code reads its endpoint from the `env` block of settings.json.
@@ -2424,9 +2425,17 @@ func claudeIn(at place) *Agent {
}
return wiringOff("Claude Code", path, getEnv, "ANTHROPIC_AUTH_TOKEN", at.gwKey())
},
- // every prompt typed into Claude Code goes into history.jsonl
+ // every prompt typed into Claude Code goes into history.jsonl —
+ // the user's, and those of the runs magpie started itself (the
+ // subscription bridge's, a warm-up's) as well: the latter are not
+ // use, and none of their requests reach the gateway as this
+ // agent's (#5100)
LastUsed: func() time.Time {
- return lastJSONLTime(filepath.Join(filepath.Dir(path), "history.jsonl"), "timestamp", "display")
+ return lastJSONLTime(filepath.Join(filepath.Dir(path), "history.jsonl"), "timestamp", "display",
+ func(m map[string]json.RawMessage) bool {
+ var sid string
+ return json.Unmarshal(m["sessionId"], &sid) == nil && usage.IsOwnSession(sid)
+ })
},
// a session takes a new CLAUDE_CODE_EFFORT_LEVEL on its next
// request, but settings.json's effort and ultracode, and the env's
diff --git a/internal/agent/claude_own_sessions_test.go b/internal/agent/claude_own_sessions_test.go
new file mode 100644
index 000000000..16ae38f4b
--- /dev/null
+++ b/internal/agent/claude_own_sessions_test.go
@@ -0,0 +1,87 @@
+package agent
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/usage"
+)
+
+// The Claude Code runs magpie started itself — the subscription bridge's,
+// a warm-up's — write the user's history.jsonl as they go, and none of
+// their requests reach the gateway as agent claude's (the bridge's go as
+// claude-desktop's, a warm-up's straight to Anthropic): drift would take
+// them for the user using Claude Code behind magpie's back (#5100). A
+// session magpie started is not use; one the user started is.
+func TestClaudeDriftOwnSessions(t *testing.T) {
+ home, _ := codexHome(t, "", "")
+ t.Setenv("CLAUDE_CONFIG_DIR", "")
+ managed := claudeManaged
+ claudeManaged = func() string { return filepath.Join(home, "managed-settings.json") }
+ t.Cleanup(func() { claudeManaged = managed })
+ cl := claude(home)
+ defer func(s time.Time) { started = s }(started)
+ started = time.Now().Add(-time.Hour)
+ // a request reaching the gateway, kept to this run: usage.Saw's record
+ // lasts the process, so the next run (-count=2) would start with it
+ var saw time.Time
+ defer func(f func(string) time.Time) { lastSeen = f }(lastSeen)
+ lastSeen = func(string) time.Time { return saw }
+ if err := cl.Apply("model", "fake/m1"); err != nil {
+ t.Fatal(err)
+ }
+ // Apply stamped now; put it back to before the prompts
+ m := appliedLoad()
+ a := m["claude"]
+ a.At = time.Now().Add(-10 * time.Minute)
+ m["claude"] = a
+ appliedSave(m)
+ hist := filepath.Join(home, ".claude", "history.jsonl")
+ line := func(entries ...map[string]any) {
+ var b []byte
+ for _, e := range entries {
+ j, _ := json.Marshal(e)
+ b = append(b, j...)
+ b = append(b, '
')
+ }
+ if err := os.WriteFile(hist, b, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ prompt := func(sid, display, project string, at time.Time) map[string]any {
+ return map[string]any{"display": display, "timestamp": at.UnixMilli(), "project": project, "sessionId": sid}
+ }
+ work := filepath.Join(os.TempDir(), "magpie-claude-work-1000")
+ proj := filepath.Join(home, "work", "bdr")
+ // a warm-up's "hi", the log's newest line: its run asked Anthropic
+ // straight, so the gateway saw nothing — not the user's use
+ usage.OwnSession("warmup-sid")
+ line(prompt("warmup-sid", "hi", work, time.Now().Add(-time.Minute)))
+ if d := cl.Drift(); d != nil {
+ t.Fatalf("magpie's own warm-up: %+v", d)
+ }
+ // the bridge's session, on the user's own project — no magpie folder in
+ // its path to go by: the session magpie started is what says it isn't use
+ usage.OwnSession("bridge-sid")
+ line(prompt("bridge-sid", "[Image #6][Pasted text #7 +3 lines]", proj, time.Now().Add(-time.Minute)))
+ if d := cl.Drift(); d != nil {
+ t.Fatalf("magpie's own bridge session: %+v", d)
+ }
+ // the user's own use, none of it at the gateway: bypassed
+ used := time.Now().Add(-5 * time.Minute)
+ line(prompt("user-sid", "hi", proj, used))
+ if d := cl.Drift(); d == nil || d.Kind != "bypassed" {
+ t.Fatalf("the user's use: %+v", d)
+ }
+ // a run of magpie's own above the user's line: the use said is still
+ // the user's, at the user's time
+ usage.OwnSession("later-sid")
+ line(prompt("user-sid", "hi", proj, used), prompt("later-sid", "hi", work, time.Now().Add(-time.Minute)))
+ if d := cl.Drift(); d == nil || d.Kind != "bypassed" || !strings.Contains(d.Detail, "used at "+used.Format("15:04")) {
+ t.Fatalf("a run of magpie's own above the user's: %+v", d)
+ }
+}
diff --git a/internal/gateway/claude_resume_test.go b/internal/gateway/claude_resume_test.go
index eca54f557..f89ec300b 100644
--- a/internal/gateway/claude_resume_test.go
+++ b/internal/gateway/claude_resume_test.go
@@ -13,6 +13,7 @@ import (
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
+ "github.com/yetone/magpie/internal/usage"
)
// resumeHarness runs Claude subscription requests through a script
@@ -359,6 +360,24 @@ func containsStr(list []string, s string) bool {
return false
}
+// A conversation's run is magpie's own: the session its init names is kept,
+// so the lines it writes to the user's history.jsonl are never taken for
+// the user's use (#5100).
+func TestClaudeBridgeSessionIsMagpiesOwn(t *testing.T) {
+ h := newResumeHarness(t)
+ h.ask("rules A", "a1")
+ var sid string
+ for pid := range h.runs() {
+ sid = "s" + pid
+ }
+ if sid == "" {
+ t.Fatal("no run")
+ }
+ if !usage.IsOwnSession(sid) {
+ t.Fatalf("the bridge run's session %s is not kept as magpie's own", sid)
+ }
+}
+
// A client Claude Code's billing line changes every turn (cch,
// cc_prompt_id, cc_prev_req…), and a run is never told it. Its next turn
// still goes on in the run that had the conversation, told the new message
diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go
index c2cd7dfc4..684970f22 100644
--- a/internal/gateway/claude_subscription.go
+++ b/internal/gateway/claude_subscription.go
@@ -3817,6 +3817,9 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
return
}
if envelope.Type == "system" && envelope.Subtype == "init" && envelope.SessionID != "" {
+ // the session is the bridge's own: the lines its run writes to
+ // the user's history.jsonl are not the user's use (#5100)
+ ownClaudeSession(envelope.SessionID)
r.mu.Lock()
r.sessionID = envelope.SessionID
r.mu.Unlock()
diff --git a/internal/gateway/claude_warmup.go b/internal/gateway/claude_warmup.go
index 2621e368b..35e6e1d0c 100644
--- a/internal/gateway/claude_warmup.go
+++ b/internal/gateway/claude_warmup.go
@@ -24,6 +24,7 @@ import (
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/redact"
+ "github.com/yetone/magpie/internal/usage"
"golang.org/x/text/unicode/norm"
)
@@ -62,7 +63,12 @@ func askClaude(ctx context.Context, configDir, model string) error {
return err
}
defer os.RemoveAll(tmp)
- cmd := binary.command(ctx, claudeWarmArgs(model)...)
+ // the run's session is magpie's own, told before it starts: its "hi"
+ // lands in the user's history.jsonl, and drift must not take it for the
+ // user's use (#5100)
+ sid := newUUID()
+ usage.OwnSession(sid)
+ cmd := binary.command(ctx, append(claudeWarmArgs(model), "--session-id", sid)...)
cmd.Dir = tmp
cmd.Stdin = strings.NewReader("hi")
env, err := binary.proxied(ctx, cleanClaudeEnv(os.Environ()))
@@ -164,6 +170,9 @@ func (w *resultLines) Write(p []byte) (int, error) {
if json.Unmarshal(w.buf[:i], &r) == nil {
if r.SessionID != "" {
w.sid = r.SessionID
+ // the session is magpie's own: the lines its run writes to
+ // the user's history.jsonl are not the user's use (#5100)
+ usage.OwnSession(r.SessionID)
}
if r.Type == "result" {
w.res = &r
@@ -552,3 +561,9 @@ func claudeBypassEnv(tui bool, configDir string) []string {
}
return []string{claudetui.BypassEnv + "=1"}
}
+
+// ownClaudeSession keeps the session id of a Claude Code run magpie started
+// itself (the bridge's, a warm-up's): its lines in the user's history.jsonl
+// are not the user's use (#5100). A wrapper, as the bridge's read of its
+// runs' stream-json has a usage of its own in scope.
+func ownClaudeSession(sid string) { usage.OwnSession(sid) }
diff --git a/internal/gateway/claude_warmup_test.go b/internal/gateway/claude_warmup_test.go
index 655c76499..0217ab685 100644
--- a/internal/gateway/claude_warmup_test.go
+++ b/internal/gateway/claude_warmup_test.go
@@ -14,6 +14,7 @@ import (
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
+ "github.com/yetone/magpie/internal/usage"
)
// fakeWarmClaude is a claude that writes what it was run with to log and
@@ -70,6 +71,44 @@ func TestWarmClaudeAsksClaudeCodeOnce(t *testing.T) {
}
}
+// A warm-up's session is magpie's own, told before the run starts and kept:
+// its "hi" lands in the user's history.jsonl, and drift must not take it
+// for the user's use (#5100).
+func TestWarmClaudeSaysItsOwnSession(t *testing.T) {
+ log := fakeWarmClaude(t, `{"type":"result","is_error":false,"result":"Hi!"}`, 0)
+ if err := warmClaude(context.Background(), ""); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := os.ReadFile(log)
+ got := string(b)
+ i := strings.Index(got, "[--session-id][")
+ if i < 0 {
+ t.Fatalf("no session of its own told: %s", got)
+ }
+ sid := got[i+len("[--session-id]["):]
+ if j := strings.Index(sid, "]"); j >= 0 {
+ sid = sid[:j]
+ }
+ if !usage.IsOwnSession(sid) {
+ t.Errorf("the run's session %s is not kept as magpie's own", sid)
+ }
+}
+
+// The helper's init tells which session a one-off interactive run (a
+// warm-up, a /usage read) is: that session is magpie's own (#5100).
+func TestClaudeHelperSessionIsMagpiesOwn(t *testing.T) {
+ out := &resultLines{done: func() {}}
+ if _, err := out.Write([]byte(`{"type":"system","subtype":"init","session_id":"helper-sid"}` + "
")); err != nil {
+ t.Fatal(err)
+ }
+ if out.sid != "helper-sid" {
+ t.Fatalf("sid %q", out.sid)
+ }
+ if !usage.IsOwnSession("helper-sid") {
+ t.Errorf("the helper's session is not kept as magpie's own")
+ }
+}
+
func TestWarmClaudeSaysWhyNot(t *testing.T) {
fakeWarmClaude(t, `{"type":"result","is_error":true,"result":"Invalid API key · Please run /login"}`, 1)
err := warmClaude(context.Background(), "")
diff --git a/internal/usage/usage.go b/internal/usage/usage.go
index 71daf4f73..0f1cbcb8c 100644
--- a/internal/usage/usage.go
+++ b/internal/usage/usage.go
@@ -1153,3 +1153,38 @@ func LastSeen(agent string) time.Time {
}
return last
}
+
+// ownClaude are the session ids of the Claude Code runs magpie started
+// itself: the subscription bridge's sessions, a warm-up's, a /usage read's.
+// Their prompts land in the user's history.jsonl beside the user's own, and
+// none of their requests reach the gateway as agent claude's (the bridge's
+// go as claude-desktop's, a warm-up's straight to Anthropic), so drift would
+// take them for the user using Claude Code behind magpie's back (#5100). An
+// entry is kept a week: a run tells its session each time it starts, and no
+// run lives longer than that.
+var ownClaude sync.Map // session id → time.Time
+
+// OwnSession notes the session id of a Claude Code run magpie started
+// itself.
+func OwnSession(sid string) {
+ if sid == "" {
+ return
+ }
+ ownClaude.Store(sid, time.Now())
+ ownClaude.Range(func(k, v any) bool {
+ if time.Since(v.(time.Time)) > 7*24*time.Hour {
+ ownClaude.Delete(k)
+ }
+ return true
+ })
+}
+
+// IsOwnSession says whether the Claude Code session was one magpie started
+// itself (OwnSession).
+func IsOwnSession(sid string) bool {
+ if sid == "" {
+ return false
+ }
+ _, ok := ownClaude.Load(sid)
+ return ok
+}
--
2.50.1 (Apple Git-155)
SHA-256 (first 16): ee10dd00a5739046
Verification
Red before the fix: with the fix's behavior reverted (the detector's skip and all three registrations; the session registry itself kept, inert then, so the tests still build), all four new tests fail; with the change in, they pass. Registry entries live a week and are re-registered at every run's start; an unregistered session still counts as use, so a real bypass still flags; a magpie restart empties the registry while bypassed's used.After(started) keeps pre-restart lines out anyway. Also checked: history.jsonl has one other drift reader (Codex's own file — magpie never starts Codex headless, nothing to exclude) and the sessions-list reader (internal/sessions, untouched — bridge sessions showing in the user's session list there is #3983's separate concern); no other agent sets LastUsed. Cost on the drift poll's hot path: one small JSON field parse and a map lookup per line of the 64 KB tail.
| Check | Result |
|---|---|
go test ./internal/agent/ -run TestClaudeDriftOwnSessions (change in) |
ok |
go test ./internal/gateway/ -run 'TestWarmClaudeSaysItsOwnSession|TestClaudeHelperSessionIsMagpiesOwn|TestClaudeBridgeSessionIsMagpiesOwn' (change in) |
ok |
| Ablation (behavior reverted, tests kept) | --- FAIL: TestClaudeDriftOwnSessions — "magpie's own warm-up: Kind:bypassed, Claude Code was used at 00:23 but none of its requests reached magpie" (the report's false positive, reproduced), --- FAIL: TestClaudeBridgeSessionIsMagpiesOwn, --- FAIL: TestWarmClaudeSaysItsOwnSession, --- FAIL: TestClaudeHelperSessionIsMagpiesOwn |
| Restored | all four ok again |
go test -tags nogui ./internal/usage/ ./internal/agent/ (full) |
ok, except TestMothX — fails on the parent commit too (verified at 1e1068c86), untouched by this patch |
go test -tags nogui ./internal/gateway/ (full) |
ok (656.5s, 0 failures) |
go test -race (drift + usage targeted) |
ok |
gofmt -l (changed files) |
clean |
go vet (changed packages) |
clean |
go build ./... (plain and -tags nogui) |
ok (pre-existing cgo/ld warnings only) |
Rebased 2026-11-06 onto upstream/main 326e72f4c |
one conflict: main's claudeBypassEnv (#5042) grew beside the spot; both kept. Targeted drift/warm-up tests red with OwnSession registration no-op'd, green restored; go test -tags nogui ./internal/gateway/ full ok (622.9s, 0 failures); gofmt -l/go vet/go build ./... clean |
Not verified
- Real Claude Code accepts
claude -p --session-id <uuid> --no-session-persistenceas expected: verified against magpie's fake-claude test harnesses, not against Anthropic's CLI; the helper already passes--session-idthe same way for interactive runs, so this follows magpie's existing practice. - The report's exact weekly-limit failure path (a warm-up that errors mid-run) — covered indirectly: the
-pwarm-up registers its session before claude starts, so a failed run's line is excluded regardless of the error. - Windows and WSL were not exercised here (the shell-script harnesses skip on Windows); on WSL the helper's claude writes the distro's own
history.jsonl, which the Windows-side drift check doesn't read.
AI use: written by GLM-5.3-Flash (ZCode) from the reporter's analysis in this issue.
Branch with the commit: https://github.com/ggbdpq/magpie/tree/fix/5100-drift-own-claude (head 0db2a61f92a72348c875db34068e9d926742da27)
take
补充一组 macOS 复现,和本 issue 的订阅桥接误报一致。
环境:Apple Silicon / macOS,Magpie 0.1.2637,Claude Code 2.1.316,Claude Desktop 4.4212.0。Claude Code 已配置本机网关。2026-11-04 23:46(UTC+08:00),Agents 页显示 was used without going through magpie 和 Reconnect。
以下为脱敏对照。A/B 是两个响应的代号:每组的 Claude Code transcript 中 assistant message ID 与 Magpie usage 的 response_id 一致,history 记录按同一 Claude Code 会话关联。
# A: 截图前的 Desktop 桥接调用
2026-11-04T23:43:10.952+08:00 agent=claude-desktop provider=claude served=claude-opus-5-5 status=200 response=A
2026-11-04T23:43:11.485+08:00 Claude Code history: non-slash input; transcript response=A
# 不点 Reconnect、不改配置;用新开的 Claude Code CLI 发送短测试
2026-11-04T23:48:22.309+08:00 agent=claude provider=claude served=claude-opus-5-5 status=200 response=CLI_PROBE
endpoint=/v1/messages; reply=MAGPIE_ROUTE_OK
# B: 探针后,Desktop 桥接再次推进 Claude Code 的历史时间
2026-11-04T23:48:30.647+08:00 agent=claude-desktop provider=claude served=claude-opus-5-5 status=200 response=B
2026-11-04T23:48:31.036+08:00 Claude Code history: non-slash input; transcript response=B
CLI 探针确实经网关成功。A/B 则说明 Magpie 的 Desktop 订阅桥接会写入 Claude Code 历史,但网关侧归为 claude-desktop。v0.1.2637 的检测逻辑 因而可以把桥接活动误当成 CLI 绕过。这个对照也说明,不能只凭 Claude Code 历史时间推断它直连。
B 是日志对照,未声称在 B 后再次看到红色提示;也未验证修复补丁或更新版本。账号、项目路径、原始会话和响应 ID、请求内容及截图均未公开。
补充一组 macOS / Apple Silicon 上的日志对照:预热成功时也会留下会推进 Claude Code LastUsed 的记录,与本 issue 的预热路径一致。
环境与版本:
- 正在运行的 Magpie 进程启动日志标明
0.1.2725(darwin/arm64)。应用包已更新至0.1.2850,但该进程自启动后尚未重启,因此这里按运行版本报告。 - Claude Code 的
~/.claude/settings.json仍保存ANTHROPIC_BASE_URL=http://127.0.0.1:3425,Magpie 正在监听此地址。 - 开启了 Claude 账号预热。
出现「Claude Code 最近绕过了 magpie,重新应用后请重启」后,回查得到以下对应记录。时间均为 2026-11-04,UTC+08:00;账号、完整临时路径和会话 ID 已省略。
Claude Code history.jsonl 时间 |
display |
project 特征 |
Magpie app.log |
|---|---|---|---|
| 23:00:33.796 | hi |
Magpie 临时目录 magpie-claude-work-<uid> |
23:00:35 claude warm-up: started <account>'s 5 hours window |
| 23:15:37.014 | hi |
同上 | 23:15:39,同样记录预热成功 |
| 23:45:40.506 | hi |
同上 | 23:45:42,同样记录预热成功 |
网关 usage.jsonl 中 agent: "claude" 的最后一条记录仍是当天 19:01:13;上述三次预热没有对应的 agent: "claude" 网关记录。因此,后续预热不断推进全局历史时间,却没有推进该 agent 的网关时间。
源码核对:
v0.1.2725的LastUsed直接读取全局history.jsonl。- 该版本的
bypassed()在历史时间更新、超过 30 秒且网关时间未跟上时判定绕过。 - 该版本的预热入口 会通过 Claude Code 发送
hi。 - 本次检查的上游
main为2d04fe73ddaf9470be139078a2583a82f58a0c17;Claude CodeLastUsed仍直接读取全局历史,尚未包含前面评论提出的按 Magpie 自有会话 ID 排除的逻辑。
这组证据来自现有运行记录的回查,未逐次观察表中每次预热后的 UI,也未实测本 issue 中的修复补丁。
补充一组 macOS / arm64、magpie 0.1.2965 的本机日志对照。现有证据与本 issue 的订阅桥接写入 Claude 全局历史、触发 CLI bypassed 检测这条路径高度一致。
环境与现象
- 运行中的 magpie 为
0.1.2965。app.log记录它于2026-11-04 23:29:24启动(darwin/arm64);本机网关GET /返回的运行版本也为0.1.2965。 - 本机 Claude Code CLI 为
2.1.318(执行claude --version核对)。同时使用 Claude Desktop,经 magpie 的 Claude 订阅桥接。 - Claude Code 的
~/.claude/settings.json仍为ANTHROPIC_BASE_URL=http://127.0.0.1:3425,该地址确由 magpie 监听。 - Agents 页反复出现「Claude Code 最近绕过了 magpie,重新应用后请重启」,手动「重新接入」后仍会再出现。
时间线(2026-11-05,UTC+08:00)
以下是现有日志的字段筛选与归一化摘录,不是完整原始日志。会话 ID、请求/响应 ID、PID、账号、用户目录、真实项目路径、第三方 provider 名称和输入正文均已省略。
00:52:25.483290 usage.jsonl agent=claude status=200
00:55:08.212522 applied.json claude.at=<这个时间>
01:04:56 history.jsonl non-slash input; project=<temp>/magpie-claude-work-<uid>
01:05:44 history.jsonl non-slash input; project=<同类临时目录>
01:05:52 history.jsonl non-slash input; project=<同类临时目录>
01:06:00 history.jsonl non-slash input; project=<同类临时目录>
01:06:03 history.jsonl non-slash input; project=<同类临时目录>
这五条记录存在于用户默认的 ~/.claude/history.jsonl,属于五个不同会话。它们都不是 /exit 等斜杠命令。
同期,magpie 的 app.log 有自己启动 Claude Code 的记录;下列 PID 已用代号替代:
01:05:43 claude: Claude Code pid RUN_A started, a run on <model> (interactive mode)
01:05:46 claude: Claude Code pid RUN_A (...) ended after 3s (exit status 1)
01:05:51 claude: Claude Code pid RUN_B started, a run on <model> (interactive mode)
01:05:53 claude: Claude Code pid RUN_B (...) ended after 3s (exit status 1)
01:06:00 claude: Claude Code pid RUN_C started, a run on <model> (interactive mode)
01:06:02 claude: Claude Code pid RUN_D started, a run on <model> (interactive mode)
01:06:02 claude: Claude Code pid RUN_C (...) ended after 3s (exit status 1)
01:06:25 claude: Claude Code pid RUN_D (...) ended after 23s (exit status 1)
本机还实际核对了存活进程的父子关系,确认存在:
magpie GUI → magpie claude-tui-helper → claude
同一时段,网关 usage.jsonl 中的成功流量归属是 claude-desktop:
01:05:43.363907 agent=claude-desktop provider=claude status=200
01:05:51.168801 agent=claude-desktop provider=claude status=200
01:05:55.340406 agent=claude-desktop provider=claude status=200
01:05:59.919504 agent=claude-desktop provider=claude status=200
01:06:02.612355 agent=claude-desktop provider=claude status=200
01:06:25.876700 agent=claude-desktop provider=claude status=200
01:06:34.780496 agent=claude-desktop provider=claude status=200
在本次回查的网关 usage 记录里,agent=claude 的最后一条仍停留在 00:52:25.483290;默认 Claude 历史却已被上述临时会话推进到 01:06:03,晚于 applied.json 中的 00:55:08。
与检测实现的对应
核对安装版本对应的源码:
- v0.1.2965 的 Claude Code LastUsed 直接读取默认 Claude 全局
history.jsonl。 - lastJSONLTime 仅排除斜杠命令,未按 magpie 自有会话 ID 排除内部调用。
- bypassed() 比较历史时间、进程启动时间、接入时间与该 agent 的
lastSeen,并保留 30 秒宽限。 - Reapply() 会重新应用配置并更新接入记录,因此能够暂时使此前历史不再触发;新的内部会话仍可再次推进历史。
因此,这组记录支持本 issue 描述的同类问题:magpie 自己启动的 Claude 活动进入用户全局历史,而相应时段的网关请求被记为 claude-desktop;CLI 的历史时间与 claude 网关时间发生错位。仅凭这组时间比较不能证明用户的 Claude Code 发生了直连。
验证边界:这是对已经存在的日志和进程状态的回查,没有逐次观察表中每条历史写入后的 UI;没有把每条 history 与具体网关响应按原始会话/响应 ID 做一一关联;没有复现本 issue 的额度预热路径,也没有实测评论中的社区修复补丁。本次未修改配置、重启进程或主动发送模型测试请求。
本评论由 AI 协助核对日志、整理并脱敏。
补充一组 Windows 11 ARM64 上的复现:最新的 magpie 0.1.3131 仍然会报,现象是订阅桥接这条路径。
环境
- magpie
0.1.3131(安装版,magpie --version) - Claude Code CLI
2.1.302(WinGet 安装),ANTHROPIC_BASE_URL指向本机网关 - Claude Desktop(3p)的 Code 页接入 magpie,模型走 Claude 订阅
现象
Agents 页 Claude Code 行显示「Claude Code 最近绕过了 magpie,重新应用后请重启」,并带有「重新接入」按钮。此时本机没有用户自己启动的 Claude Code,只是在 Desktop Code 页里对话。
本机对照(时间为本机 −08:00,2026-11-05)
applied.json 中 claude.at 为 17:38:24。
~/.claude/history.jsonl 末尾(只列时间、sessionId、project):
23:34:55 269c28a8-… C:\Users\<user>\Documents\Projects\Magpie
23:36:55 9619b363-… C:\Users\<user>\Documents\Projects\Magpie
23:38:13 980cbf32-… C:\Users\<user>\Documents\Projects\Optical Automation
23:38:32 9619b363-… C:\Users\<user>\Documents\Projects\Magpie
这几行都来自 Desktop Code 页的会话:
-
当时正在运行的桥接进程(
Win32_Process命令行,已截断):magpie.exe claude-tui-helper …\claude.exe -p --output-format stream-json --input-format stream-json … --setting-sources "" … --resume 9619b363-… (23:36:51 启动) magpie.exe claude-tui-helper …\claude.exe -p --output-format stream-json --input-format stream-json … --setting-sources "" … --resume 980cbf32-… (23:38:08 启动)其 sessionId 和上面的 history 行一致,转录写在默认的
~/.claude/projects/<用户项目>/下。 -
269c28a8-…是新开的 Desktop 会话。它的转录首条parentUuid为null,entrypoint为cli,图片路径包含magpie-claude-images-。所以写进用户history.jsonl的,不只有--resume旧会话的运行。
同一时段 usage.jsonl 中只有 agent=claude-desktop。最后一条 agent=claude 停在 2026-11-04 06:29。安装版二进制里搜不到 usage.OwnSession。引用本 issue 的提交 0db2a61f 目前还不在 main 上(compare 结果为 diverged,main 落后它 1 个提交),所以 0.1.3131 以及最新的 v0.1.3133 都还没有包含这个修复。
另外,history.jsonl 里有 300 行的 project 是 %TEMP%\magpie-claude-work,最近一条在 23:36:30,没有对应的转录文件。我没有逐条确认它们来自预热还是其他入口,但这些行同样会推进 LastUsed。
补充结论
- Windows 上也能复现,而且桥接用
-pstream-json 模式加--resume运行时,同样写入用户的~/.claude/history.jsonl。 - 新开的 Desktop 会话也会写入 history,不只限于续用旧会话。按
sessionId排除(上面补丁的思路)能覆盖这种情况;如果只在--resume时隔离配置目录,就盖不住。
Rebased onto current upstream/main (803d7747e): zero conflicts, head c6eded857, branch fix/5100-drift-own-claude. No upstream commits on the own-session marking path in this range.
Two corroborating reports since the patch landed, both pointing at the same bridge path — @jerrychoi (11-05, macOS/arm64, 0.1.2965: Desktop-Code conversation in ~/.claude/history.jsonl, "bypassed" banner with ANTHROPIC_BASE_URL pinned to the gateway) and @laweit-lxy (11-06, Windows 11 ARM64, 0.1.3131: same pairing with timestamps aligned against applied.json). Both are exactly the false positive this patch stops: the bridge's sessions get marked as magpie's own, so a Desktop-only conversation no longer reads as Claude Code sneaking past.
Verification on the new base:
TestClaudeDriftOwnSessions,TestClaudeBridgeSessionIsMagpiesOwn,TestWarmClaudeSaysItsOwnSession,TestClaudeHelperSessionIsMagpiesOwngreen.- Ablation on the new base:
IsOwnSessionfixed false → the drift-own and bridge-session tests red; restored → green. - Fresh patch
git ams clean onto a tree at803d7747e; sha256[:16]6f3bbd6583420f82. Real CLI/Desktop pairing stays NOT-RUNNABLE here — the two reports above are the live evidence.
Generated-by: GLM-5.3-Flash (ZCode)
0.1.3078(macOS)上今天仍出现这条提示。上游 main 当前代码中 LastUsed 的读法未变,最新发布为 v0.1.3528。
| 来源(11-09 19:56 至 11-10 14:07,UTC+08:00) | 行数 | 是否计入 LastUsed |
|---|---|---|
桥接工作目录下的 /usage |
157 | 否 |
桥接工作目录下的 [Pasted text #1 +N lines] |
83 | 是 |
| 用户项目目录下的非斜杠行(31 个会话) | 181 | 是 |
某行前 5 秒至后 30 秒内,若网关有 agent=claude-desktop、provider=claude 的请求开始,就算关联。181 行中关联 180 行;前 2 秒至后 10 秒内关联 172 行。同批时间整体后移 10 分钟,对照分别为 73、47 行。
用户真实项目目录下大量行与 Desktop 订阅请求同时出现,按桥接工作目录过滤仍会漏掉;仅凭时间关联无法确定桥接写入的确切行数。
本评论由 AI 根据本机日志统计起草