Files
magpie/internal/sessions/cursor_editor.go
T
yetoneandliubing 9935119f1d sessions: search finds Cursor and OpenCode sessions read from their stores, and a Cursor chat's system prompt isn't shown as said (#1743)
Follow-up to liubing's #1743 patch, which put cursor and opencode in
HasTranscript. That moved their search from magpie's recorded
transcript to SearchSession, whose byte prefilter (mayHold) reads
s.Path. For these agents s.Path isn't the conversation:
- OpenCode's JSON storage: the session info file, without messages,
  so every word missed;
- OpenCode's and Cursor's SQLite stores: the newest pages are in the
  -wal, so a live chat's latest turns missed.
linesFile now skips the prefilter for them (a Cursor .jsonl still
gets it).

cursorTranscript also handed the CLI store's system message ("You
are a coding agent.") to the transcript as a said part; system
messages are skipped, as the listing already does.

The patch's tests commit left TestSearchSessionWithoutATranscript
red (it used cursor as the agent without a transcript; now gemini).
sessions-empty-range.test.cjs runs in every language, de at 420px.

Run: go test -tags nogui -count=1 ./internal/sessions/ ok, and -race
ok; sessions-empty-range 10/10 (Chromium+WebKit, en zh zh-TW ja de);
sessions-today/overview/toolbar/search/manage/calendar-fill/paging
GUI tests pass.
Broken by hand: prefilter always on -> TestSearchOpenCodeFiles and
TestSearchCursorLiveChat red; system skip removed ->
TestSearchCursorLiveChat red. Also broke the patch itself: editor
files not appended, readOnly Delete guard, stats message dates, CLI
dedupe, HasTranscript entries, parseCursor readOnly dispatch, and
the "All sessions" button (via MAGPIE_TEST_APP_JS); each went red.

Co-authored-by: liubing <lb0806@foxmail.com>
2026-10-13 06:43:50 +08:00

329 lines
8.9 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 := openCursorStore(path)
if err != nil {
return nil
}
db.SetMaxOpenConns(4)
dbs[path], dbCleanup[path] = db, done
return db
}
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 {
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("SELECT value FROM cursorDiskKV WHERE key LIKE 'composerData:%'")
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, sid: id, path: path, main: true, readOnly: true, editor: metas[id]}
if !stat(&f) || !cursorEditorHasMessages(path) {
continue
}
if f.editor != nil {
f.rev = f.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, sid: id, path: p + "#" + id, main: true, readOnly: true, editor: m, rev: m.revision, size: int64(len(b)), mod: ms(max(m.Created, m.Updated))})
}
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.sid, Size: f.size, Mod: f.mod.UnixNano(), DBRevision: f.rev}
if m := f.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.editor != nil && f.editor.db != nil {
_ = editorMessages(f.editor.db, f.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 := openCursorStore(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
}