sessions: read Cursor editor history and Cursor/OpenCode conversations (#1743)

Discover editor project transcripts and cursorDiskKV histories without modifying the source. Share one SQLite/WAL snapshot across a scan, refresh metadata changes, deduplicate CLI histories, and reject deletion of read-only sessions.

Count message-only sessions and expose an all-dates action when a filter hides existing history. Read Cursor CLI text, reasoning and tool parts, and OpenCode v1/v2 transcripts through the existing transcript API.
This commit is contained in:
liubing
2026-10-13 06:43:50 +08:00
committed by yetone
parent 296b63f8d6
commit 1cd8140047
10 changed files with 505 additions and 4 deletions
+20
View File
@@ -257,6 +257,26 @@ waits for `show` to accept navigation before creating its draft.
## Verification
The session readers include Cursor CLI chat stores, Cursor editor project
transcripts and older editor `cursorDiskKV` conversations. CLI stores win
when the same session ID has a project transcript. Editor conversations are
read only, including at the delete API, and cannot be resumed by cursor-agent.
Project transcripts contain no message timestamps or billing data; their
existing file modification time supplies the activity date, and tokens and
cost are not inferred. Database bubbles retain their own timestamps.
The editor database is opened as one read-only snapshot per listing, shared
by its chats and removed when the listing ends. Metadata changes invalidate
the cached summary even if the project transcript has not changed. See
[`cursor_editor.go`](../../internal/sessions/cursor_editor.go),
`TestCursorEditorTranscript` and `TestCursorEditorLiveDatabaseAndMetadataRefresh`
in [`cursor_editor_test.go`](../../internal/sessions/cursor_editor_test.go).
Messages without tokens or an active-time estimate still count as sessions
in the overview. Cursor and OpenCode conversations can be opened through
the existing transcript API, including CLI reasoning and tool calls. When the selected date range is empty but
matching history exists, Usage offers **All sessions**, preserving the agent,
model, folder and search filters. See `sessions-empty-range.test.cjs`.
```sh
go test -tags nogui ./internal/gui
go test -run TestWebView2 ./internal/gui # on Windows: Wails' runtime lookup, missing and present
+13
View File
@@ -19287,6 +19287,19 @@ function renderSessions() {
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, 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.")));
if (from && all.some((s) => byAgent(s) && byFolder(s) &&
(!sessModel || s.models.some((m) => m.model === sessModel)) &&
(!q || [s.title, s.cwd, s.id, s.name, ...s.models.map((m) => m.model)].some((x) => (x || "").toLowerCase().includes(q))))) {
stats.firstChild.textContent = t("No sessions in this range");
const history = el("button", "text sess-show-history", t("All sessions"));
history.onclick = () => {
sessRange = "all";
try { localStorage.setItem("magpie.sessRange", sessRange); } catch {}
sessStats = null;
loadSessions().catch((e) => status(e.message, "err"));
};
stats.append(history);
}
box.hidden = true;
chart.hidden = true;
grid.hidden = true;
+4 -1
View File
@@ -269,7 +269,7 @@ func cursorFiles() []file {
}
out = append(out, f)
}
return out
return append(out, cursorEditorFiles(out)...)
}
// pbFields reads a protobuf message's fields of one number that are bytes
@@ -425,6 +425,9 @@ func cursorTyped(parts []cursorPart) (typed, other string) {
// parseCursor reads a chat's store whole.
func parseCursor(f file) *state {
if f.readOnly {
return parseCursorEditor(f)
}
s := &state{Size: f.size, Mod: f.mod.UnixNano()}
dir := filepath.Dir(f.path)
last := f.mod
+324
View File
@@ -0,0 +1,324 @@
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 == "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
}
+3
View File
@@ -225,6 +225,9 @@ func Delete(agent, id string) (Trashed, error) {
if len(fs) == 0 {
return Trashed{}, errors.New("no such session")
}
if s.ReadOnly {
return Trashed{}, errors.New("this session is read only")
}
paths := sessionPaths(agent, id, fs)
if len(paths) == 0 {
// a stopped distro's listing, of files since gone
+9 -1
View File
@@ -172,6 +172,9 @@ func ocRoots(out []file, parent map[string]string) []file {
// they are done (closeDBs).
var dbs = map[string]*sql.DB{}
// Snapshot readers also remove their temporary database when a scan ends.
var dbCleanup = map[string]func(){}
func openDB(path string) *sql.DB {
if db := dbs[path]; db != nil {
return db
@@ -187,7 +190,12 @@ func openDB(path string) *sql.DB {
func closeDBs() {
for p, db := range dbs {
db.Close()
if done := dbCleanup[p]; done != nil {
done()
delete(dbCleanup, p)
} else {
db.Close()
}
delete(dbs, p)
}
}
+4 -1
View File
@@ -351,6 +351,7 @@ type file struct {
alma *almaStore
rev string
readOnly bool
editor *cursorEditorMeta
// wsl: the WSL distro whose home it is in; cold: that distro isn't
// running, and the file, as last listed, is not to be opened (that
// would start the distro)
@@ -453,6 +454,8 @@ func Dirs() []string {
{OmpDir(), filepath.Join(OmpDir(), "sessions")},
{FactoryDir(), filepath.Join(FactoryDir(), "sessions")},
{CursorDir(), filepath.Join(CursorDir(), "chats")},
{cursorDataDir(), filepath.Join(cursorDataDir(), "projects")},
{filepath.Dir(cursorEditorDB()), cursorEditorDB()},
{AlmaDir(), almaDB()},
{MiniMaxDir(), minimaxSessions()},
} {
@@ -679,7 +682,7 @@ func refresh(want, all []file) {
if f.cold {
continue // in a stopped WSL distro: what was read of it stands
}
if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.hermes == nil || f.hermes.revision == "" || s.DBRevision != f.hermes.revision)) || (f.agent == "alma" && s.DBRevision != f.rev) {
if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.hermes == nil || f.hermes.revision == "" || s.DBRevision != f.hermes.revision)) || ((f.agent == "alma" || f.agent == "cursor") && s.DBRevision != f.rev) {
todo = append(todo, f)
}
}
+4
View File
@@ -210,6 +210,10 @@ func statsAt(days int, now time.Time) Stats {
}
sh.prompts += d.Prompts
sh.replies += d.Replies
if d.Prompts+d.Replies > 0 {
sh.dates[date] = true
dates[date] = true
}
pd.messages += d.Prompts + d.Replies
for name, n := range d.Tools {
sh.tools[name] += n
+5 -1
View File
@@ -30,7 +30,7 @@ var ErrNoTranscript = errors.New("this agent's conversations can't be shown")
// transcript.
func HasTranscript(agent string) bool {
switch agent {
case "claude", "qoder", "qoder-cn", "codex", "pi", "omp":
case "claude", "qoder", "qoder-cn", "codex", "pi", "omp", "cursor", "opencode":
return true
}
return false
@@ -72,6 +72,10 @@ func readTranscript(s Session, add func(bool, Part) bool) error {
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", "omp":
+119
View File
@@ -0,0 +1,119 @@
package sessions
import (
"encoding/json"
"sort"
)
// openCodeTranscript reads the conversation in message order from the same
// store the listing chose, including while a v1 to v2 migration is underway.
func openCodeTranscript(s Session, add func(bool, Part) bool) error {
dbReadMu.Lock()
defer dbReadMu.Unlock()
defer closeDBs()
for _, f := range openCodeFiles() {
if f.sid != s.ID {
continue
}
if v, ok := f.oc.(ocV2DB); ok {
rows, err := v.db.Query("SELECT type,data FROM session_message WHERE session_id=? AND type IN ('user','assistant') ORDER BY seq", s.ID)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var role string
var raw []byte
if err := rows.Scan(&role, &raw); err != nil {
return err
}
var m struct {
Text string `json:"text"`
Content []json.RawMessage `json:"content"`
}
if err := json.Unmarshal(raw, &m); err != nil {
return err
}
if role == "user" {
if !add(true, textPart(role, m.Text)) {
return nil
}
continue
}
for _, p := range m.Content {
if !openCodeTranscriptPart(role, p, add) {
return nil
}
}
}
return rows.Err()
}
var messages []ocMessage
for _, b := range f.oc.messages(f.sid) {
var m ocMessage
if json.Unmarshal(b, &m) == nil {
messages = append(messages, m)
}
}
sort.SliceStable(messages, func(i, j int) bool {
if messages[i].Time.Created != messages[j].Time.Created {
return messages[i].Time.Created < messages[j].Time.Created
}
return messages[i].ID < messages[j].ID
})
for _, m := range messages {
for _, p := range f.oc.parts(m.ID) {
if !openCodeTranscriptPart(m.Role, p, add) {
return nil
}
}
}
return nil
}
return ErrNoTranscript
}
func openCodeTranscriptPart(role string, raw []byte, add func(bool, Part) bool) bool {
var p struct {
Type string `json:"type"`
Text string `json:"text"`
Name string `json:"name"`
Tool string `json:"tool"`
Synthetic bool `json:"synthetic"`
Ignored bool `json:"ignored"`
State struct {
Input json.RawMessage `json:"input"`
Output string `json:"output"`
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
} `json:"state"`
}
if json.Unmarshal(raw, &p) != nil || p.Synthetic || p.Ignored {
return true
}
switch p.Type {
case "text":
return add(role == "user", textPart(role, p.Text))
case "reasoning":
return add(false, Part{Role: role, Kind: "thinking", Text: p.Text})
case "tool":
name := p.Name
if name == "" {
name = p.Tool
}
if !add(false, Part{Role: role, Kind: "tool_use", Name: name, Text: string(p.State.Input)}) {
return false
}
if p.State.Output != "" && !add(false, Part{Role: "tool", Kind: "tool_result", Name: name, Text: p.State.Output}) {
return false
}
for _, r := range p.State.Content {
if r.Type == "text" && !add(false, Part{Role: "tool", Kind: "tool_result", Name: name, Text: r.Text}) {
return false
}
}
}
return true
}