Follow-up to Koohoko's 3d6f8b8e, after review. - Cost: assemble asks DesktopTitles once per native Claude Desktop session, and each call globbed and stat'ed every local_*.json, so a list of N Cowork sessions looked at the metadata N times. The names are now one index, rebuilt at most once a second (desktopTitlesHeld); a rename in Desktop shows within that second. Files are read through filememo, the shared reader the usage resolver already uses for these same files, which also catches a same-size rewrite inside one mtime tick (the patch's own size+mtime cache didn't). - A record that is there but doesn't parse (Desktop midway through a write) keeps its last parse instead of dropping to the bare id; a record gone still takes its names with it. - Handles: Claude.app 2.7032's LocalSessionManager (app.asar, read-only) counts unarchivedCliSessionId as a live handle beside cliSessionId and preClearCliSessionId as lineage beside priorCliSessionIds, and runs a record with no cliSessionId under its sessionId without "local_". All are named now; the raw "local_..." id no longer is (no usage record carries it). - Siblings: MergeExternalStats (the Sessions page's stats summaries) and the Context page named gateway-only Desktop sessions by the recorded prompt or nothing; both use the Desktop name now. - docs/subsystems/gateway-sessions.md says all of the above. Real layout: no Desktop session records exist on this Mac or the Windows box (only claude_desktop_config.json), so field names and types were checked against Claude.app 2.7032's own reader/writer code: a string title, string cliSessionId/unarchivedCliSessionId/ preClearCliSessionId, an array priorCliSessionIds, files <account>/<org>/local_*.json under claude-code-sessions and local-agent-mode-sessions. Dirs come from desktopdir.Everywhere, the resolver the other Desktop session readers use (Windows %APPDATA% and MSIX LocalCache, Linux ~/.config); Windows/Linux not run. Run: new tests TestDesktopSessionTitleHandles, TestDesktopSessionTitleInStats, TestDesktopTitlesReadOncePerList, and context checks in TestDesktopSessionTitlesOnPages. Each broken by hand went red: rescan per call -> "metadata looked at 12 times, want once"; no last-good -> "a half-written file lost its names"; no unarchived/stem -> missing ids; stats without the name -> "stats titles map[cli-s:Recorded prompt ...]"; Context without it -> "context titles map[...: ...]". go test -race -count=20 -run TestDesktop ./internal/sessions; go test -tags nogui ./... (sandbox HOME, pinned caches): all ok but internal/plugin's TestPiPackage (pi-codemode export missing; passes alone, doesn't import sessions or gui), filed as #1879; gofmt -l; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...; go build, GOOS=linux go build -tags nogui, GOOS=windows go build. GUI: routing-sessions, session-identity, sessions-overview, sessions-bar-names, sessions-gateway-delete, sessions-manage, context-window in Chromium and WebKit (84/84 each). Real binary: magpie web under a sandbox HOME with Claude-3p Code and Claude Cowork fixture records and five claude-desktop usage records; the Sessions page (Chromium, WebKit) showed both titles on current, prior and unarchived ids and the bare id on the unmatched one; /api/gateway/session-titles named them; a rename showed after 1.3s; a half-written file kept the name; deleting the record went back to the id. Co-authored-by: Koohoko <koohoko@gmail.com>
172 lines
5.2 KiB
Go
172 lines
5.2 KiB
Go
package sessions
|
|
|
|
import (
|
|
"cmp"
|
|
"math"
|
|
"slices"
|
|
"sort"
|
|
"time"
|
|
)
|
|
|
|
// ExternalModel and ExternalSession are read-only session projections from a
|
|
// request ledger such as the gateway. They intentionally carry no file or
|
|
// resume capability.
|
|
type ExternalModel struct {
|
|
Model string
|
|
Tokens
|
|
Cost float64
|
|
Priced bool
|
|
}
|
|
type ExternalSession struct {
|
|
Agent, ID string
|
|
Title string // what it was first asked (GatewayTitle); its id when ""
|
|
Start, Last time.Time
|
|
Models []ExternalModel
|
|
Daily []ExternalDayUsage
|
|
Tokens
|
|
Cost float64
|
|
Unpriced int
|
|
}
|
|
|
|
// MergeExternal adds external sessions to a file-backed listing. Native
|
|
// sessions win on the exact Agent+ID identity and external entries are kept
|
|
// read-only (no file of the agent's to resume or open) with a gateway transcript
|
|
// reader; magpie's own record of one is deleted by DeleteGateway.
|
|
func MergeExternal(native []Session, external []ExternalSession) []Session {
|
|
names := desktopExternalTitles(external)
|
|
seen := map[string]bool{}
|
|
for _, s := range native {
|
|
seen[s.Agent+"|"+s.ID] = true
|
|
}
|
|
out := append([]Session(nil), native...)
|
|
for _, e := range external {
|
|
if e.Agent == "" || e.ID == "" || seen[e.Agent+"|"+e.ID] {
|
|
continue
|
|
}
|
|
s := Session{ReadOnly: true, Gateway: true, Transcript: true, Agent: e.Agent, ID: e.ID, Title: cmp.Or(names[e.Agent+"|"+e.ID], e.Title, e.ID), Start: e.Start, Last: e.Last, Models: []Model{}, Unpriced: e.Unpriced}
|
|
for _, m := range e.Models {
|
|
s.Models = append(s.Models, Model{Model: m.Model, Tokens: m.Tokens, Cost: m.Cost, Priced: m.Priced})
|
|
s.Tokens.add(m.Tokens)
|
|
}
|
|
s.Cost = e.Cost
|
|
out = append(out, s)
|
|
}
|
|
sort.SliceStable(out, func(i, j int) bool { return out[i].Last.After(out[j].Last) })
|
|
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.
|
|
func desktopExternalTitles(external []ExternalSession) map[string]string {
|
|
var ids []string
|
|
for _, e := range external {
|
|
if e.Agent == "claude-desktop" {
|
|
ids = append(ids, e.ID)
|
|
}
|
|
}
|
|
out := map[string]string{}
|
|
for id, name := range DesktopTitles(ids) {
|
|
out["claude-desktop|"+id] = name
|
|
}
|
|
return out
|
|
}
|
|
|
|
// MergeExternalStats appends external daily usage and session summaries to a
|
|
// Stats snapshot. It is deliberately data-only so callers can keep their own
|
|
// source and pricing policy.
|
|
type ExternalDayUsage struct {
|
|
Date, Agent, Cwd, Model string
|
|
Tokens
|
|
Cost float64
|
|
Priced bool
|
|
}
|
|
|
|
func MergeExternalStats(st Stats, days []ExternalDayUsage, external []ExternalSession) Stats {
|
|
oldFirst, _ := time.ParseInLocation(time.DateOnly, st.From, time.Local)
|
|
for _, d := range days {
|
|
if d.Date <= st.To && (st.From == "" || d.Date < st.From) {
|
|
st.From = d.Date
|
|
}
|
|
}
|
|
first, _ := time.ParseInLocation(time.DateOnly, st.From, time.Local)
|
|
if !oldFirst.IsZero() && !first.Equal(oldFirst) {
|
|
shift := int(math.Round(oldFirst.Sub(first).Hours() / 24))
|
|
st.Sessions = slices.Clone(st.Sessions)
|
|
for i := range st.Sessions {
|
|
s := &st.Sessions[i]
|
|
s.Days = slices.Clone(s.Days)
|
|
for j := range s.Days {
|
|
s.Days[j] += shift
|
|
}
|
|
pd := map[int]*summaryDay{}
|
|
for d, v := range s.perDay {
|
|
pd[d+shift] = v
|
|
}
|
|
s.perDay = pd
|
|
}
|
|
}
|
|
byDate := map[string]int{}
|
|
for i := range st.Days {
|
|
byDate[st.Days[i].Date] = i
|
|
}
|
|
for _, u := range days {
|
|
if u.Date < st.From || u.Date > st.To {
|
|
continue
|
|
}
|
|
i, ok := byDate[u.Date]
|
|
if !ok {
|
|
st.Days = append(st.Days, Day{Date: u.Date, Usage: []Usage{}, Active: []Active{}})
|
|
i = len(st.Days) - 1
|
|
byDate[u.Date] = i
|
|
}
|
|
d := &st.Days[i]
|
|
found := false
|
|
for i := range d.Usage {
|
|
if d.Usage[i].Agent == u.Agent && d.Usage[i].Cwd == u.Cwd && d.Usage[i].Model == u.Model {
|
|
d.Usage[i].Tokens.add(u.Tokens)
|
|
d.Usage[i].Cost += u.Cost
|
|
d.Usage[i].Priced = d.Usage[i].Priced && u.Priced
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
if !found {
|
|
d.Usage = append(d.Usage, Usage{Agent: u.Agent, Cwd: u.Cwd, Model: u.Model, Tokens: u.Tokens, Cost: u.Cost, Priced: u.Priced})
|
|
}
|
|
}
|
|
names := desktopExternalTitles(external)
|
|
for _, e := range external {
|
|
if e.ID == "" || e.Agent == "" {
|
|
continue
|
|
}
|
|
s := Summary{Key: e.Agent + ":" + e.ID, Agent: e.Agent, ID: e.ID, Title: cmp.Or(names[e.Agent+"|"+e.ID], e.Title), Last: e.Last, Tokens: e.Tokens, Cost: e.Cost, Priced: true, Models: []string{}, Days: []int{}, perDay: map[int]*summaryDay{}}
|
|
for _, u := range e.Daily {
|
|
day, err := time.ParseInLocation(time.DateOnly, u.Date, time.Local)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
d := int(math.Round(day.Sub(first).Hours() / 24))
|
|
if first.IsZero() || u.Date < st.From || u.Date > st.To {
|
|
continue
|
|
}
|
|
pd := s.perDay[d]
|
|
if pd == nil {
|
|
pd = &summaryDay{}
|
|
s.perDay[d] = pd
|
|
s.Days = append(s.Days, d)
|
|
}
|
|
pd.output += u.Output
|
|
}
|
|
sort.Ints(s.Days)
|
|
for _, m := range e.Models {
|
|
s.Models = append(s.Models, m.Model)
|
|
s.Priced = s.Priced && m.Priced
|
|
}
|
|
st.Sessions = append(st.Sessions, s)
|
|
}
|
|
sort.Slice(st.Days, func(i, j int) bool { return st.Days[i].Date < st.Days[j].Date })
|
|
sort.SliceStable(st.Sessions, func(i, j int) bool { return st.Sessions[i].Last.After(st.Sessions[j].Last) })
|
|
return st
|
|
}
|