diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index b2175e552..98e8c0664 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -4914,7 +4914,7 @@ function renderSessions() { if (!used.length && !list.length) { stats.classList.add("empty"); const filtered = sessAgent !== "all" || sessModel || sessFolder || q; - stats.append(el("div", "none", !all.length && !rows.length ? t("No sessions yet. Claude Code's and Codex's sessions on this computer show up here, with what each cost and the command that resumes it.") : filtered ? t("No session matches.") : t("Nothing in this range."))); + stats.append(el("div", "none", !all.length && !rows.length ? t("No sessions yet. Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.") : filtered ? t("No session matches.") : t("Nothing in this range."))); box.hidden = true; chart.hidden = true; } else { diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index c69cdc3e6..a0a78c359 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -603,7 +603,7 @@ const I18N = { "at list price": "按标价", "just now": "刚刚", "No session matches.": "没有匹配的会话。", - "No sessions yet. Claude Code's and Codex's sessions on this computer show up here, with what each cost and the command that resumes it.": "还没有会话。这台电脑上 Claude Code 和 Codex 的会话会显示在这里,附带各自的费用和继续会话的命令。", + "No sessions yet. Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "还没有会话。这台电脑上 Claude Code、Codex、OpenCode 和 Pi 的会话会显示在这里,附带各自的费用和继续会话的命令。", "Reading the agents' session files…": "正在读取 Agent 的会话文件…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "合计统计 Agent 自己文件里的全部会话;列表为按最近活动取的 {n} 个 · {dirs}", "90 days": "90 天", diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index e5b16f373..3789245b2 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -42,7 +42,10 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { agents[a.ID] = a } out := sessionsJSON{Sessions: []sessionJSON{}, Terminal: runtime.GOOS == "darwin" && !isWeb(w), - Dirs: []string{tilde(sessions.ClaudeDir()), tilde(sessions.CodexDir())}} + Dirs: []string{}} + for _, d := range sessions.Dirs() { + out.Dirs = append(out.Dirs, tilde(d)) + } list := sessions.List(n) since := time.Now() for _, s := range list { diff --git a/internal/sessions/opencode.go b/internal/sessions/opencode.go new file mode 100644 index 000000000..34a2a003b --- /dev/null +++ b/internal/sessions/opencode.go @@ -0,0 +1,365 @@ +package sessions + +import ( + "database/sql" + "encoding/json" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// OpenCode keeps a session as rows, not a file of lines: since 1.2 in its +// SQLite database (opencode.db: session, message and part tables, each +// message and part a JSON document), before that as JSON files under +// storage/ — session//.json, message//.json and +// part//.json. The database is made from those files once, +// which stay behind, so where there is a database only it is read. An +// assistant message carries its model and its tokens, input without the +// cache and output without the reasoning. A subagent's work is a session +// of its own whose parent is the session it ran in, and counts there. + +// OpenCodeDir is OpenCode's data folder: $XDG_DATA_HOME/opencode, else +// ~/.local/share/opencode — on Windows too, where OpenCode keeps it there. +func OpenCodeDir() string { + if d := os.Getenv("XDG_DATA_HOME"); d != "" { + return filepath.Join(d, "opencode") + } + home, _ := os.UserHomeDir() + return filepath.Join(home, ".local", "share", "opencode") +} + +// openCodeDB is OpenCode's database: $OPENCODE_DB (a path in the data +// folder unless absolute), else opencode.db there. +func openCodeDB() string { + if p := os.Getenv("OPENCODE_DB"); p != "" && p != ":memory:" { + if filepath.IsAbs(p) { + return p + } + return filepath.Join(OpenCodeDir(), p) + } + return filepath.Join(OpenCodeDir(), "opencode.db") +} + +// ocInfo is a session as OpenCode keeps it, a row or a file. +type ocInfo struct { + ID string `json:"id"` + ParentID string `json:"parentID"` + Directory string `json:"directory"` + Title string `json:"title"` + Time struct { + Created int64 `json:"created"` + Updated int64 `json:"updated"` + } `json:"time"` +} + +// ocMessage is a message, a JSON document in either store. +type ocMessage struct { + ID string `json:"id"` + Role string `json:"role"` + ModelID string `json:"modelID"` + Time struct { + Created int64 `json:"created"` + Completed int64 `json:"completed"` + } `json:"time"` + Path *struct { + Cwd string `json:"cwd"` + } `json:"path"` + Tokens *struct { + Input int `json:"input"` + Output int `json:"output"` + Reasoning int `json:"reasoning"` + Cache struct { + Read int `json:"read"` + Write int `json:"write"` + } `json:"cache"` + } `json:"tokens"` +} + +// ocPart is a part of a message: only its text is looked at, for a title. +type ocPart struct { + Type string `json:"type"` + Text string `json:"text"` + Synthetic bool `json:"synthetic"` + Ignored bool `json:"ignored"` +} + +// ocStore is where OpenCode keeps its sessions: its database or its files. +type ocStore interface { + info(sid string) (ocInfo, bool) + messages(sid string) [][]byte // in no set order + parts(mid string) [][]byte // in order +} + +func ms(n int64) time.Time { + if n <= 0 { + return time.Time{} + } + return time.UnixMilli(n) +} + +// openCodeFiles are OpenCode's sessions, one "file" each: in the database +// its path is the database's and #, its size the count of its +// messages and its time that of the latest change to one; from the files +// its own file's path, the sum of its messages' sizes and the latest time. +func openCodeFiles() []file { + if db := openCodeDB(); fileExists(db) { + return openCodeDBFiles(db) + } + return openCodeJSONFiles(filepath.Join(OpenCodeDir(), "storage")) +} + +func fileExists(p string) bool { + fi, err := os.Stat(p) + return err == nil && fi.Mode().IsRegular() +} + +// ocRoots gives each session the key of the session it ran under, the one +// at the top: a subagent's subagent counts there too. +func ocRoots(out []file, parent map[string]string) []file { + for i := range out { + root := out[i].sid + for n := 0; parent[root] != "" && n < 64; n++ { + root = parent[root] + } + out[i].key = "opencode:" + root + out[i].main = parent[out[i].sid] == "" + } + return out +} + +// ---- the database ------------------------------------------------------------- + +// dbs are the databases open while List or Stats reads them, closed when +// they are done (closeDBs). +var dbs = map[string]*sql.DB{} + +func openDB(path string) *sql.DB { + if db := dbs[path]; db != nil { + return db + } + db, err := provider.OpenReadOnly(path) + if err != nil { + return nil + } + db.SetMaxOpenConns(4) + dbs[path] = db + return db +} + +func closeDBs() { + for p, db := range dbs { + db.Close() + delete(dbs, p) + } +} + +type ocDB struct{ db *sql.DB } + +func openCodeDBFiles(path string) []file { + db := openDB(path) + if db == nil { + return nil + } + rows, err := db.Query(`SELECT s.id, COALESCE(s.parent_id, ''), s.time_updated, COUNT(m.id), COALESCE(MAX(m.time_updated), 0) + FROM session s LEFT JOIN message m ON m.session_id = s.id GROUP BY s.id`) + if err != nil { + return nil + } + defer rows.Close() + store := ocDB{db} + var out []file + parent := map[string]string{} + for rows.Next() { + var id, par string + var updated, n, last int64 + if rows.Scan(&id, &par, &updated, &n, &last) != nil { + continue + } + parent[id] = par + out = append(out, file{agent: "opencode", path: path + "#" + id, sid: id, oc: store, size: n, mod: ms(max(updated, last))}) + } + return ocRoots(out, parent) +} + +func (s ocDB) info(sid string) (ocInfo, bool) { + var i ocInfo + err := s.db.QueryRow(`SELECT id, COALESCE(parent_id, ''), directory, title, time_created, time_updated FROM session WHERE id = ?`, sid). + Scan(&i.ID, &i.ParentID, &i.Directory, &i.Title, &i.Time.Created, &i.Time.Updated) + return i, err == nil +} + +func (s ocDB) rows(query, arg string) [][]byte { + rows, err := s.db.Query(query, arg) + if err != nil { + return nil + } + defer rows.Close() + var out [][]byte + for rows.Next() { + var b []byte + if rows.Scan(&b) == nil { + out = append(out, b) + } + } + return out +} + +func (s ocDB) messages(sid string) [][]byte { + return s.rows(`SELECT data FROM message WHERE session_id = ?`, sid) +} + +func (s ocDB) parts(mid string) [][]byte { + return s.rows(`SELECT data FROM part WHERE message_id = ? ORDER BY id`, mid) +} + +// ---- the files ---------------------------------------------------------------- + +type ocFiles struct{ root string } // storage/ + +func openCodeJSONFiles(root string) []file { + infos, _ := filepath.Glob(filepath.Join(root, "session", "*", "*.json")) + store := ocFiles{root} + var out []file + parent := map[string]string{} + for _, p := range infos { + b, err := os.ReadFile(p) + var i ocInfo + if err != nil || json.Unmarshal(b, &i) != nil || i.ID == "" { + continue + } + f := file{agent: "opencode", path: p, sid: i.ID, oc: store} + if !stat(&f) { + continue + } + // a message's file is written again as its reply goes on + f.size = 0 + if es, err := os.ReadDir(filepath.Join(root, "message", i.ID)); err == nil { + for _, e := range es { + if fi, err := e.Info(); err == nil && fi.Mode().IsRegular() { + f.size += fi.Size() + if fi.ModTime().After(f.mod) { + f.mod = fi.ModTime() + } + } + } + } + parent[i.ID] = i.ParentID + out = append(out, f) + } + return ocRoots(out, parent) +} + +func (s ocFiles) info(sid string) (ocInfo, bool) { + ps, _ := filepath.Glob(filepath.Join(s.root, "session", "*", sid+".json")) + for _, p := range ps { + var i ocInfo + if b, err := os.ReadFile(p); err == nil && json.Unmarshal(b, &i) == nil { + return i, true + } + } + return ocInfo{}, false +} + +func (s ocFiles) docs(dir string) [][]byte { + ps, _ := filepath.Glob(filepath.Join(s.root, dir, "*.json")) + sort.Strings(ps) + var out [][]byte + for _, p := range ps { + if b, err := os.ReadFile(p); err == nil { + out = append(out, b) + } + } + return out +} + +func (s ocFiles) messages(sid string) [][]byte { return s.docs(filepath.Join("message", sid)) } +func (s ocFiles) parts(mid string) [][]byte { return s.docs(filepath.Join("part", mid)) } + +// ---- reading a session -------------------------------------------------------- + +// parseOpenCode reads a session whole: a message's usage is written in +// place as its reply goes on, so there is no reading on from before. +func parseOpenCode(f file) *state { + s := &state{Size: f.size, Mod: f.mod.UnixNano()} + if f.oc == nil { + return s + } + info, ok := f.oc.info(f.sid) + if !ok { + return s + } + s.ID, s.Cwd = info.ID, info.Directory + if t := title(info.Title); t != "" && !ocDefaultTitle(t) { + s.Named = t + } + var msgs []ocMessage + for _, b := range f.oc.messages(f.sid) { + var m ocMessage + if json.Unmarshal(b, &m) == nil { + msgs = append(msgs, m) + } + } + sort.SliceStable(msgs, func(i, j int) bool { + if msgs[i].Time.Created != msgs[j].Time.Created { + return msgs[i].Time.Created < msgs[j].Time.Created + } + return msgs[i].ID < msgs[j].ID + }) + s.saw(ms(info.Time.Created), f.main) + for _, m := range msgs { + at := ms(m.Time.Created) + s.saw(at, f.main) + switch m.Role { + case "user": + if f.main && s.Title == "" && s.First == "" { + ocTitle(s, f.oc.parts(m.ID)) + } + case "assistant": + if done := ms(m.Time.Completed); !done.IsZero() { + s.saw(done, f.main) + at = done + } + if s.Cwd == "" && m.Path != nil { + s.Cwd = m.Path.Cwd + } + if t := m.Tokens; t != nil && m.ModelID != "" { + s.use(dateOf(at), m.ModelID, Tokens{Input: t.Input, Output: t.Output + t.Reasoning, CacheRead: t.Cache.Read, CacheWrite: t.Cache.Write}) + } + } + } + return s +} + +// ocTitle takes a session's title from its first prompt: the words typed, +// not what OpenCode put in beside them (a file read, a command's template). +func ocTitle(s *state, parts [][]byte) { + var typed, other []string + for _, b := range parts { + var p ocPart + if json.Unmarshal(b, &p) != nil || p.Type != "text" || p.Ignored || strings.TrimSpace(p.Text) == "" { + continue + } + if p.Synthetic { + other = append(other, p.Text) + } else { + typed = append(typed, p.Text) + } + } + if t := strings.Join(typed, " "); strings.HasPrefix(strings.TrimSpace(t), "<") { + s.First = untagged(t) + } else { + s.Title = title(t) + } + if s.Title == "" && s.First == "" { + s.First = untagged(strings.Join(other, " ")) + } +} + +// ocDefaultTitle is the title OpenCode gives a session before it names it. +func ocDefaultTitle(t string) bool { + return strings.HasPrefix(t, "New session - ") || strings.HasPrefix(t, "Child session - ") +} diff --git a/internal/sessions/opencode_pi_test.go b/internal/sessions/opencode_pi_test.go new file mode 100644 index 000000000..eb403ad56 --- /dev/null +++ b/internal/sessions/opencode_pi_test.go @@ -0,0 +1,279 @@ +package sessions + +import ( + "database/sql" + "encoding/json" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + _ "modernc.org/sqlite" +) + +const ( + ocMain = "ses_1a2b3c4d5e6fAAAAAAAAAAAAAA" + ocChild = "ses_1a2b3c4d5e6fBBBBBBBBBBBBBB" + piFirst = "0199aaaa-1111-7222-8333-444455556666" + piFork = "0199bbbb-1111-7222-8333-444455556666" +) + +// setupMore is setup with OpenCode's JSON files and Pi's sessions put +// where the two keep them. +func setupMore(t *testing.T) (data, pi string) { + claude, _ := setup(t) + dir := filepath.Dir(claude) + data, pi = filepath.Join(dir, "data"), filepath.Join(dir, "pi") + copyTree(t, "testdata/opencode", filepath.Join(data, "opencode")) + copyTree(t, "testdata/pi", pi) + return +} + +func find(t *testing.T, ss []Session, agent, id string) Session { + t.Helper() + for _, s := range ss { + if s.Agent == agent && s.ID == id { + return s + } + } + t.Fatalf("no %s session %s in %+v", agent, id, ss) + return Session{} +} + +func at(s string) time.Time { + t, _ := time.Parse(time.RFC3339, s) + return t +} + +// checkOpenCode checks the OpenCode fixtures' one session with anything in +// it: its subagent's usage in, the reasoning in the output, the typed words +// of its first prompt its title. +func checkOpenCode(t *testing.T, ss []Session) { + t.Helper() + n := 0 + for _, s := range ss { + if s.Agent == "opencode" { + n++ + } + } + if n != 1 { + t.Fatalf("want 1 OpenCode session (the child in its parent, the empty one out), got %d: %+v", n, ss) + } + oc := find(t, ss, "opencode", ocMain) + if oc.Cwd != "/work/oc" || oc.Title != "Why does the login test flake?" { + t.Fatalf("opencode: %+v", oc) + } + if a := model(oc, "gpt-6-astra"); a.Tokens != (Tokens{1000, 120, 5000, 0}) || !a.Priced { + t.Fatalf("astra: %+v", a) + } + if l := model(oc, "codex/gpt-6-luna"); l.Tokens != (Tokens{300, 60, 2000, 0}) || l.Priced { + t.Fatalf("luna: %+v", l) + } + if o := model(oc, "claude-opus-5-5"); o.Tokens != (Tokens{40, 60, 700, 300}) { + t.Fatalf("the subagent's opus: %+v", o) + } + if !oc.Start.Equal(at("2026-09-26T10:00:00Z")) || !oc.Last.Equal(at("2026-09-26T10:03:00Z")) { + t.Fatalf("opencode times %s %s", oc.Start, oc.Last) + } + if runtime.GOOS != "windows" { + if want := "cd '/work/oc' && opencode --session " + ocMain; oc.Resume != want { + t.Fatalf("resume %q", oc.Resume) + } + } +} + +func TestOpenCodeFiles(t *testing.T) { + inZone(t, 0) + setupMore(t) + checkOpenCode(t, List(0)) + + // the work of the main session only, 10:00:00–10:03:00, every pause short + s := statsAt(0, statsNow) + if got, sec := usageOn(s, "2026-09-26", "/work/oc"); got != (Tokens{1340, 240, 7700, 300}) || sec != 180 { + t.Fatalf("opencode on the 26th: %+v, %ds active", got, sec) + } +} + +// ocDB builds an OpenCode database from the JSON fixtures, as OpenCode's +// own migration does. +func ocMakeDB(t *testing.T, path string) *sql.DB { + t.Helper() + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Close() }) + for _, q := range []string{ + "PRAGMA journal_mode=WAL", + "CREATE TABLE session (id text PRIMARY KEY, project_id text NOT NULL, parent_id text, slug text NOT NULL, directory text NOT NULL, title text NOT NULL, version text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, time_archived integer, tokens_input integer DEFAULT 0 NOT NULL)", + "CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)", + "CREATE TABLE part (id text PRIMARY KEY, message_id text NOT NULL, session_id text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)", + } { + if _, err := db.Exec(q); err != nil { + t.Fatal(err) + } + } + root := "testdata/opencode/storage" + infos, _ := filepath.Glob(filepath.Join(root, "session", "*", "*.json")) + for _, p := range infos { + var i ocInfo + b, _ := os.ReadFile(p) + if err := json.Unmarshal(b, &i); err != nil { + t.Fatal(err) + } + var parent any + if i.ParentID != "" { + parent = i.ParentID + } + // the times OpenCode's migration gave them: not the latest message's + if _, err := db.Exec("INSERT INTO session (id, project_id, parent_id, slug, directory, title, version, time_created, time_updated) VALUES (?, '0f3a', ?, 's', ?, ?, '1.1.53', ?, ?)", + i.ID, parent, i.Directory, i.Title, i.Time.Created, i.Time.Created); err != nil { + t.Fatal(err) + } + msgs, _ := filepath.Glob(filepath.Join(root, "message", i.ID, "*.json")) + for _, mp := range msgs { + b, _ := os.ReadFile(mp) + var m ocMessage + json.Unmarshal(b, &m) + ocInsert(t, db, i.ID, m.ID, m.Time.Created, max(m.Time.Created, m.Time.Completed), string(b)) + parts, _ := filepath.Glob(filepath.Join(root, "part", m.ID, "*.json")) + for _, pp := range parts { + b, _ := os.ReadFile(pp) + if _, err := db.Exec("INSERT INTO part VALUES (?, ?, ?, 0, 0, ?)", filepath.Base(pp), m.ID, i.ID, string(b)); err != nil { + t.Fatal(err) + } + } + } + } + return db +} + +func ocInsert(t *testing.T, db *sql.DB, sid, mid string, created, updated int64, data string) { + t.Helper() + if _, err := db.Exec("INSERT INTO message VALUES (?, ?, ?, ?, ?)", mid, sid, created, updated, data); err != nil { + t.Fatal(err) + } +} + +func TestOpenCodeDB(t *testing.T) { + inZone(t, 0) + data, _ := setupMore(t) + // the JSON files stay behind beside the database made from them: only + // the database is read + db := ocMakeDB(t, filepath.Join(data, "opencode", "opencode.db")) + ss := List(0) + checkOpenCode(t, ss) + oc := find(t, ss, "opencode", ocMain) + if filepath.Base(oc.Path) != "opencode.db#"+ocMain { + t.Fatalf("path %s", oc.Path) + } + s := statsAt(0, statsNow) + if got, sec := usageOn(s, "2026-09-26", "/work/oc"); got != (Tokens{1340, 240, 7700, 300}) || sec != 180 { + t.Fatalf("opencode on the 26th: %+v, %ds active", got, sec) + } + + // a reply later in the subagent: its session is read again + ocInsert(t, db, ocChild, "msg_0005", 1790416990000, 1790417000000, + `{"id":"msg_0005","role":"assistant","modelID":"claude-opus-5-5","tokens":{"input":1,"output":2,"reasoning":0,"cache":{"read":3,"write":4}},"time":{"created":1790416990000,"completed":1790417000000}}`) + oc = find(t, List(0), "opencode", ocMain) + if o := model(oc, "claude-opus-5-5"); o.Tokens != (Tokens{41, 62, 703, 304}) { + t.Fatalf("after a new reply: %+v", o) + } + if !oc.Last.Equal(at("2026-09-26T10:03:20Z")) { + t.Fatalf("last %s", oc.Last) + } + + // $OPENCODE_DB names another database, in the data folder; with none + // made there yet, the JSON files are what there is + t.Setenv("OPENCODE_DB", "other.db") + if oc := find(t, List(0), "opencode", ocMain); filepath.Ext(oc.Path) != ".json" { + t.Fatalf("read a database $OPENCODE_DB doesn't name: %s", oc.Path) + } + if len(dbs) != 0 { + t.Fatalf("databases left open: %v", dbs) + } +} + +func TestPi(t *testing.T) { + inZone(t, 0) + setupMore(t) + ss := List(0) + p := find(t, ss, "pi", piFirst) + if p.Cwd != "/work/pi" || p.Title != "Refactor the parser" { + t.Fatalf("pi: %+v", p) + } + // a tool's model work and a compaction on the model in use, a usage + // entry on its own + if o := model(p, "claude-opus-5-5"); o.Tokens != (Tokens{110, 55, 1300, 200}) || !o.Priced { + t.Fatalf("opus: %+v", o) + } + if o := model(p, "claude/claude-opus-5-5"); o.Tokens != (Tokens{60, 40, 500, 0}) { + t.Fatalf("magpie's opus: %+v", o) + } + if !p.Start.Equal(at("2026-09-24T08:00:00Z")) || !p.Last.Equal(at("2026-09-24T08:04:00Z")) { + t.Fatalf("pi times %s %s", p.Start, p.Last) + } + if runtime.GOOS != "windows" { + if want := "cd '/work/pi' && pi --session " + piFirst; p.Resume != want { + t.Fatalf("resume %q", p.Resume) + } + } + + // the fork: what it copied counted in the session it came from + f := find(t, ss, "pi", piFork) + if f.Tokens != (Tokens{7, 3, 0, 0}) || f.Title != "Refactor the parser" { + t.Fatalf("fork: %+v", f) + } + if !f.Start.Equal(at("2026-09-25T09:00:00Z")) || !f.Last.Equal(at("2026-09-25T09:00:20Z")) { + t.Fatalf("fork times %s %s", f.Start, f.Last) + } + + s := statsAt(0, statsNow) + if got, sec := usageOn(s, "2026-09-24", "/work/pi"); got != (Tokens{170, 95, 1800, 200}) || sec != 240 { + t.Fatalf("pi on the 24th: %+v, %ds active", got, sec) + } + if got, sec := usageOn(s, "2026-09-25", "/work/pi"); got != (Tokens{7, 3, 0, 0}) || sec != 20 { + t.Fatalf("pi on the 25th: %+v, %ds active", got, sec) + } +} + +// Pi's sessions in a folder of the user's choosing, all in one, as the +// sessionDir setting or $PI_CODING_AGENT_SESSION_DIR puts them. +func TestPiSessionDir(t *testing.T) { + _, pi := setupMore(t) + flat := filepath.Join(filepath.Dir(pi), "flat") + os.MkdirAll(flat, 0o755) + from := filepath.Join(pi, "sessions", "--work-pi--") + name := "2026-09-24T08-00-00-000Z_" + piFirst + ".jsonl" + if err := os.Rename(filepath.Join(from, name), filepath.Join(flat, name)); err != nil { + t.Fatal(err) + } + os.WriteFile(filepath.Join(pi, "settings.json"), []byte("{\n // where the sessions go\n \"sessionDir\": "+jsonString(flat)+",\n}\n"), 0o644) + find(t, List(0), "pi", piFirst) + + t.Setenv("PI_CODING_AGENT_SESSION_DIR", filepath.Join(filepath.Dir(pi), "none")) + Reset() + for _, s := range List(0) { + if s.ID == piFirst { + t.Fatal("$PI_CODING_AGENT_SESSION_DIR comes before the setting") + } + } +} + +func jsonString(s string) string { + b, _ := json.Marshal(s) + return string(b) +} + +func TestDirs(t *testing.T) { + data, pi := setupMore(t) + d := Dirs() + if len(d) != 4 || d[2] != filepath.Join(data, "opencode") || d[3] != pi { + t.Fatalf("dirs %v", d) + } + os.RemoveAll(pi) + if d := Dirs(); len(d) != 3 { + t.Fatalf("a Pi folder that isn't there listed: %v", d) + } +} diff --git a/internal/sessions/pi.go b/internal/sessions/pi.go new file mode 100644 index 000000000..93b8a7401 --- /dev/null +++ b/internal/sessions/pi.go @@ -0,0 +1,201 @@ +package sessions + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "strings" + + "github.com/tidwall/jsonc" +) + +// Pi writes a file per session,