Files
magpie/internal/gui/desktop_session_titles_test.go
T
yetoneandKoohoko 067f39f406 sessions: Desktop titles read once per second, from every handle Desktop keeps, and reach stats and Context (#1675)
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>
2026-10-13 07:14:22 +08:00

113 lines
4.3 KiB
Go

package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/sessions"
"github.com/yetone/magpie/internal/usage"
)
// The user-facing lists and Routing use Desktop's metadata even when no
// transcript or gateway recording exists, including after a rename.
func TestDesktopSessionTitlesOnPages(t *testing.T) {
sandboxHome(t)
sessions.Reset()
t.Cleanup(sessions.Reset)
const id = "578bd3d1-834b-43fb-b40c-ed9d17ad7731"
const prior = "578bd3d1-834b-43fb-b40c-ed9d17ad7732"
dirs := sessions.DesktopDataDirs()
path := filepath.Join(dirs[len(dirs)-1], "claude-code-sessions", "account", "org", "local_fixture.json")
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
write := func(name string) {
t.Helper()
b, _ := json.Marshal(map[string]any{"sessionId": "local_fixture", "cliSessionId": id, "priorCliSessionIds": []string{prior}, "title": name})
if err := os.WriteFile(path, b, 0o600); err != nil {
t.Fatal(err)
}
}
write("Desktop 会话标题")
for _, session := range []string{id, prior, "remote-only"} {
usage.Append(usage.Record{Time: time.Now().Add(-time.Hour), Agent: "claude-desktop", Session: session, Provider: "deepseek", Model: "deepseek-flash", Input: 40, Output: 9, Status: 200})
}
mux := http.NewServeMux()
sessionRoutes(mux, folderOnly{})
sessionManageRoutes(mux, folderOnly{})
traceRoutes(mux)
check := func(name, remoteName string) {
t.Helper()
for _, path := range []string{"/api/sessions", "/api/sessions/manage?agent=claude-desktop", "/api/sessions/one?key=claude-desktop:" + id} {
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
if w.Code != 200 {
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
}
var out struct {
sessions.Session
Sessions []sessions.Session `json:"sessions"`
}
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
if out.ID != "" {
out.Sessions = []sessions.Session{out.Session}
}
for _, s := range out.Sessions {
want := name
if s.ID == "remote-only" {
want = remoteName
}
if s.Title != want || s.Input != 40 || s.Output != 9 || !s.Gateway || !s.ReadOnly || s.Path != "" || s.Resume != "" {
t.Fatalf("%s: %+v, want title %q and unchanged ledger/capabilities", path, s, want)
}
}
if !strings.Contains(path, "/one?") && len(out.Sessions) != 3 {
t.Fatalf("%s: got %d sessions, want 3", path, len(out.Sessions))
}
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/gateway/session-titles", strings.NewReader(`{"sessions":["claude-desktop:`+id+`","claude-desktop:`+prior+`","claude:`+id+`"]}`)))
var out struct {
Titles map[string]string `json:"titles"`
}
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil || len(out.Titles) != 2 || out.Titles["claude-desktop:"+id] != name || out.Titles["claude-desktop:"+prior] != name {
t.Fatalf("routing names: %d %s", w.Code, w.Body)
}
// the Context page's sessions
titles := map[string]string{}
for _, s := range contextOf([]gateway.Route{ctxRoute(1, "claude-desktop", id, 20000, 1000, 200000, 0), ctxRoute(2, "claude-desktop", "remote-only", 20000, 1000, 200000, 0)}, 7).Sessions {
titles[s.Key] = s.Title
}
if titles[id] != name || titles["remote-only"] != "" {
t.Fatalf("context titles %v, want %q", titles, name)
}
}
check("Desktop 会话标题", "remote-only")
write("Desktop renamed")
// what was read stands for a second (desktopTitlesHeld); Reset is that
// second gone by
sessions.Reset()
check("Desktop renamed", "remote-only")
// Keep upstream's newly added first-prompt title when no Desktop name
// is available, while a saved Desktop name still takes precedence.
if err := sessions.SetGatewayRecording(true, false); err != nil {
t.Fatal(err)
}
for _, session := range []string{id, "remote-only"} {
if err := sessions.SaveGatewayTurn(sessions.GatewayTurn{Agent: "claude-desktop", Session: session, Time: time.Now().Add(-time.Hour),
Input: []sessions.Part{{Role: "user", Kind: "text", Text: "Recorded remote prompt"}}}); err != nil {
t.Fatal(err)
}
}
check("Desktop renamed", "Recorded remote prompt")
}