sessions: the Claude subscription bridge's own runs are not local sessions
iwinux on X: a Pi request through a group a Claude subscription serves was listed twice in the request log, once as "Pi · Claude Code" and once as "Claude Code · Local session", with the same tokens and cost. Cause: a bridge run is the real Claude Code. It saves its session in the account's projects folder, in the caller's folder's project: the user's own ~/.claude or a saved account's claude-accounts folder, both of which appdir.ClaudeHomes lists. listCCFiles read it as a session of the user's, and the ledger's pairing (request id, then session and tokens) didn't match it with the gateway's record, whose session is the caller's. So every call was counted twice: request log, usage ledger, cost totals, the Sessions page. -p runs and interactive (TUI) runs alike, plus a branch's cut copy and a replayed transcript. Fix: every session a bridge run saves is named by the new internal/bridgesid. New is a version 4 UUID whose last six bytes are a keyed SHA-256 of its first ten, the key a random file of this computer's (<config>/claude-bridge-session-key, made once by temp file + link). To Anthropic, which Claude Code sends the session id to, it is as random as any, so it marks nothing upstream. startRun passes --session-id for a new run (-p and interactive; the TUI helper keeps a --session-id it is given and makes a marked one otherwise), replaySession and cutSessionWhere name their files with it. listCCFiles leaves out a .jsonl, and a session's sub-agent folder, whose id bridgesid.Is knows, for agent "claude" only. That one listing feeds calls, the ledger, the request log, Sessions, traces and WSL distros, so all of them drop the double count. Other bridged runs (warm-up, askClaude, /usage, WSL -p) use --no-session-persistence and write no session. Rows already counted twice: a bridge session already removed (a run's session is removed when it ends) is gone from the ledger already, as it is read from the files there are. One still on disk under an old random id (a live or shelved run resumed under it, or a stopped gateway's leftover in a caller's folder) can't be told from the user's and stays counted until it is removed; old ids carry no mark to fix it on read. Tests: TestNewIsKnown, TestKeyKept, TestKeyMadeOnce (bridgesid); TestBridgeSessionsAreNotLocal (sessions: a marked session in the user's folder, its sub-agent file, and one in a saved account's folder give no calls and no rows; the user's session beside them counts); TestClaudeRunSessionsAreTheBridges (-p and interactive, a new run and a replayed transcript) and TestClaudeCutSessionIsTheBridges (gateway). Broken by hand, on mica: bridged() returning false made TestBridgeSessionsAreNotLocal red (calls req_m1..m4, want req_m1 alone); newUUID back in startRun, replaySession and cutSessionWhere made both gateway tests red (print, interactive and the cut copy). Run on mica at this head (rebased on7ea1e6a4b): gofmt -l clean, go vet ./... ok, go build ok; go test -tags nogui ./internal/bridgesid ./internal/sessions ./internal/usage ok; ./internal/gateway -run 'Claude|Subscription|Bridge|Fork|Shelf' ok. At the first base (8a59e7616): the same vet plus GOOS=linux -tags nogui and GOOS=windows vet ok, the three builds ok, ./internal/claudetui ./internal/appdir ./internal/masking ok. The full ./... suite was not run: mica's suite lock had five full suites queued ahead of it, and this ships now. Not tried: a real Claude Code run with a real account (mote is down; the -p --session-id flag is Claude Code's documented one, and the interactive helper already passed it); Windows and WSL runs.
This commit is contained in:
@@ -1669,6 +1669,25 @@ removed there by its id, when it ends or is discarded (`removeSession`).
|
||||
A session that a stopped gateway left there, and its temp files, stay
|
||||
there as the user's own sessions do; a sweep can't tell them apart.
|
||||
|
||||
Every session a run saves is named by `bridgesid.New`: a new run's
|
||||
(`--session-id`, in `-p` and in the interactive mode, whose helper keeps
|
||||
the id it is given), a replayed transcript's (`replaySession`) and a
|
||||
branch's copy (`cutSession`). The id is a version 4 UUID whose last six
|
||||
bytes are a keyed hash of its first ten, the key a random file of this
|
||||
computer's (`<config>/claude-bridge-session-key`), so to Anthropic, which
|
||||
Claude Code tells the session id, it is as random as any. The
|
||||
local-session readers (`listCCFiles` in `internal/sessions`, through
|
||||
`bridgesid.Is`) leave such a session and its sub-agents' files out: read
|
||||
as a session of the user's Claude Code, each call the gateway counted
|
||||
under the agent that asked was listed and counted again as "Claude Code ·
|
||||
Local session", in the request log, the usage ledger, cost totals and
|
||||
the Sessions page (iwinux on X). A session saved before 11-14 has a plain
|
||||
random id and is still read until it is removed (when its run ends, or
|
||||
by the sweep); a stopped gateway's leftover in a caller's folder stays
|
||||
until the user removes it. `TestClaudeRunSessionsAreTheBridges`,
|
||||
`TestClaudeCutSessionIsTheBridges` and `TestBridgeSessionsAreNotLocal`
|
||||
hold it.
|
||||
|
||||
## Files a run leaves
|
||||
|
||||
- Its session: `<config>/projects/<work project>/<session>.jsonl`, for
|
||||
|
||||
@@ -295,6 +295,18 @@ call magpie had routed was counted again as a local session's whatever
|
||||
provider id ZCode wrote beside it (nori_tsukiji on X). Verification:
|
||||
`TestZCodeCallsPairWithTheGatewaysRecords`.
|
||||
|
||||
The Claude subscription bridge's own Claude Code runs save their sessions
|
||||
in a Claude folder the readers list (the user's own, or a saved account's
|
||||
under `claude-accounts`), often in the caller's project. They aren't the
|
||||
user's: the gateway recorded each call under the agent that asked, and
|
||||
nothing paired the session file's call with that record, so every call was
|
||||
counted twice, once as "Claude Code · Local session" (iwinux on X). Their
|
||||
ids are the bridge's (`bridgesid`, see
|
||||
[the bridge](claude-subscription-bridge.md#the-runs-working-folder-clientworkdir)),
|
||||
and `listCCFiles` leaves such a session and its sub-agents' files out of
|
||||
every listing: calls, the ledger, the Sessions page, traces and WSL.
|
||||
Verification: `TestBridgeSessionsAreNotLocal`.
|
||||
|
||||
A ZCode session's name is the app's: its task index
|
||||
(`v2/tasks-index.sqlite` in the data folder, `tasks.title` by `task_id`,
|
||||
the session's id) holds what the app shows and what the user renamed it to,
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
// Package bridgesid names the Claude Code sessions the Claude subscription
|
||||
// bridge runs, so the local-session readers can tell them from the user's
|
||||
// own.
|
||||
//
|
||||
// A bridge run is the real Claude Code, and it saves its session where
|
||||
// Claude Code saves the user's: the account's projects folder, in the
|
||||
// caller's folder's project. The readers of local sessions took it for a
|
||||
// session of the user's, and the request the gateway already counted was
|
||||
// counted again as "Claude Code · Local session", its tokens and cost
|
||||
// twice (iwinux on X: a Pi request through a Claude subscription group
|
||||
// listed twice since the bridge runs the interactive mode).
|
||||
//
|
||||
// Every session a bridge run writes gets an id New made: a version 4 UUID
|
||||
// whose last six bytes are a keyed hash of its first ten. The key is this
|
||||
// computer's own (a random file in magpie's config folder), so the id is as
|
||||
// random as any to anyone without it, Anthropic, which Claude Code tells
|
||||
// the session id, included, while magpie's readers check it with no list
|
||||
// to keep: Is.
|
||||
package bridgesid
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
)
|
||||
|
||||
// keyFile is the key's file in magpie's config folder.
|
||||
const keyFile = "claude-bridge-session-key"
|
||||
|
||||
// recheck is how long a missing or unreadable key is believed missing
|
||||
// before its file is looked at again: Is is asked for every Claude Code
|
||||
// session file a listing finds.
|
||||
const recheck = 10 * time.Second
|
||||
|
||||
var key struct {
|
||||
sync.Mutex
|
||||
dir string // the config folder the key was read for
|
||||
k []byte
|
||||
missing time.Time
|
||||
}
|
||||
|
||||
// keyFor is the key in config folder dir, made there first when create is
|
||||
// set and there is none. nil when there is none, or it can't be read: no
|
||||
// id is then taken for a bridge's.
|
||||
func keyFor(dir string, create bool) []byte {
|
||||
key.Lock()
|
||||
defer key.Unlock()
|
||||
if key.dir != dir {
|
||||
key.dir, key.k, key.missing = dir, nil, time.Time{}
|
||||
}
|
||||
if key.k != nil {
|
||||
return key.k
|
||||
}
|
||||
if !create && !key.missing.IsZero() && time.Since(key.missing) < recheck {
|
||||
return nil
|
||||
}
|
||||
path := filepath.Join(dir, keyFile)
|
||||
k, err := readKey(path)
|
||||
if errors.Is(err, fs.ErrNotExist) && create {
|
||||
k, err = makeKey(path)
|
||||
}
|
||||
if err != nil {
|
||||
key.missing = time.Now()
|
||||
return nil
|
||||
}
|
||||
key.k, key.missing = k, time.Time{}
|
||||
return k
|
||||
}
|
||||
|
||||
func readKey(path string) ([]byte, error) {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
k, err := hex.DecodeString(strings.TrimSpace(string(b)))
|
||||
if err != nil || len(k) != 32 {
|
||||
return nil, fmt.Errorf("%s: not a key", path)
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
// makeKey writes a new key at path, unless another process wrote one
|
||||
// first: then that one is the key.
|
||||
func makeKey(path string) ([]byte, error) {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
k := make([]byte, 32)
|
||||
if _, err := rand.Read(k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// written whole under a name of its own, then linked to path: a reader
|
||||
// never sees half of it, and a second writer's link fails
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), keyFile+".*")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
_, err = tmp.WriteString(hex.EncodeToString(k) + "\n")
|
||||
if cerr := tmp.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.Link(tmp.Name(), path); err != nil {
|
||||
if errors.Is(err, fs.ErrExist) {
|
||||
return readKey(path)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
// mark is the keyed hash of a session id's first ten bytes.
|
||||
func mark(k []byte, head []byte) [sha256.Size]byte {
|
||||
var in [32 + 10]byte
|
||||
copy(in[:], k)
|
||||
copy(in[32:], head)
|
||||
return sha256.Sum256(in[:])
|
||||
}
|
||||
|
||||
// New is a session id for a bridge run: a version 4 UUID that Is knows.
|
||||
// Without a key (magpie's config folder can't be written) it is a plain
|
||||
// random one, which the readers take for the user's.
|
||||
func New() string {
|
||||
var b [16]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
b[6] = b[6]&0x0f | 0x40
|
||||
b[8] = b[8]&0x3f | 0x80
|
||||
if k := keyFor(appdir.Config(), true); k != nil {
|
||||
m := mark(k, b[:10])
|
||||
copy(b[10:], m[:6])
|
||||
}
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
|
||||
}
|
||||
|
||||
// Is says id is a session New made on this computer.
|
||||
func Is(id string) bool {
|
||||
if len(id) != 36 || id[8] != '-' || id[13] != '-' || id[18] != '-' || id[23] != '-' {
|
||||
return false
|
||||
}
|
||||
var b [16]byte
|
||||
n := 0
|
||||
for i := 0; i < len(id); i++ {
|
||||
if i == 8 || i == 13 || i == 18 || i == 23 {
|
||||
continue
|
||||
}
|
||||
v, ok := unhex(id[i])
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
b[n/2] |= v << (4 * (1 - n%2))
|
||||
n++
|
||||
}
|
||||
k := keyFor(appdir.Config(), false)
|
||||
if k == nil {
|
||||
return false
|
||||
}
|
||||
m := mark(k, b[:10])
|
||||
return [6]byte(m[:6]) == [6]byte(b[10:])
|
||||
}
|
||||
|
||||
func unhex(c byte) (byte, bool) {
|
||||
switch {
|
||||
case c >= '0' && c <= '9':
|
||||
return c - '0', true
|
||||
case c >= 'a' && c <= 'f':
|
||||
return c - 'a' + 10, true
|
||||
case c >= 'A' && c <= 'F':
|
||||
return c - 'A' + 10, true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package bridgesid
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var uuidV4 = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
|
||||
|
||||
func sandbox(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
t.Setenv("HOME", dir)
|
||||
t.Setenv("USERPROFILE", dir)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
|
||||
return filepath.Join(dir, "config", "magpie")
|
||||
}
|
||||
|
||||
// An id New makes is a version 4 UUID Claude Code takes, and Is knows it;
|
||||
// a random UUID and junk it doesn't.
|
||||
func TestNewIsKnown(t *testing.T) {
|
||||
sandbox(t)
|
||||
for range 50 {
|
||||
id := New()
|
||||
if !uuidV4.MatchString(id) {
|
||||
t.Fatalf("%q is not a version 4 UUID", id)
|
||||
}
|
||||
if !Is(id) {
|
||||
t.Fatalf("Is(%q) = false for an id New made", id)
|
||||
}
|
||||
}
|
||||
for _, no := range []string{
|
||||
"0b6f2c8e-3a41-4c2d-9e7f-5a1b2c3d4e5f", // a session of the user's
|
||||
"", "not-a-uuid", "0b6f2c8e3a414c2d9e7f5a1b2c3d4e5f",
|
||||
"0b6f2c8e-3a41-4c2d-9e7f-5a1b2c3d4e5g",
|
||||
} {
|
||||
if Is(no) {
|
||||
t.Errorf("Is(%q) = true", no)
|
||||
}
|
||||
}
|
||||
// one bit changed anywhere is no longer the bridge's
|
||||
id := []byte(New())
|
||||
id[0] ^= 1
|
||||
if Is(string(id)) {
|
||||
t.Errorf("Is(%q) = true with its first byte changed", id)
|
||||
}
|
||||
}
|
||||
|
||||
// The key is kept in magpie's config folder: an id made before is known
|
||||
// after a restart (the key read again), and another computer's (another
|
||||
// key) is not.
|
||||
func TestKeyKept(t *testing.T) {
|
||||
cfg := sandbox(t)
|
||||
id := New()
|
||||
b, err := os.ReadFile(filepath.Join(cfg, keyFile))
|
||||
if err != nil || len(b) != 65 {
|
||||
t.Fatalf("the key file: %q %v", b, err)
|
||||
}
|
||||
forget() // as a new process has no key
|
||||
if !Is(id) {
|
||||
t.Fatalf("an id made before the key was read again isn't known")
|
||||
}
|
||||
sandbox(t)
|
||||
if Is(id) {
|
||||
t.Fatalf("another config folder's key knew the id")
|
||||
}
|
||||
if New(); Is(id) {
|
||||
t.Fatalf("a new key knew the old one's id")
|
||||
}
|
||||
}
|
||||
|
||||
// With no key, Is knows nothing and makes no key; New makes one. Two that
|
||||
// make it at once end with the same key.
|
||||
func TestKeyMadeOnce(t *testing.T) {
|
||||
cfg := sandbox(t)
|
||||
if Is("0b6f2c8e-3a41-4c2d-9e7f-5a1b2c3d4e5f") {
|
||||
t.Fatal("Is said yes with no key")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(cfg, keyFile)); err == nil {
|
||||
t.Fatal("Is made a key")
|
||||
}
|
||||
keys := make([][]byte, 8)
|
||||
var wg sync.WaitGroup
|
||||
for i := range keys {
|
||||
wg.Go(func() { keys[i], _ = makeKey(filepath.Join(cfg, keyFile)) })
|
||||
}
|
||||
wg.Wait()
|
||||
for _, k := range keys {
|
||||
if len(k) != 32 || string(k) != string(keys[0]) {
|
||||
t.Fatalf("keys made at once differ: %x", keys)
|
||||
}
|
||||
}
|
||||
forget()
|
||||
if id := New(); !Is(id) {
|
||||
t.Fatalf("an id made with the shared key isn't known")
|
||||
}
|
||||
}
|
||||
|
||||
// forget drops the key read, as a new process starts with none.
|
||||
func forget() {
|
||||
key.Lock()
|
||||
key.dir, key.k, key.missing = "", nil, time.Time{}
|
||||
key.Unlock()
|
||||
}
|
||||
+10
-11
@@ -19,7 +19,6 @@ package claudetui
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -39,6 +38,7 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/bridgesid"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/wslrun"
|
||||
)
|
||||
@@ -151,16 +151,23 @@ func Run(args []string) error {
|
||||
}
|
||||
args = interactiveArgs(pargs[len(wslArgs(wsl)):])
|
||||
s := &shim{out: os.Stdout, changed: make(chan struct{}, 1), rowsCh: make(chan struct{}, 1), exited: make(chan struct{}), readDone: make(chan struct{}), wsl: wsl, listed: mcpListed(args)}
|
||||
resume := ""
|
||||
resume, named := "", ""
|
||||
for i, a := range args {
|
||||
if a == "--resume" && i+1 < len(args) {
|
||||
resume = args[i+1]
|
||||
}
|
||||
if a == "--session-id" && i+1 < len(args) {
|
||||
named = args[i+1]
|
||||
}
|
||||
}
|
||||
if resume != "" {
|
||||
s.sid = resume
|
||||
} else if named != "" {
|
||||
// the bridge's own id, which the local-session readers know
|
||||
// (bridgesid)
|
||||
s.sid = named
|
||||
} else {
|
||||
s.sid = newUUID()
|
||||
s.sid = bridgesid.New()
|
||||
args = append(args, "--session-id", s.sid)
|
||||
}
|
||||
s.projects = filepath.Join(configDir(), "projects")
|
||||
@@ -1603,14 +1610,6 @@ func (s *shim) turnOver() {
|
||||
s.rowsMu.Unlock()
|
||||
}
|
||||
|
||||
func newUUID() string {
|
||||
var b [16]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
b[6] = b[6]&0x0f | 0x40
|
||||
b[8] = b[8]&0x3f | 0x80
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
|
||||
}
|
||||
|
||||
// interactiveArgs are `claude -p` arguments made the interactive mode's:
|
||||
// the same model, tools, MCP servers, settings, effort, system prompt and
|
||||
// session, without what only -p takes; its permission prompts kept, and
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/bridgesid"
|
||||
)
|
||||
|
||||
// runSession is the session a run's Claude Code was named: given with
|
||||
// --session-id, or resumed with --resume.
|
||||
func runSession(t *testing.T, log string) string {
|
||||
t.Helper()
|
||||
args, _, _ := strings.Cut(log, "\n")
|
||||
for _, flag := range []string{"--session-id ", "--resume "} {
|
||||
if _, v, ok := strings.Cut(args, flag); ok {
|
||||
v, _, _ = strings.Cut(v, " ")
|
||||
return v
|
||||
}
|
||||
}
|
||||
t.Fatalf("the run was named no session: %s", args)
|
||||
return ""
|
||||
}
|
||||
|
||||
// Every session a bridge run's Claude Code saves has an id bridgesid
|
||||
// knows, in -p and in the interactive mode, a new run's and a replayed
|
||||
// transcript's: the local-session readers leave them out, as the gateway
|
||||
// counts their calls already (iwinux on X: each call listed twice, the
|
||||
// second time as "Claude Code · Local session").
|
||||
func TestClaudeRunSessionsAreTheBridges(t *testing.T) {
|
||||
t.Run("print", func(t *testing.T) {
|
||||
h := newScriptHarness(t, "ok", "")
|
||||
h.ask("rules", "a1")
|
||||
h.ask("other rules", "b1", "b2") // no run has it: told whole
|
||||
runs := h.runs()
|
||||
if len(runs) != 2 {
|
||||
t.Fatalf("%d runs", len(runs))
|
||||
}
|
||||
for _, log := range runs {
|
||||
if sid := runSession(t, log); !bridgesid.Is(sid) {
|
||||
t.Errorf("a -p run's session %s isn't the bridge's", sid)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("interactive", func(t *testing.T) {
|
||||
h := tuiScriptHarness(t, "")
|
||||
h.ask("rules", "a1")
|
||||
h.ask("other rules", "b1", "b2") // a transcript replayed
|
||||
runs := h.runs()
|
||||
if len(runs) != 2 {
|
||||
t.Fatalf("%d runs", len(runs))
|
||||
}
|
||||
resumed := false
|
||||
for _, log := range runs {
|
||||
resumed = resumed || strings.Contains(log, "--resume ")
|
||||
if sid := runSession(t, log); !bridgesid.Is(sid) {
|
||||
t.Errorf("an interactive run's session %s isn't the bridge's", sid)
|
||||
}
|
||||
}
|
||||
if !resumed {
|
||||
t.Errorf("no run resumed a replayed transcript: %v", runs)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A branch's copy of a run's session is the bridge's too.
|
||||
func TestClaudeCutSessionIsTheBridges(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
dir := t.TempDir()
|
||||
lines := `{"type":"user","uuid":"a","sessionId":"S"}` + "\n" +
|
||||
`{"type":"assistant","uuid":"b","sessionId":"S"}` + "\n"
|
||||
if err := os.WriteFile(filepath.Join(dir, "S.jsonl"), []byte(lines), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := cutSession([]string{dir}, "S", "b")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bridgesid.Is(id) {
|
||||
t.Fatalf("the copy %s isn't the bridge's", id)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/bridgesid"
|
||||
)
|
||||
|
||||
// replaySession is a saved session written for a conversation no run has
|
||||
@@ -55,7 +57,7 @@ func replaySession(dirs []string, work, model string, req *Request) *savedSessio
|
||||
for _, b := range blocks {
|
||||
delete(b, "cache_control")
|
||||
}
|
||||
sid, user, assistant := newUUID(), newUUID(), newUUID()
|
||||
sid, user, assistant := bridgesid.New(), newUUID(), newUUID()
|
||||
at := time.Now().UTC()
|
||||
line := func(parent any, uuid, kind string, message map[string]any, at time.Time) []byte {
|
||||
b, _ := json.Marshal(map[string]any{
|
||||
|
||||
@@ -61,6 +61,7 @@ import (
|
||||
|
||||
"github.com/santhosh-tekuri/jsonschema/v6"
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/bridgesid"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/claudecode"
|
||||
"github.com/yetone/magpie/internal/claudetui"
|
||||
@@ -1166,7 +1167,14 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
if from != nil {
|
||||
args = append(args, "--resume", from.session)
|
||||
fromLen = from.size()
|
||||
} else if hasReply(req.Messages) {
|
||||
} else {
|
||||
// a session of the bridge's names itself so (bridgesid): the
|
||||
// local-session readers leave it out, as the gateway counts its
|
||||
// calls already (iwinux on X: each call listed twice, once as
|
||||
// Claude Code's local session)
|
||||
args = append(args, "--session-id", bridgesid.New())
|
||||
}
|
||||
if from == nil && hasReply(req.Messages) {
|
||||
// no run had the conversation: this one is told it whole, in one
|
||||
// message, its earlier turns marked as such (renderClaudePrompt)
|
||||
log.Printf("claude: a new Claude Code is told the whole conversation: %d messages, %d images, the last turn marked as the one to answer", len(req.Messages), countImages(req.Messages))
|
||||
@@ -3184,7 +3192,7 @@ func cutSessionWhere(dirs []string, sid, what string, at func(b []byte, last boo
|
||||
if end <= 0 {
|
||||
continue
|
||||
}
|
||||
id := newUUID()
|
||||
id := bridgesid.New() // the copy is the bridge's too
|
||||
lines := bytes.ReplaceAll(b[:end], []byte(`"sessionId":"`+sid+`"`), []byte(`"sessionId":"`+id+`"`))
|
||||
// a name no one has: nothing reads it before the run starts
|
||||
path := filepath.Join(dir, id+".jsonl")
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/bridgesid"
|
||||
)
|
||||
|
||||
// A session the Claude subscription bridge's Claude Code saved, in the
|
||||
// user's own Claude folder or a saved account's, is not one of the user's:
|
||||
// the gateway counts its calls already, under the agent that asked. Read
|
||||
// as a local session too, each call was listed and counted twice (iwinux
|
||||
// on X: a Pi request through a Claude subscription group, again as
|
||||
// "Claude Code · Local session", the same tokens and cost). Its
|
||||
// sub-agents' files go with it; the user's sessions, beside it in the
|
||||
// same project, are counted as before.
|
||||
func TestBridgeSessionsAreNotLocal(t *testing.T) {
|
||||
d := setupCalls(t)
|
||||
config := filepath.Join(t.TempDir(), "config")
|
||||
t.Setenv("XDG_CONFIG_HOME", config)
|
||||
own, other := bridgesid.New(), bridgesid.New()
|
||||
saved := filepath.Join(config, "magpie", "claude-accounts", "a1")
|
||||
user := func(id string) string {
|
||||
return `{"type":"user","timestamp":"` + stamp(0) + `","message":{"role":"user","content":"hello"},"cwd":"/work/app","sessionId":"` + id + `"}`
|
||||
}
|
||||
// the user's own session, and a bridge run's in the same project
|
||||
writeLines(t, filepath.Join(d.claude, "projects", "-work-app", "main1.jsonl"),
|
||||
user("main1"), swap(claudeMsg("m1", "claude-opus-5-5", 1, 2, 0, 0, 1), `"sess1"`, `"main1"`))
|
||||
writeLines(t, filepath.Join(d.claude, "projects", "-work-app", own+".jsonl"),
|
||||
user(own), swap(claudeMsg("m2", "claude-opus-5-5", 2, 490, 0, 0, 2), `"sess1"`, `"`+own+`"`))
|
||||
writeLines(t, filepath.Join(d.claude, "projects", "-work-app", own, "subagents", "agent-a.jsonl"),
|
||||
swap(claudeMsg("m3", "claude-opus-5-5", 3, 4, 0, 0, 3), `"sess1"`, `"`+own+`"`))
|
||||
// a saved account's run
|
||||
writeLines(t, filepath.Join(saved, "projects", "-work-app", other+".jsonl"),
|
||||
user(other), swap(claudeMsg("m4", "claude-opus-5-5", 5, 6, 0, 0, 4), `"sess1"`, `"`+other+`"`))
|
||||
|
||||
got := map[string]int{}
|
||||
for _, c := range Calls(time.Time{}) {
|
||||
got[c.RequestID]++
|
||||
}
|
||||
if len(got) != 1 || got["req_m1"] != 1 {
|
||||
t.Fatalf("calls %v, want the user's req_m1 alone", got)
|
||||
}
|
||||
rows := map[string]int{}
|
||||
for _, s := range List(0) {
|
||||
rows[s.ID]++
|
||||
}
|
||||
if len(rows) != 1 || rows["main1"] != 1 {
|
||||
t.Fatalf("sessions %v, want the user's main1 alone", rows)
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ import (
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/bridgesid"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/dirent"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
@@ -902,6 +903,14 @@ func joinedIs(s, a, b string, sep ...byte) bool {
|
||||
return len(s) == len(a)+1+len(b) && s[len(a)] == c && s[:len(a)] == a && s[len(a)+1:] == b
|
||||
}
|
||||
|
||||
// bridged says id is the session of a Claude Code run the Claude
|
||||
// subscription bridge started (bridgesid.Is), not one of the user's: the
|
||||
// gateway counts every call of it already, under the agent that asked, and
|
||||
// read here too it was counted again as a local session's (iwinux on X).
|
||||
// It is the id alone that tells, so it holds wherever the run saved it: an
|
||||
// account's folder or the user's own, a caller's project or magpie's, WSL.
|
||||
func bridged(agent, id string) bool { return agent == "claude" && bridgesid.Is(id) }
|
||||
|
||||
func listCCFiles(agent, dir string) []file {
|
||||
projects := filepath.Join(dir, "projects")
|
||||
watch(dir) // statFiles reads only the projects that changed
|
||||
@@ -929,10 +938,13 @@ func listCCFiles(agent, dir string) []file {
|
||||
root := filepath.Join(projects, project.Name())
|
||||
for _, e := range readDirectory(root) {
|
||||
if !e.IsDir() && strings.HasSuffix(e.Name(), ".jsonl") {
|
||||
if bridged(agent, strings.TrimSuffix(e.Name(), ".jsonl")) {
|
||||
continue
|
||||
}
|
||||
path, key := names.of(root, e.Name(), agent, strings.TrimSuffix(e.Name(), ".jsonl"))
|
||||
f := file{agent: agent, key: key, path: path, main: true}
|
||||
out = append(out, f)
|
||||
} else if dirent.IsFolder(root, e) {
|
||||
} else if dirent.IsFolder(root, e) && !bridged(agent, e.Name()) {
|
||||
path := filepath.Join(root, e.Name())
|
||||
subs := filepath.Join(path, "subagents")
|
||||
for _, sub := range readDirectory(subs) {
|
||||
|
||||
Reference in New Issue
Block a user