Files
magpie/internal/sessions/transcript.go
T
yetone af8f3a9399 sessions: a new install reads no agent's session history until the user allows it (RustCats on X)
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.
2026-10-29 23:56:05 +08:00

275 lines
8.2 KiB
Go

package sessions
// A session's whole conversation, read from the agent's own file when it is
// asked for: what was said, in order, by the user, the model and its tools.
// The file is only read; magpie keeps no copy.
import (
"bytes"
"encoding/json"
"errors"
"math"
"github.com/tidwall/gjson"
)
// Transcript is what was said in a session, in the order it was said.
type Transcript struct {
Parts []Part `json:"parts"`
Cut bool `json:"cut,omitempty"` // there was more than is kept here
Source string `json:"source,omitempty"`
Captured int `json:"captured,omitempty"`
}
// transcriptMax is the characters of all of a transcript's parts.
const transcriptMax = 400_000
// ErrNoTranscript is a session whose conversation magpie can't read: an
// agent that keeps it in a database, or in a form not read here.
var ErrNoTranscript = errors.New("this agent's conversations can't be shown")
// HasTranscript says whether an agent's sessions can be read as a
// transcript.
func HasTranscript(agent string) bool {
switch agent {
case "claude", "qoder", "qoder-cn", "codex", "pi", "raft", "omp", "cursor", "opencode", "kimi", "agy":
return true
}
return false
}
// readable says whether a session's conversation can be read: its agent's
// can, and its file is the one they are read from (an agy conversation
// listed from its row alone has none).
func readable(s Session) bool {
return HasTranscript(s.Agent) && !(s.Agent == "agy" && agyRowOnly(s.Path))
}
func (t *Transcript) add(_ bool, p Part) bool {
size := 0
for _, x := range t.Parts {
size += len(x.Text)
}
if size >= transcriptMax {
t.Cut = true
return false
}
if p, ok := keep(p); ok {
t.Parts = append(t.Parts, p)
}
return true
}
// TranscriptOf reads a session's conversation from its (main) file.
func TranscriptOf(s Session) (Transcript, error) {
if !Reads(s.Agent) {
return Transcript{Parts: []Part{}}, ErrNotRead
}
out := Transcript{Parts: []Part{}}
if !HasTranscript(s.Agent) || s.Path == "" {
return out, ErrNoTranscript
}
return out, readTranscript(s, out.add)
}
// readTranscript tells add each part of a session's conversation, in order,
// as its agent's file has it.
func readTranscript(s Session, add func(bool, Part) bool) error {
return readTranscriptOf(s, nil, add)
}
// readTranscriptOf is readTranscript decoding only the lines keep says yes
// to, where a line stands alone (Claude's, Codex's, Kimi's); Pi's lines are a tree,
// read whole.
func readTranscriptOf(s Session, keep func([]byte) bool, add func(bool, Part) bool) error {
whole := Call{Agent: s.Agent, File: s.Path, To: math.MaxInt64}
switch s.Agent {
case "opencode":
return openCodeTranscript(s, add)
case "cursor":
return cursorTranscript(s.Path, add)
case "codex":
return codexContentOf(whole, keep, add)
case "pi", "raft", "omp":
return piTranscript(s.Path, add)
case "kimi":
return kimiTranscript(s.Path, keep, add)
case "agy":
return agyTranscript(s.Path, keep, add)
default:
if s.BranchOf != "" && keep == nil {
return branchTranscript(s, add)
}
return claudeContentOf(whole, keep, add)
}
}
// branchTranscript reads a branch (ccFamily) as its conversation went: the
// session it is a branch of from its start up to the last message the two
// share, then what the branch said on its own. A fork made after a
// compaction holds only the summary and what follows it, and opened on
// that summary and one turn (Neo, #feedback). A search reads the branch's
// own file only, so a hit in the shared part is the head's, not each
// branch's again.
func branchTranscript(s Session, add func(bool, Part) bool) error {
ends := map[string]int64{}
if _, err := scanThin(s.BranchOf, 0, nil, thinClaude, func(b []byte, _, end int64) bool {
if u := ccMessageUUID(b); u != "" {
ends[u] = end
}
return true
}); err != nil {
// the head unread: the branch alone, as before it was known to be one
return claudeContentOf(Call{Agent: s.Agent, File: s.Path, To: math.MaxInt64}, nil, add)
}
fork := int64(-1)
if _, err := scanThin(s.Path, 0, nil, thinClaude, func(b []byte, _, _ int64) bool {
if e, ok := ends[ccMessageUUID(b)]; ok && e > fork {
fork = e
}
return true
}); err != nil {
return err
}
if fork < 0 {
return claudeContentOf(Call{Agent: s.Agent, File: s.Path, To: math.MaxInt64}, nil, add)
}
more := true
if err := claudeContentOf(Call{Agent: s.Agent, File: s.BranchOf, To: fork}, nil, func(in bool, p Part) bool {
more = add(in, p) && more
return more
}); err != nil || !more {
return err
}
return claudeContentOf(Call{Agent: s.Agent, File: s.Path, To: math.MaxInt64}, func(b []byte) bool {
_, shared := ends[ccMessageUUID(b)]
return !shared
}, add)
}
// ccMessageUUID is the uuid of a Claude-format user or assistant line, ""
// for any other line.
func ccMessageUUID(b []byte) string {
if !bytes.Contains(b, ccUser) && !bytes.Contains(b, ccAssistant) {
return ""
}
r := gjson.GetManyBytes(b, "type", "uuid")
if t := r[0].String(); (t == "user" || t == "assistant") && r[1].Type == gjson.String {
return r[1].String()
}
return ""
}
// piEntry is a line of a Pi (or oh-my-pi) session: an entry of its tree.
type piEntry struct {
Type string `json:"type"`
ID string `json:"id"`
ParentID string `json:"parentId"`
Summary string `json:"summary"` // compaction, branch_summary
Message *struct {
Role string `json:"role"`
ToolName string `json:"toolName"`
Model string `json:"model"` // an assistant's: the one it was answered by (#2253)
Content json.RawMessage `json:"content"`
} `json:"message"`
}
var piMessage = []byte(`"type":"message"`)
// piTranscript reads the branch the session is on: a Pi session is a tree,
// each entry naming its parent, and the last entry written is where it
// stands (an earlier branch, left by /tree or a retry, isn't said again).
func piTranscript(path string, add func(bool, Part) bool) error {
byID := map[string]piEntry{}
last := ""
_, err := scanAt(path, 0, nil, func(b []byte, _, _ int64) bool {
var e piEntry
if json.Unmarshal(b, &e) != nil || e.ID == "" || e.Type == "session" || e.Type == "title" {
return true
}
if !bytes.Contains(b, piMessage) && e.Type != "compaction" && e.Type != "branch_summary" {
// keep the tree whole without holding what isn't shown
e = piEntry{Type: e.Type, ID: e.ID, ParentID: e.ParentID}
}
byID[e.ID], last = e, e.ID
return true
})
if err != nil {
return err
}
var branch []piEntry
for id, n := last, 0; id != "" && n <= len(byID); n++ {
e, ok := byID[id]
if !ok {
break
}
branch = append(branch, e)
id = e.ParentID
}
for i := len(branch) - 1; i >= 0; i-- {
for _, p := range piParts(branch[i]) {
if p.Role == "assistant" && branch[i].Message != nil {
p.Model = branch[i].Message.Model
}
if !add(p.Role != "assistant", p) {
return nil
}
}
}
return nil
}
// piParts are what an entry said.
func piParts(e piEntry) []Part {
switch e.Type {
case "compaction", "branch_summary":
return []Part{{Role: "user", Kind: "context", Text: e.Summary}}
case "message":
default:
return nil
}
if e.Message == nil {
return nil
}
m := e.Message
var role string
switch m.Role {
case "user":
role = "user"
case "assistant":
role = "assistant"
case "toolResult":
return []Part{{Role: "tool", Kind: "tool_result", Name: m.ToolName, Text: resultText(m.Content)}}
default:
return nil
}
var s string
if json.Unmarshal(m.Content, &s) == nil {
return []Part{textPart(role, s)}
}
var blocks []struct {
Type string `json:"type"`
Text string `json:"text"`
Thinking string `json:"thinking"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
if json.Unmarshal(m.Content, &blocks) != nil {
return nil
}
var parts []Part
for _, b := range blocks {
switch b.Type {
case "text":
parts = append(parts, textPart(role, b.Text))
case "thinking":
parts = append(parts, Part{Role: role, Kind: "thinking", Text: b.Thinking})
case "toolCall":
parts = append(parts, Part{Role: role, Kind: "tool_use", Name: b.Name, Text: pretty(b.Arguments)})
case "image":
parts = append(parts, Part{Role: role, Kind: "image", Text: "[image]"})
}
}
return parts
}