Files
magpie/internal/sessions/workbuddy.go
T
yetoneandJoeyWu-tech 572a1757cc sessions: a path listed twice in one read is read once, so the start's warm-up no longer quits magpie (#2932)
Since c381e4cd1 (#2776) each file a refresh reads has an
entry in parsing, closed and deleted when its parse is published.
refresh checked parsing[f.path] while picking the files to read but set
the entry only later, while building the jobs, so a path listed twice
in one want passed the check twice: two jobs on one entry, and the
second publish closed a nil channel. The start's warm-up
(warmSessions -> StatsAndNative -> refresh) took magpie down a few
seconds after every start, in the GUI, `magpie web` and --gateway alike.
Reported by TimWongUp, nativeas, tianhao2316-beep, mxl2498, cunnak and
Tsuki-hash, on Windows and macOS.

Two sources of the duplicate were found in the thread:
- CODEBUDDY_CONFIG_DIR on WorkBuddy's folder (TimWongUp's .zshrc;
  on Windows WorkBuddy's installer, or its IDE host for its children,
  sets both variables to one .workbuddy): codebuddyFiles and
  workbuddyFiles listed each .jsonl once each.
- A Hermes state.db holding one session id as a TEXT and a BLOB row
  (nativeas): both scan to one string, one <db>#<id> path.

The change, JoeyWu-tech's fix/2932-rebased (7cc938ca) with two test
changes:
- refresh marks a file in parsing as it takes it, so a second listing
  of the path is left out (or waited on). This is the guard: whatever
  list repeats a path, no refresh reads it twice.
- allFiles and callSources keep each path once (distinctPaths), so a
  path is not counted twice either. OpenCode's list doubles the same
  TEXT/BLOB rows (tested); ZCode's and Alma's would too.
- hermesFiles keeps one file a session id, as late as its later row.
- codebuddyFiles lists nothing when CodeBuddy Code's folder is
  WorkBuddy's (os.SameFile: a link or Windows' case rules count too),
  so those sessions are WorkBuddy's on the Sessions page and in usage;
  Dirs names such a folder once. A session the CodeBuddy CLI wrote
  there shows as WorkBuddy's (agreed by TimWongUp on the issue).

Added here: TestCodeBuddyInWorkBuddysFolderIsReadOnce has a "both"
case, both variables on one folder as the Windows reports have it, and
runs StatsAndNative(0) first, the warm-up's own call.
TestOpenCodeIDStoredAsTextAndBlobIsListedOnce lists under mu with
useDBs, as List does: it left OpenCode's db open, and on Windows its
TempDir could not be removed ("being used by another process").

Red on origin/main (sessions code of 86254d404, these tests, a test-only
sameFolder shim): TestRefreshReadsAPathListedTwiceOnce,
TestCodeBuddyInWorkBuddysFolderIsReadOnce (named and both) and
TestHermesIDStoredAsTextAndBlobIsOneSession panic "close of nil
channel" at sessions.go:891 from refresh at :905; the "both" case from
stats.go:143 and :117, the reports' frames.
TestOpenCodeIDStoredAsTextAndBlobIsListedOnce: "allFiles lists the
session 2 times", the same for callSources. Same on the Windows box.
Broken by hand: with only the refresh marking undone, the refresh test
panics again; with codebuddyFiles' check off, the CodeBuddy test fails
"calls ... codebuddy:6, want WorkBuddy's 6" and "listed 3 WorkBuddy and
3 CodeBuddy Code sessions, want 3 and 0". Restored, green.

Run:
- Full suite, `go test -timeout 45m ./...` (pipefail, log kept whole),
  darwin arm64, go1.26.8, at 31136c446 (86254d404 + these two
  changes, before the OpenCode test's useDBs change): 68 packages ok,
  no FAIL; internal/sessions 158s, internal/gateway 579s. No suite lock
  exists on this machine; no other full suite was running.
- At the pushed head (rebased on ec7e50b82, a redact-only change):
  go test ./internal/sessions/ ok, -race ./internal/sessions/ ok
  (109s); -race -count=5 on the four new tests and
  TestReadNotHeldByAnotherRead ok earlier.
- Windows 11 box (cross-compiled test binary, testenv's sandbox HOME):
  the whole internal/sessions package PASS with the fix, the linked
  case included; the new tests red on main's code as above.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows:
  ok.

Not tried: a real WorkBuddy/CodeBuddy install, a real Hermes state.db
with a BLOB id, or the app's GUI start on Windows; the tests use the
fixtures under the reporters' settings. Not covered: two agents told
to share a folder under different spellings other than CodeBuddy and
WorkBuddy (Pi and omp, Qoder and Qoder CN) still list it twice, without
the crash: #3258.

Co-authored-by: JoeyWu-tech <71250493+JoeyWu-tech@users.noreply.github.com>
2026-10-22 18:06:07 +08:00

249 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 {
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
}
}