RustCats on X: a fresh magpie showed every agent's session history on
the Sessions page before anyone agreed to it, and asked for a per-agent
choice instead.
- sessions.Reads(agent) (internal/sessions/access.go) is the one gate,
from settings.SessionReads {Asked, All, Agents}. Every lister asks it,
the aggregators (allFiles, callFilesWith, callSourcesWith,
traceLineFiles, wslFiles, DesktopDataDirs) filter by it again, and
readers of an already-listed session (TranscriptOf, ContentOf,
SearchSession, SubagentTranscript, CarryOver, ReadCallSource) return
ErrNotRead, so a cache from before a switch was turned off goes no
further. The Sessions list, stats, /api/sessions/overview, the call and
trace indexes, Usage's agent-file calls and the Codex/Pi title readers
all pass it.
- SettleReads decides once and saves: an install with sessions.json or
a calls-v* cache read sessions before and keeps all on; a fresh one
reads none, not asked. A saved value is never replaced; save, sync and
restore keep it (KeepOwn); only SetSessionReads writes it. An
unwritable settings.json reads nothing this run.
- GUI: GET/POST /api/sessions/reads. While not asked, the Sessions page
shows a consent card: each agent found (by a stat of its folder only)
with a switch, Allow selected and Allow all. Settings > Privacy >
Agents' session history has "Agents found later" and a row per agent.
Strings in en, zh, zh-TW, ja, de.
- CLI: magpie sessions read [on|off all|<agent>...]; magpie sessions
says on stderr when nothing is allowed yet; the TUI's empty Sessions
page says how.
Read either way, because none of it lists or shows a session: the
gateway's own usage ledger, its projections and the conversations it
recorded (magpie's own records, so usage and cost keep working); the
agents' config and sign-in files; Claude Code's and Codex's
history.jsonl last-used time and a session file's mtime for a quota's
first use; Codex's newest rollout's last line before magpie restarts
Codex (codexTurnOpen).
Tests: TestFreshInstallReadsNoAgentUntilAllowed,
TestSettleReadsKeepsWhatWasThere, TestSessionReadsRoutes,
TestSessionsRead, TestSessionsNotAskedSaysHow, sessions-reads.test.cjs
(26 cases: consent and Settings in 5 languages, Chromium and WebKit,
390 to 900 wide).
Run on mote:
- full Go suite (gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui,
GOOS=windows go vet, go build, go test -timeout 45m ./...) at this
change on 8c63c5b78: 79 packages ok; internal/gui red on
TestSettingsSaveKeepsWhatItDoesNotSend (mine: SessionReads is written
by SetSessionReads only, the test now sets it so; green after) and
TestMainWindowCorners (the same on origin/main c1da9ccda, #3949).
- whole GUI suite (make test-ui, concurrency 2) at this change on
8c63c5b78: 14985 tests, 276 failed in 44 files. Mine: i18n-keys
(comments named "Allow all"/"Allow selected"; lowercased) and
account-discovery (read the last Privacy heading; now the one above
its list); both green after. The 44 files again on origin/main
c1da9ccda: 36 red there too (#4304, with #3218, #3412, #3414, #3795,
#4120, #4125). stays-strict green alone; gateway-key-models webkit red
1 of 3 alone on main too; plugin-github de 440 red on main (#3218).
- at the pushed head (rebased on cd10dfbe6): go build ./...; go test
internal/sessions, settings, cli, tui ok; internal/gui
TestSettingsSave*, TestSessionReads*, TestSessions* ok; i18n-keys,
account-discovery, sessions-reads: 62 pass, 0 fail.
Broken by hand:
- the aggregator filter off with the leaf gates on: green (the leaf
gates hold); both off: TestFreshInstall red on List, Agents, Calls,
CallSources, traces, stats, TranscriptOf and Search.
- consentApplies=false and Settings' old save({all}) without the rows:
all 13 Chromium cases of sessions-reads red.
- sessNothing's hint removed: TestSessionsNotAskedSaysHow red.
Real binary in a sandbox HOME on mote (removed after): a fresh
`magpie sessions` is empty with the hint on stderr; `sessions read`
says not asked, claude off; `read --help` prints usage and saves
nothing; `read on claude` lists the one session; `read off all`
empties it again.
Not tried: the GUI and real app on Windows and Linux; WSL agents in the
consent list (WSL distros are not looked into; Allow all covers them);
a fresh install of a signed release build.
252 lines
7.9 KiB
Go
252 lines
7.9 KiB
Go
package sessions
|
|
|
|
import (
|
|
"bytes"
|
|
"cmp"
|
|
"encoding/json"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/yetone/magpie/internal/appdir"
|
|
)
|
|
|
|
// WorkBuddy (Tencent's desktop agent) keeps its sessions much as Claude
|
|
// Code does, under its folder's projects/: a session's <id>.jsonl in its
|
|
// project's folder, with <id>.meta.json beside it (the cwd, for the ones it
|
|
// brought over from its older history). Its lines are the OpenAI Agents
|
|
// SDK's items — "message", "reasoning", "function_call",
|
|
// "function_call_result" — and "ai-title" and "custom-title", each with its
|
|
// time (timestamp, in milliseconds), the session id and mostly the cwd. What
|
|
// a reply spent is in providerData.usage of one of its lines (the assistant
|
|
// message's, or its last function call's), named by the reply's
|
|
// providerData.messageId: input with what was read from the cache in it
|
|
// (inputTokensDetails[].cached_tokens), output with the reasoning. The
|
|
// sessions brought over from its older history have it as input_tokens and
|
|
// output_tokens instead, at times one line for the whole conversation.
|
|
// WorkBuddy is a desktop app: nothing resumes a session from a terminal.
|
|
|
|
// WorkBuddyDir is WorkBuddy's folder: $WORKBUDDY_CONFIG_DIR, else ~/.workbuddy.
|
|
func WorkBuddyDir() string {
|
|
if d := strings.TrimSpace(appdir.Getenv("WORKBUDDY_CONFIG_DIR")); d != "" {
|
|
return expandHome(d)
|
|
}
|
|
home, _ := os.UserHomeDir()
|
|
return filepath.Join(home, ".workbuddy")
|
|
}
|
|
|
|
// workbuddyFiles are the sessions under WorkBuddy's projects/, however deep:
|
|
// a session's own <id>.jsonl, and a subagent's under <id>/subagents/.
|
|
func workbuddyFiles() []file { return buddyFiles("workbuddy", WorkBuddyDir()) }
|
|
|
|
// codebuddyFiles are the same under CodeBuddy Code's projects/: the CLI keeps
|
|
// them as its desktop sibling does, one agent's folder apart (#1779). None
|
|
// when its folder is WorkBuddy's, which workbuddyFiles reads already.
|
|
func codebuddyFiles() []file {
|
|
if codebuddyInWorkBuddy() {
|
|
return nil
|
|
}
|
|
return buddyFiles("codebuddy", CodeBuddyDir())
|
|
}
|
|
|
|
// codebuddyInWorkBuddy is whether CodeBuddy Code's folder is WorkBuddy's
|
|
// ($CODEBUDDY_CONFIG_DIR set to ~/.workbuddy, or a link to it). Its sessions
|
|
// are then read once, as WorkBuddy's: read as both, each was listed and
|
|
// counted twice, and one refresh took each path twice (#2932).
|
|
func codebuddyInWorkBuddy() bool { return sameFolder(CodeBuddyDir(), WorkBuddyDir()) }
|
|
|
|
// sameFolder is whether a and b are one folder on disk, however each is
|
|
// spelled (a link, a letter's case where the disk ignores it). A folder
|
|
// that can't be read is no other.
|
|
func sameFolder(a, b string) bool {
|
|
x, err := os.Stat(a)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
y, err := os.Stat(b)
|
|
return err == nil && os.SameFile(x, y)
|
|
}
|
|
|
|
// isBuddy is whether agent keeps its sessions the way WorkBuddy does: its
|
|
// own, or CodeBuddy Code's.
|
|
func isBuddy(agent string) bool { return agent == "workbuddy" || agent == "codebuddy" }
|
|
|
|
// buddyFiles are the sessions under projects/ in dir, as agent's: WorkBuddy's,
|
|
// or CodeBuddy Code's, which keeps them the same way.
|
|
func buddyFiles(agent, dir string) []file {
|
|
if !Reads(agent) {
|
|
return nil
|
|
}
|
|
var out []file
|
|
walkLinked(filepath.Join(dir, "projects"), func(p string, d os.DirEntry, err error) error {
|
|
if err != nil || d.IsDir() || !strings.HasSuffix(d.Name(), ".jsonl") {
|
|
return nil
|
|
}
|
|
f := file{agent: agent, key: agent + ":" + strings.TrimSuffix(d.Name(), ".jsonl"), path: p, main: true}
|
|
if dir := filepath.Dir(p); filepath.Base(dir) == "subagents" {
|
|
f.key, f.main = agent+":"+filepath.Base(filepath.Dir(dir)), false
|
|
}
|
|
if stat(&f) {
|
|
out = append(out, f)
|
|
}
|
|
return nil
|
|
})
|
|
return out
|
|
}
|
|
|
|
// wbDetails are the details of a count WorkBuddy wrote down: a list of them
|
|
// (inputTokensDetails: [{cached_tokens}]), or one.
|
|
type wbDetails []map[string]int
|
|
|
|
func (d *wbDetails) UnmarshalJSON(b []byte) error {
|
|
var list []map[string]int
|
|
if json.Unmarshal(b, &list) == nil {
|
|
*d = list
|
|
return nil
|
|
}
|
|
var one map[string]int
|
|
if json.Unmarshal(b, &one) == nil {
|
|
*d = wbDetails{one}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (d wbDetails) sum(key string) int {
|
|
n := 0
|
|
for _, m := range d {
|
|
n += m[key]
|
|
}
|
|
return n
|
|
}
|
|
|
|
type wbLine struct {
|
|
Type string `json:"type"`
|
|
Role string `json:"role"`
|
|
ID string `json:"id"`
|
|
Cwd string `json:"cwd"`
|
|
SessionID string `json:"sessionId"`
|
|
AITitle string `json:"aiTitle"`
|
|
CustomTitle string `json:"customTitle"`
|
|
Content json.RawMessage `json:"content"`
|
|
ProviderData struct {
|
|
MessageID string `json:"messageId"`
|
|
Model string `json:"model"`
|
|
RequestModel string `json:"requestModelId"`
|
|
Usage *struct {
|
|
Input int `json:"inputTokens"`
|
|
Output int `json:"outputTokens"`
|
|
InputDetails wbDetails `json:"inputTokensDetails"`
|
|
OldInput int `json:"input_tokens"`
|
|
OldOutput int `json:"output_tokens"`
|
|
OldDetails wbDetails `json:"input_tokens_details"`
|
|
CacheWrite int `json:"cacheCreationTokens"`
|
|
OldCacheWrite int `json:"cache_creation_input_tokens"`
|
|
} `json:"usage"`
|
|
} `json:"providerData"`
|
|
}
|
|
|
|
var (
|
|
wbUsage = []byte(`"usage"`)
|
|
wbTitle = []byte(`-title"`)
|
|
wbUser = []byte(`"role":"user"`)
|
|
wbCwd = []byte(`"cwd":"`)
|
|
wbScene = regexp.MustCompile(`^@[\w-]+:\S*$`)
|
|
)
|
|
|
|
func workbuddyLine(s *state, b []byte, main bool) {
|
|
at := numTS(b)
|
|
s.saw(at, main)
|
|
want := bytes.Contains(b, wbUsage) ||
|
|
main && (bytes.Contains(b, wbTitle) || s.First == "" && bytes.Contains(b, wbUser)) ||
|
|
s.Cwd == "" && bytes.Contains(b, wbCwd)
|
|
if !want {
|
|
return
|
|
}
|
|
var l wbLine
|
|
if json.Unmarshal(b, &l) != nil {
|
|
return
|
|
}
|
|
if s.Cwd == "" && l.Cwd != "" {
|
|
s.Cwd = l.Cwd
|
|
}
|
|
if s.ID == "" && l.SessionID != "" {
|
|
s.ID = l.SessionID
|
|
}
|
|
p := l.ProviderData
|
|
if m := cmp.Or(p.Model, p.RequestModel); m != "" {
|
|
s.Model = m // the model in use, for a usage that names none
|
|
}
|
|
switch l.Type {
|
|
case "custom-title":
|
|
// named by the user: before the one WorkBuddy made
|
|
if main && l.CustomTitle != "" {
|
|
s.Custom = title(l.CustomTitle)
|
|
}
|
|
case "ai-title":
|
|
if main && l.AITitle != "" {
|
|
s.Named = title(l.AITitle)
|
|
}
|
|
case "message":
|
|
if main && l.Role == "user" && s.First == "" {
|
|
s.First = wbPrompt(l.Content)
|
|
}
|
|
}
|
|
u := p.Usage
|
|
if u == nil {
|
|
return
|
|
}
|
|
in, out := cmp.Or(u.Input, u.OldInput), cmp.Or(u.Output, u.OldOutput)
|
|
read := u.InputDetails.sum("cached_tokens") + u.OldDetails.sum("cached_tokens")
|
|
write := cmp.Or(u.CacheWrite, u.OldCacheWrite)
|
|
t := Tokens{Input: max(0, in-read-write), Output: out, CacheRead: read, CacheWrite: write}
|
|
model := cmp.Or(p.Model, p.RequestModel, s.Model, "auto")
|
|
id := p.MessageID
|
|
if id != "" && id == s.Msg {
|
|
// another line of the reply counted: its usage stands for the whole
|
|
s.unuse(s.MsgDay, s.MsgModel, s.MsgUse)
|
|
}
|
|
date := dateOf(at)
|
|
s.Msg, s.MsgModel, s.MsgUse, s.MsgDay = id, model, t, date
|
|
s.use(date, model, t)
|
|
}
|
|
|
|
// wbPrompt is the words typed in a user message: its input_text blocks,
|
|
// less what WorkBuddy put in beside them (<system-reminder>…, @scene:…).
|
|
func wbPrompt(content json.RawMessage) string {
|
|
var text string
|
|
if json.Unmarshal(content, &text) == nil {
|
|
if strings.HasPrefix(strings.TrimSpace(text), "<") {
|
|
return ""
|
|
}
|
|
return title(text)
|
|
}
|
|
var blocks []struct{ Type, Text string }
|
|
if json.Unmarshal(content, &blocks) != nil {
|
|
return ""
|
|
}
|
|
var parts []string
|
|
for _, b := range blocks {
|
|
t := strings.TrimSpace(b.Text)
|
|
if (b.Type == "input_text" || b.Type == "text") && t != "" && !strings.HasPrefix(t, "<") && !wbScene.MatchString(t) {
|
|
parts = append(parts, t)
|
|
}
|
|
}
|
|
return title(strings.Join(parts, " "))
|
|
}
|
|
|
|
// workbuddyMeta fills in a session's cwd from its meta file, for the lines
|
|
// that name none.
|
|
func workbuddyMeta(s *state, path string) {
|
|
b, err := os.ReadFile(strings.TrimSuffix(path, ".jsonl") + ".meta.json")
|
|
if err != nil {
|
|
return
|
|
}
|
|
var m struct {
|
|
Cwd string `json:"cwd"`
|
|
}
|
|
if json.Unmarshal(b, &m) == nil {
|
|
s.Cwd = m.Cwd
|
|
}
|
|
}
|