Files
magpie/internal/sessions/cursor_editor.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

367 lines
11 KiB
Go

package sessions
import (
"database/sql"
"encoding/json"
"os"
"path/filepath"
"strings"
"time"
)
// Cursor's editor stores older chats in cursorDiskKV, and newer chats as
// project transcripts. These are read only: cursor-agent cannot resume them.
type cursorEditorMeta struct {
db *sql.DB
revision string
ID string `json:"composerId"`
Name string `json:"name"`
Created int64 `json:"createdAt"`
Updated int64 `json:"lastUpdatedAt"`
Headers []struct {
ID string `json:"bubbleId"`
} `json:"fullConversationHeadersOnly"`
Workspace struct {
URI struct {
Path string `json:"fsPath"`
} `json:"uri"`
} `json:"workspaceIdentifier"`
}
// Share one read-only snapshot across all editor chats in a listing. Opening
// the WAL-backed global database separately for every chat copies it N times.
func openCursorEditorDB(path string) *sql.DB {
if db := dbs[path]; db != nil {
return db
}
db, done, err := openCursorEditorStore(path)
if err != nil {
return nil
}
db.SetMaxOpenConns(4)
dbs[path], dbCleanup[path] = db, done
return db
}
// openCursorEditorStore opens the editor's state.vscdb to read it. While
// Cursor runs, its own processes share the store as readers of its -wal
// through its -shm, and magpie reads it as one more, in place: a copy of a
// store of several GB was written to the temp folder each time Cursor had
// written since the last, ~10.6 GB every few minutes on Windows, where no
// clone makes a copy free (Echo-Huang0010, #1988). Nothing magpie shows is
// read from the store's file times, so a reader's mark in -shm moves no
// chat; each chat carries its own (lastUpdatedAt). With no -shm beside a
// live -wal there is no Cursor running to share it with, and it is opened
// as a chat's store is (openCursorStore).
func openCursorEditorStore(path string) (*sql.DB, func(), error) {
// copies an older magpie left, which no copy made here would sweep
cursorSnaps.sweep.Do(sweepCursorSnaps)
wal, werr := os.Stat(path + "-wal")
_, serr := os.Stat(path + "-shm")
if !cursorReadInPlace || werr != nil || wal.Size() == 0 || serr != nil {
return openCursorStore(path)
}
db, err := openSQLite(path, "mode=ro&_pragma=busy_timeout(3000)")
if err != nil {
return openCursorStore(path)
}
cursorInPlace.Add(1)
return db, func() { db.Close() }, nil
}
// cursorComposersQuery lists the editor's chats by a range on the key's
// index. LIKE is case-insensitive, so SQLite can't use the index for it and
// reads the whole table: every bubble and checkpoint, often several GB. A
// live store is read from a fresh copy whenever Cursor has written, and a
// fresh copy (an APFS clone on macOS) isn't in the page cache, so every
// listing read the whole store from disk again and Sessions never finished
// loading (#1988). ';' is the character after ':'.
const cursorComposersQuery = "SELECT value FROM cursorDiskKV WHERE key >= 'composerData:' AND key < 'composerData;'"
func cursorEditorDB() string {
dir, err := os.UserConfigDir()
if err != nil {
return ""
}
return filepath.Join(dir, "Cursor", "User", "globalStorage", "state.vscdb")
}
func cursorEditorFiles(cli []file) []file {
if !Reads("cursor") {
return nil
}
seen := map[string]bool{}
for _, f := range cli {
seen[strings.TrimPrefix(f.key, "cursor:")] = true
seen[filepath.Base(filepath.Dir(f.path))] = true
}
metas := map[string]*cursorEditorMeta{}
var out []file
p := cursorEditorDB()
if fileExists(p) {
if db := openCursorEditorDB(p); db != nil {
rows, err := db.Query(cursorComposersQuery)
if err == nil {
for rows.Next() {
var b []byte
var m cursorEditorMeta
if rows.Scan(&b) != nil || json.Unmarshal(b, &m) != nil || !safeID.MatchString(m.ID) {
continue
}
m.db, m.revision = db, hashHead(string(b))
metas[m.ID] = &m
}
rows.Close()
}
}
}
root := filepath.Join(cursorDataDir(), "projects")
// Only top-level conversations; subagents are not additional user chats.
for _, pattern := range []string{"*/agent-transcripts/*/*.jsonl", "*/agent-transcripts/*.jsonl"} {
paths, _ := filepath.Glob(filepath.Join(root, pattern))
for _, path := range paths {
id := strings.TrimSuffix(filepath.Base(path), ".jsonl")
if !safeID.MatchString(id) || seen[id] {
continue
}
f := file{agent: "cursor", key: "cursor:" + id, path: path, main: true, readOnly: true, more: &fileMore{sid: id, editor: metas[id]}}
if !stat(&f) || !cursorEditorHasMessages(path) {
continue
}
if f.m().editor != nil {
f.w().rev = f.m().editor.revision
}
out = append(out, f)
seen[id] = true
}
}
for id, m := range metas {
if seen[id] || len(m.Headers) == 0 {
continue
}
b, _ := json.Marshal(m)
out = append(out, file{agent: "cursor", key: "cursor:" + id, path: p + "#" + id, main: true, readOnly: true, size: int64(len(b)), mod: ms(max(m.Created, m.Updated)), more: &fileMore{sid: id, editor: m, rev: m.revision}})
}
return out
}
// Failed exports are not conversations, including in the management
// page's counts, which are computed before full parsing.
func cursorEditorHasMessages(path string) bool {
found := false
_ = readCursorEditor(path, func(role, text string, _ time.Time) bool {
if role == "user" {
text, _ = cursorTyped([]cursorPart{{Type: "text", Text: text}})
}
found = (role == "user" || role == "assistant") && strings.TrimSpace(text) != ""
return !found
})
return found
}
func parseCursorEditor(f file) *state {
s := &state{ID: f.m().sid, Size: f.size, Mod: f.mod.UnixNano(), DBRevision: f.m().rev}
if m := f.m().editor; m != nil {
s.Named = cursorTitle(m.Name)
s.Cwd = m.Workspace.URI.Path
s.saw(ms(m.Created), false)
s.saw(ms(m.Updated), false)
}
// Project transcripts have no timestamps: their existing modification
// time is the only activity date available, never the time of this scan.
s.saw(f.mod, false)
message := func(role, text string, at time.Time) bool {
if at.IsZero() {
at = f.mod
}
s.saw(at, false)
if role == "user" {
typed, _ := cursorTyped([]cursorPart{{Type: "text", Text: text}})
if typed != "" {
s.day(dateOf(at)).Prompts++
if s.Title == "" {
s.Title = title(typed)
}
}
} else if role == "assistant" && strings.TrimSpace(text) != "" {
s.day(dateOf(at)).Replies++
}
return true
}
if _, _, ok := cursorEditorDatabasePath(f.path); ok && f.m().editor != nil && f.m().editor.db != nil {
_ = editorMessages(f.m().editor.db, f.m().sid, message)
} else {
_ = readCursorEditor(f.path, message)
}
if len(s.Days) == 0 {
// A failed transcript export may contain only an error record,
// while the editor metadata still has a name for the empty chat.
s.Named = ""
}
return s
}
func editorMessages(db *sql.DB, id string, add func(string, string, time.Time) bool) error {
var raw []byte
if err := db.QueryRow("SELECT value FROM cursorDiskKV WHERE key = ?", "composerData:"+id).Scan(&raw); err != nil {
return err
}
var meta cursorEditorMeta
if err := json.Unmarshal(raw, &meta); err != nil {
return err
}
for _, h := range meta.Headers {
if err := db.QueryRow("SELECT value FROM cursorDiskKV WHERE key = ?", "bubbleId:"+id+":"+h.ID).Scan(&raw); err != nil {
if err == sql.ErrNoRows {
continue
}
return err
}
var b struct {
Type int `json:"type"`
Text string `json:"text"`
Created string `json:"createdAt"`
}
if json.Unmarshal(raw, &b) != nil {
continue
}
role := ""
if b.Type == 1 {
role = "user"
} else if b.Type == 2 {
role = "assistant"
}
at, _ := time.Parse(time.RFC3339Nano, b.Created)
if at.IsZero() {
at = ms(max(meta.Created, meta.Updated))
}
if role != "" && !add(role, b.Text, at) {
break
}
}
return nil
}
func readCursorEditor(path string, add func(string, string, time.Time) bool) error {
if dbPath, id, ok := cursorEditorDatabasePath(path); ok {
db, done, err := openCursorEditorStore(dbPath)
if err != nil {
return err
}
defer done()
return editorMessages(db, id, add)
}
_, err := scanAt(path, 0, nil, func(b []byte, _, _ int64) bool {
var m struct {
Role string `json:"role"`
Message struct {
Content json.RawMessage `json:"content"`
} `json:"message"`
}
if json.Unmarshal(b, &m) != nil {
return true
}
var texts []string
for _, p := range cursorParts(m.Message.Content) {
if p.Type == "text" {
texts = append(texts, p.Text)
}
}
return add(m.Role, strings.Join(texts, ""), time.Time{})
})
return err
}
func cursorEditorDatabasePath(path string) (string, string, bool) {
i := strings.LastIndex(path, "#")
if i < 0 || !strings.HasSuffix(path[:i], ".vscdb") || !safeID.MatchString(path[i+1:]) {
return "", "", false
}
return path[:i], path[i+1:], true
}
func cursorTranscript(path string, add func(bool, Part) bool) error {
emit := func(role, text string, _ time.Time) bool {
if role == "user" {
text, _ = cursorTyped([]cursorPart{{Type: "text", Text: text}})
}
if role != "user" && role != "assistant" {
return true
}
return add(role == "user", textPart(role, text))
}
_, _, editorDB := cursorEditorDatabasePath(path)
if strings.HasSuffix(path, ".jsonl") || editorDB {
return readCursorEditor(path, emit)
}
db, done, err := openCursorStore(path)
if err != nil {
return err
}
defer done()
meta, ok := readCursorMeta(db)
if !ok {
return ErrNoTranscript
}
for _, m := range cursorMessages(db, meta.Root) {
if m.Role == "system" {
// the agent's own prompt, not said in the conversation
continue
}
if m.Role == "user" {
typed, _ := cursorTyped(cursorParts(m.Content))
if !emit(m.Role, typed, time.Time{}) {
return nil
}
continue
}
for _, p := range cursorTranscriptParts(m) {
if !add(false, p) {
return nil
}
}
}
return nil
}
func cursorTranscriptParts(m cursorMessage) []Part {
var text string
if json.Unmarshal(m.Content, &text) == nil {
return []Part{textPart(m.Role, text)}
}
var blocks []struct {
Type string `json:"type"`
Text string `json:"text"`
ToolName string `json:"toolName"`
Input json.RawMessage `json:"input"`
Args json.RawMessage `json:"args"`
Result json.RawMessage `json:"result"`
Output json.RawMessage `json:"output"`
}
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(m.Role, b.Text))
case "reasoning":
parts = append(parts, Part{Role: m.Role, Kind: "thinking", Text: b.Text})
case "tool-call":
args := b.Input
if len(args) == 0 {
args = b.Args
}
parts = append(parts, Part{Role: m.Role, Kind: "tool_use", Name: b.ToolName, Text: pretty(args)})
case "tool-result":
result := b.Result
if len(result) == 0 {
result = b.Output
}
parts = append(parts, Part{Role: "tool", Kind: "tool_result", Name: b.ToolName, Text: resultText(result)})
}
}
return parts
}