sessions: a PI-Desktop chat goes by the title PI-Desktop gave it, not its id (#1967)

PI-Desktop (vastsa/PI-Desktop) sends its chats through magpie with
X-Magpie-Session set to its own session id. Those are gateway sessions
with no file magpie reads, so Sessions and the context page listed them
by id. PI-Desktop keeps the name only in its index database, pi.sqlite's
sessions table (id, title, deleted_at).

PIDesktopTitles reads that table from $PI_DESKTOP_DATA_DIR or
~/.pi-desktop. It opens the database only through openCursorStore:
immutable when there is no write-ahead log, or from a temp copy when
there is one (a running PI-Desktop keeps one). It is re-read when the
database or its log changes, at most once a second. Deleted and untitled
rows are skipped. A database that can't be read leaves the names last
read standing. MergeExternal, MergeExternalStats and the GUI's context
page use it for sessions attributed to pi-desktop (aec6908c6) or pi,
which PI-Desktop was counted as before.

Run:
- TestPIDesktopTitlesNameGatewaySessions builds pi.sqlite with
  PI-Desktop's schema in WAL mode with checkpoints off. It checks that
  pi and pi-desktop sessions get the title, a claude session with the
  same id doesn't, deleted and untitled rows don't, a rename shows up on
  the next read, and the folder's files are unchanged.
- Broken by hand: isPIDesktop returning false made it red (titles
  stayed the id), and so did dropping `deleted_at IS NULL` (the deleted
  row got its title).
- go test -tags nogui ./internal/sessions/ ./internal/gui/ passes.
- gofmt -l is clean. go vet passes on darwin, linux (nogui) and windows.

Not tried: a real PI-Desktop install. The schema is from its source. A
data folder the user picked in PI-Desktop's own settings, other than
$PI_DESKTOP_DATA_DIR, isn't followed.
This commit is contained in:
yetone
2026-10-13 17:10:25 +08:00
parent 5617281f55
commit cdb7b5ff7e
4 changed files with 247 additions and 5 deletions
+13 -1
View File
@@ -251,7 +251,7 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
}
// the sessions, the latest first
slices.SortFunc(order, func(a, b string) int { return sess[b].Last.Compare(sess[a].Last) })
var codexIDs, desktopIDs []string
var codexIDs, desktopIDs, piIDs []string
for _, sk := range order {
s := sess[sk]
if acc := agents[s.Agent]; acc != nil && s.Requests > 1 {
@@ -267,6 +267,8 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
codexIDs = append(codexIDs, s.Key)
case "claude-desktop":
desktopIDs = append(desktopIDs, s.Key)
case "pi-desktop", "pi":
piIDs = append(piIDs, s.Key)
}
}
}
@@ -288,6 +290,16 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
}
}
}
// PI-Desktop's by the name it keeps in pi.sqlite, which no file of the
// chat has (#1967); Pi's own sessions find none there and go on below
if len(piIDs) > 0 {
titles := sessions.PIDesktopTitles(piIDs)
for i := range out.Sessions {
if a := out.Sessions[i].Agent; (a == "pi-desktop" || a == "pi") && out.Sessions[i].Title == "" {
out.Sessions[i].Title = titles[out.Sessions[i].Key]
}
}
}
// every other agent's sessions go by the name the Sessions page shows
untitled := map[string]int{}
for i, s := range out.Sessions {
+15 -4
View File
@@ -55,20 +55,31 @@ func MergeExternal(native []Session, external []ExternalSession) []Session {
return out
}
// desktopExternalTitles are the names Desktop saved for the Claude Desktop
// sessions among external (DesktopTitles), by Agent|ID. They come before
// the gateway's recorded first prompt.
// desktopExternalTitles are the names an app saved for its sessions among
// external, by Agent|ID: Claude Desktop's (DesktopTitles), PI-Desktop's
// (PIDesktopTitles, #1967). They come before the gateway's recorded first
// prompt.
func desktopExternalTitles(external []ExternalSession) map[string]string {
var ids []string
var ids, pi []string
for _, e := range external {
if e.Agent == "claude-desktop" {
ids = append(ids, e.ID)
} else if isPIDesktop(e.Agent) {
pi = append(pi, e.ID)
}
}
out := map[string]string{}
for id, name := range DesktopTitles(ids) {
out["claude-desktop|"+id] = name
}
if len(pi) > 0 {
names := PIDesktopTitles(pi)
for _, e := range external {
if name := names[e.ID]; name != "" && isPIDesktop(e.Agent) {
out[e.Agent+"|"+e.ID] = name
}
}
}
return out
}
+109
View File
@@ -0,0 +1,109 @@
package sessions
import (
"errors"
"io/fs"
"os"
"path/filepath"
"strconv"
"sync"
"time"
)
// PI-Desktop (vastsa/PI-Desktop) keeps its chats as its own jsonl, not
// Pi's, and their names only in its index database: pi.sqlite's sessions
// table (id, title, deleted_at; its crates/host-core/src/db/schema.rs). A
// chat it sends through magpie with X-Magpie-Session is a gateway session
// with no file magpie reads, so it went by its id (#1967, dgmico); these
// are the names it goes by instead.
// PIDesktopDir is where PI-Desktop keeps its data: $PI_DESKTOP_DATA_DIR,
// else ~/.pi-desktop (a packaged install's, its 04-data-storage.md).
func PIDesktopDir() string {
if d := os.Getenv("PI_DESKTOP_DATA_DIR"); d != "" {
return d
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".pi-desktop")
}
var piDesktopTitles struct {
sync.Mutex
at time.Time
stamp string // pi.sqlite's and its log's size and time when read
names map[string]string // session id → its title
}
// piDesktopTitlesHeld is how long the names read stand before the
// database is looked at again. Tests set it to 0.
var piDesktopTitlesHeld = time.Second
// PIDesktopTitles are the titles PI-Desktop gave the chats ids name, those
// it has one for. pi.sqlite is only read: opened immutable, or from a copy
// when its write-ahead log holds what isn't in it yet, as Cursor's
// store.db is (openCursorStore). A database that can't be read leaves the
// names last read standing: unknown, not untitled.
func PIDesktopTitles(ids []string) map[string]string {
out := map[string]string{}
if len(ids) == 0 {
return out
}
piDesktopTitles.Lock()
defer piDesktopTitles.Unlock()
if piDesktopTitles.names == nil || time.Since(piDesktopTitles.at) >= piDesktopTitlesHeld {
scanPIDesktopTitles()
}
for _, id := range ids {
if name := piDesktopTitles.names[id]; name != "" {
out[id] = name
}
}
return out
}
// scanPIDesktopTitles reads the names again when pi.sqlite or its log
// changed; the caller holds piDesktopTitles.
func scanPIDesktopTitles() {
piDesktopTitles.at = time.Now()
path := filepath.Join(PIDesktopDir(), "pi.sqlite")
main, err := os.Stat(path)
if errors.Is(err, fs.ErrNotExist) {
piDesktopTitles.names, piDesktopTitles.stamp = map[string]string{}, ""
return
} else if err != nil {
return
}
stamp := main.ModTime().String() + "|" + strconv.FormatInt(main.Size(), 10)
if wal, err := os.Stat(path + "-wal"); err == nil {
stamp += "|" + wal.ModTime().String() + "|" + strconv.FormatInt(wal.Size(), 10)
}
if piDesktopTitles.names != nil && stamp == piDesktopTitles.stamp {
return
}
db, closeDB, err := openCursorStore(path)
if err != nil {
return
}
defer closeDB()
rows, err := db.Query(`SELECT id, title FROM sessions WHERE deleted_at IS NULL AND title != ''`)
if err != nil {
return
}
defer rows.Close()
names := map[string]string{}
for rows.Next() {
var id, name string
if rows.Scan(&id, &name) == nil && id != "" {
names[id] = title(name)
}
}
if rows.Err() != nil {
return
}
piDesktopTitles.names, piDesktopTitles.stamp = names, stamp
}
// isPIDesktop says whether a gateway session's agent may be PI-Desktop's:
// its own name, or Pi's, which it goes by unless given a User-Agent of
// its own (#1966).
func isPIDesktop(agent string) bool { return agent == "pi-desktop" || agent == "pi" }
+110
View File
@@ -0,0 +1,110 @@
package sessions
import (
"database/sql"
"os"
"path/filepath"
"testing"
"time"
)
// piDesktopSchema is the sessions table as PI-Desktop's host-core makes it
// (crates/host-core/src/db/schema.rs).
const piDesktopSchema = `CREATE TABLE sessions (
id TEXT PRIMARY KEY,
title TEXT NOT NULL DEFAULT '',
project_id INTEGER,
provider_id TEXT,
model_id TEXT,
mode TEXT NOT NULL DEFAULT 'agent',
title_source TEXT NOT NULL DEFAULT 'legacy'
CHECK (title_source IN ('legacy', 'default', 'manual', 'generated')),
source TEXT,
deleted_at INTEGER,
pinned INTEGER NOT NULL DEFAULT 0,
last_seq INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)`
// A chat PI-Desktop sends through magpie (X-Magpie-Session: its id) goes
// by the title PI-Desktop keeps in pi.sqlite, as Pi's or as PI-Desktop's
// own agent, and not by its id (#1967, dgmico) — read with the title still
// in the write-ahead log, as a running PI-Desktop leaves it, without a
// byte written in PI-Desktop's folder.
func TestPIDesktopTitlesNameGatewaySessions(t *testing.T) {
dir := t.TempDir()
t.Setenv("PI_DESKTOP_DATA_DIR", dir)
held := piDesktopTitlesHeld
piDesktopTitlesHeld = 0
t.Cleanup(func() { piDesktopTitlesHeld = held; piDesktopTitles.names, piDesktopTitles.stamp = nil, "" })
path := filepath.Join(dir, "pi.sqlite")
db, err := sql.Open("sqlite", "file:"+filepath.ToSlash(path))
if err != nil {
t.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(1) // one connection, so the log stays open
for _, q := range []string{"PRAGMA journal_mode=WAL", "PRAGMA wal_autocheckpoint=0", piDesktopSchema,
`INSERT INTO sessions (id, title, title_source, created_at, updated_at) VALUES ('3970a74b-bc9e-4379-a228-38474a2b6871', '你好啊', 'generated', 1, 2)`,
`INSERT INTO sessions (id, title, title_source, deleted_at, created_at, updated_at) VALUES ('gone-0001', 'Deleted chat', 'manual', 5, 1, 2)`,
`INSERT INTO sessions (id, title, title_source, created_at, updated_at) VALUES ('blank-0001', '', 'default', 1, 2)`,
} {
if _, err := db.Exec(q); err != nil {
t.Fatalf("%s: %v", q, err)
}
}
if fi, err := os.Stat(path + "-wal"); err != nil || fi.Size() == 0 {
t.Fatalf("the titles should be in the log, as a running PI-Desktop has them: %v", err)
}
before := folderState(t, dir)
const id = "3970a74b-bc9e-4379-a228-38474a2b6871"
got := MergeExternal(nil, []ExternalSession{
{Agent: "pi", ID: id, Last: time.Unix(3, 0)},
{Agent: "pi-desktop", ID: id, Last: time.Unix(2, 0)},
{Agent: "claude", ID: id, Last: time.Unix(1, 0)},
{Agent: "pi", ID: "gone-0001"},
{Agent: "pi", ID: "blank-0001", Title: "what it was first asked"},
})
want := map[string]string{"pi|" + id: "你好啊", "pi-desktop|" + id: "你好啊", "claude|" + id: id, "pi|gone-0001": "gone-0001", "pi|blank-0001": "what it was first asked"}
for _, s := range got {
if w := want[s.Agent+"|"+s.ID]; s.Title != w {
t.Errorf("%s|%s titled %q, want %q", s.Agent, s.ID, s.Title, w)
}
}
st := MergeExternalStats(Stats{}, nil, []ExternalSession{{Agent: "pi-desktop", ID: id, Last: time.Now()}})
if len(st.Sessions) != 1 || st.Sessions[0].Title != "你好啊" {
t.Errorf("stats sessions %+v", st.Sessions)
}
if after := folderState(t, dir); after != before {
t.Errorf("PI-Desktop's folder changed:\n%s\n→\n%s", before, after)
}
// renamed in PI-Desktop: the next read has the new name
if _, err := db.Exec(`UPDATE sessions SET title = '改过的名字', title_source = 'manual' WHERE id = ?`, id); err != nil {
t.Fatal(err)
}
if got := PIDesktopTitles([]string{id})[id]; got != "改过的名字" {
t.Errorf("after the rename %q", got)
}
}
// folderState is each file of dir with its size and time.
func folderState(t *testing.T, dir string) string {
t.Helper()
es, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
var s string
for _, e := range es {
fi, err := e.Info()
if err != nil {
t.Fatal(err)
}
s += e.Name() + " " + fi.ModTime().String() + " " + itoa(int(fi.Size())) + "\n"
}
return s
}