usage: dsh sessions in Context go by their titles (Kumo31 on Discord)

Usage -> Context listed DeepSeek Harness sessions as "magpie-a",
"magpie-f" and so on, while Usage -> Sessions showed their titles. Real
dsh 0.2.0-rc.2 sends no session header on its chat-completions and
messages routes. The gateway therefore keys each request by
conversationID, a hash of the first user message. contextOf joined
titles on agent + session id, and a hash never matches a dsh session
id. The responses route sends session_id and was already joined.

- The dsh reader (sessions) records the ids the gateway gives a
  session's requests: the first typed user/message and the
  session/title-llm-request message. Each is hashed in the forms dsh
  sends it: a string, and a text part with or without a cache mark.
  The text goes through a JSON.stringify-compatible encoder (jsString),
  because encoding/json escapes <, > and &. These ids are
  Session.Convs; cacheVersion goes to 22.
- contextOf (joinConvs) puts a route that names no session under the
  session its conv id came from. An id two sessions share is left as
  it is. The title call merges in and is skipped as a tool-less side
  call. The existing title join then finds the session.

Fixture: internal/sessions/testdata/dsh-gateway holds two real dsh
session files and the four requests that dsh sent for them to a fake
upstream: a turn and a title call on each of the completions and
messages routes, headers and body as captured. Only the cwd is
rewritten to /work/proj.

Siblings: other agents that send no session header have the same gap,
but none was run to see what it sends. Filed as #3263.

Run at bc11b8a5f (on origin/main ccbc72781):
- gofmt -l: clean.
- go vet: darwin, GOOS=linux -tags nogui and GOOS=windows ./...: clean.
- set -o pipefail; go test -timeout 45m ./... | tee: exit 0, every
  package ok.
- No GUI or page files changed, so the GUI suite was not run.

Broken by hand:
- joinConvs commented out: TestContextDshSessionTitles red, the
  sessions keyed magpie-950998..., magpie-3dc586... and so on, with no
  titles.
- json.Marshal in place of jsString: TestDshSessionConvsAreTheGatewayIDs
  red on all four requests.
- title-llm-request not collected: that test red on both title calls.

New tests:
- TestDshRoutesCarryTheSessionConvs sends the captured requests
  through the gateway's handler and finds each route's Conv among its
  session's Convs.
- On the old code the tests don't build, because Convs doesn't exist.

Not tried:
- a masked first prompt (the hash is taken after masking, so the
  session stays untitled);
- a first prompt with an image or several parts;
- dsh's subagent files and forks (seeded sessions);
- a conv after compaction;
- the DSH desktop app;
- Kumo31's own history. Old routes keep their Conv, so they should
  join on the next read, but that was not seen.
This commit is contained in:
yetone
2026-10-22 19:03:32 +08:00
parent 46176fc14f
commit 9572a35761
11 changed files with 410 additions and 4 deletions
+152
View File
@@ -0,0 +1,152 @@
package gateway
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
)
// Kumo31 on Discord: dsh's chat-completions and messages routes send no
// session id, so the gateway keys each request by its first prompt's hash
// (conversationID), and the Context page listed dsh's sessions as
// "magpie-a…" where the Sessions page has their titles. The requests here
// are the ones real dsh 0.2.0-rc.2 sent for the two sessions beside them,
// a turn and its title call on each route, headers and body as they came:
// every one's conversation id is one the session's file gives (Convs).
const dshFixture = "../sessions/testdata/dsh-gateway"
const dshChat, dshMsgs = "session-508e7b0a-37c0-41f7-ac62-e48ab3146111", "session-8d93476d-ca34-461c-9e8e-7031c1dedfff"
// dshRequests are the captured requests, by the session each was sent in.
var dshRequests = map[string]string{
"completions-turn.json": dshChat,
"completions-title.json": dshChat,
"messages-turn.json": dshMsgs,
"messages-title.json": dshMsgs,
}
// dshFixtureSessions lists the fixture's dsh sessions, by id.
func dshFixtureSessions(t *testing.T) map[string]sessions.Session {
t.Helper()
// dsh's layout: $DSH_HOME/sessions/<project>/<session>/session.v4.jsonl
home := t.TempDir()
if err := os.CopyFS(filepath.Join(home, "sessions"), os.DirFS(filepath.Join(filepath.FromSlash(dshFixture), "sessions"))); err != nil {
t.Fatal(err)
}
t.Setenv("DSH_HOME", home)
sessions.Reset()
t.Cleanup(sessions.Reset)
byID := map[string]sessions.Session{}
for _, s := range sessions.List(0) {
if s.Agent == "dsh" {
byID[s.ID] = s
}
}
if len(byID) != 2 || byID[dshChat].Title == "" || byID[dshMsgs].Title == "" {
t.Fatalf("sessions %+v", byID)
}
return byID
}
// dshRequest is a captured request's path, headers and body as dsh sent them.
func dshRequest(t *testing.T, name string) (string, http.Header, []byte) {
t.Helper()
b, err := os.ReadFile(filepath.Join(filepath.FromSlash(dshFixture), "requests", name))
if err != nil {
t.Fatal(err)
}
head, body, _ := bytes.Cut(b, []byte("\n"))
var captured struct {
Path string `json:"path"`
Headers map[string]string `json:"headers"`
}
if err := json.Unmarshal(head, &captured); err != nil {
t.Fatal(err)
}
h := http.Header{}
for k, v := range captured.Headers {
h.Set(k, v)
}
return captured.Path, h, body
}
func TestDshSessionConvsAreTheGatewayIDs(t *testing.T) {
fresh(t)
byID := dshFixtureSessions(t)
for name, id := range dshRequests {
_, h, body := dshRequest(t, name)
conv := conversationID(h, body)
if !strings.HasPrefix(conv, "magpie-") {
t.Fatalf("%s: dsh sent a session id now (%s); the join isn't needed for it", name, conv)
}
if !slices.Contains(byID[id].Convs, conv) {
t.Errorf("%s: %s is not among %s's %v", name, conv, id, byID[id].Convs)
}
for other, s := range byID {
if other != id && slices.Contains(s.Convs, conv) {
t.Errorf("%s: %s is %s's too", name, conv, other)
}
}
t.Logf("%s %s", name, conv)
}
}
// The same requests sent through the gateway are traced under those ids:
// what reaches conversationID is the body dsh sent, not one rewritten on
// the way in.
func TestDshRoutesCarryTheSessionConvs(t *testing.T) {
fresh(t)
byID := dshFixtureSessions(t)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "/messages") {
io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":9,"output_tokens":1}}`)
return
}
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":1}}`)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "fake", Name: "FAKE", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1", Anthropic: up.URL}); err != nil {
t.Fatal(err)
}
s := New()
for name, id := range dshRequests {
path, h, body := dshRequest(t, name)
// only the model is changed, to one this gateway has
body = bytes.Replace(body, []byte(`"model":"group/flash"`), []byte(`"model":"fake/m1"`), 1)
body = bytes.Replace(body, []byte(`"stream":true`), []byte(`"stream":false`), 1)
r := httptest.NewRequest("POST", path, bytes.NewReader(body))
r.Header = h.Clone()
r.Header.Del("Content-Length")
r.Header.Del("Accept-Encoding")
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("%s: %d %s", name, w.Code, w.Body)
}
rs := s.Trace(context.Background(), 0, 0).Routes
var last Route
for _, x := range rs {
if x.ID > last.ID {
last = x
}
}
// (its agent is package agent's to name: "dsh" by its User-Agent,
// which gui's TestContextDshSessionTitles checks)
if last.Session != "" || !slices.Contains(byID[id].Convs, last.Conv) {
t.Errorf("%s: route session %q conv %q, not one of %s's %v", name, last.Session, last.Conv, id, byID[id].Convs)
}
}
}
+46 -1
View File
@@ -161,6 +161,43 @@ func sessionOfRoute(r gateway.Route) string {
return r.Conv
}
// joinConvs puts a route that names no session under the agent's session
// its conversation id was read from (sessions' Convs): dsh's
// chat-completions and messages routes send no session id, so the gateway
// keys each request by its first prompt's hash, and the page showed
// "magpie-a…" where the Sessions page shows the session's title (Kumo31
// on Discord). An id two sessions share stays as it is.
func joinConvs(routes []gateway.Route, list func() []sessions.Session) {
loose := false
for _, r := range routes {
if r.Session == "" && r.ParentSession == "" && r.Conv != "" {
loose = true
break
}
}
if !loose {
return
}
of := map[string]string{}
for _, s := range list() {
for _, c := range s.Convs {
k := s.Agent + "\x00" + c
if id, ok := of[k]; ok && id != s.ID {
of[k] = ""
} else if !ok {
of[k] = s.ID
}
}
}
for i, r := range routes {
if r.Session == "" && r.ParentSession == "" && r.Conv != "" {
if id := of[r.Agent+"\x00"+r.Conv]; id != "" {
routes[i].Session = id
}
}
}
}
// compacted says a prompt is a compaction of the one before it: under 60%
// of a prompt of some size.
func compacted(prev, next int) bool { return prev >= 20000 && next < prev*6/10 }
@@ -211,6 +248,14 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
}
agents := map[string]*agentAcc{}
sess := map[string]*ctxSession{}
var listed []sessions.Session
list := func() []sessions.Session {
if listed == nil {
listed = sessions.List(0)
}
return listed
}
joinConvs(routes, list)
tooled := toolSessions(routes)
var order []string
for _, r := range routes {
@@ -341,7 +386,7 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
}
}
if len(untitled) > 0 {
for _, s := range sessions.List(0) {
for _, s := range list() {
if i, ok := untitled[s.Agent+"\x00"+s.ID]; ok && s.Title != "" {
out.Sessions[i].Title = s.Title
}
+61
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"io"
"maps"
"net/http"
"net/http/httptest"
"os"
@@ -17,6 +18,7 @@ import (
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
"github.com/yetone/magpie/internal/usage"
)
// ctxRoute is a done request of agent in session whose prompt holds base
@@ -240,6 +242,65 @@ func TestContextSessionTitles(t *testing.T) {
}
}
// Kumo31 on Discord: dsh sends no session id on its chat-completions and
// messages routes, so its requests reach the page keyed by the gateway's
// hash of their first prompt, and its sessions were listed as "magpie-a…".
// They go under the session that prompt was read from, by the title the
// Sessions page shows; its title call, with no tools, is no turn of it.
// The ids are the real requests' beside the fixture
// (gateway's TestDshSessionConvsAreTheGatewayIDs).
func TestContextDshSessionTitles(t *testing.T) {
sandboxHome(t)
home := t.TempDir()
fixture := filepath.Join("..", "sessions", "testdata", "dsh-gateway", "sessions")
if err := os.CopyFS(filepath.Join(home, "sessions"), os.DirFS(fixture)); err != nil {
t.Fatal(err)
}
t.Setenv("DSH_HOME", home)
sessions.Reset()
t.Cleanup(sessions.Reset)
const chat, msgs = "session-508e7b0a-37c0-41f7-ac62-e48ab3146111", "session-8d93476d-ca34-461c-9e8e-7031c1dedfff"
listed := map[string]string{}
for _, s := range sessions.List(0) {
listed[s.Agent+" "+s.ID] = s.Title
}
if listed["dsh "+chat] == "" || listed["dsh "+msgs] == "" {
t.Fatalf("listed %v", listed)
}
// the gateway names the agent by dsh's User-Agent, as it sent it
if a := usage.AgentOf("deepseek-harness/0.2.0-rc.2 (+https://github.com/deepseek-ai/deepseek-harness)"); a != "dsh" {
t.Fatalf("dsh's requests go as %q", a)
}
conv := func(id int64, c string, tools bool) gateway.Route {
r := ctxRoute(id, "dsh", "", 20000, 1000*int(id), 128000, 0)
r.Conv = c
if !tools {
r.Prompt.Parts = r.Prompt.Parts[2:]
}
return r
}
out := contextOf([]gateway.Route{
conv(1, "magpie-950998433c3e70e50dc32994", true), // chat-completions turn
conv(2, "magpie-3dc58631c53e0df2e657ee2c", false), // its title call
conv(3, "magpie-be31a0561e12cf603d3e79d9", true), // messages turn
conv(4, "magpie-a2ca3891cf83d335f4a635fa", false), // its title call
conv(5, "magpie-000000000000000000000000", true), // no file's
}, 7)
titles := map[string]string{}
for _, s := range out.Sessions {
titles[s.Key] = s.Title
}
want := map[string]string{chat: listed["dsh "+chat], msgs: listed["dsh "+msgs], "magpie-000000000000000000000000": ""}
if !maps.Equal(titles, want) {
t.Fatalf("titles %v, want %v", titles, want)
}
for _, s := range out.Sessions {
if s.Key != "magpie-000000000000000000000000" && s.Requests != 1 {
t.Fatalf("%s: %d requests, its title call counted as a turn", s.Key, s.Requests)
}
}
}
// masaka on Discord: a part of the context window card opens to its text.
// /api/context/text lists the part's items, and gives one item's text when
// asked for it; a request whose body is no longer kept is 404.
+83 -2
View File
@@ -3,6 +3,8 @@ package sessions
import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
@@ -227,7 +229,12 @@ type dshEvent struct {
} `json:"source"`
Title string `json:"title"`
Inherited bool `json:"inherited"`
Message struct {
// Messages are a title call's (session/title-llm-request)
Messages []struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
} `json:"messages"`
Message struct {
Source dshSource `json:"source"`
} `json:"message"`
Usage *struct {
@@ -239,7 +246,7 @@ type dshEvent struct {
} `json:"data"`
}
var dshWanted = [][]byte{[]byte(`"user/message"`), []byte(`"session/title"`), []byte(`"assistant/message"`), []byte(`"session/end-seed"`)}
var dshWanted = [][]byte{[]byte(`"user/message"`), []byte(`"session/title"`), []byte(`"session/title-llm-request"`), []byte(`"assistant/message"`), []byte(`"session/end-seed"`)}
// dshCarry is what a read of a dsh session file carries on with: where it
// read to and the header it read first.
@@ -323,6 +330,7 @@ func dshCount(s *state, h *dshHead, b []byte, main bool) {
switch e.Type {
case "user/message":
if main && s.Title == "" && s.First == "" && e.Data.Source.Kind == "user" {
s.Convs = append(s.Convs, dshConvs(e.Data.Content)...)
if t := ccText(e.Data.Content); strings.HasPrefix(t, "<") {
s.First = untagged(t)
} else {
@@ -333,6 +341,15 @@ func dshCount(s *state, h *dshHead, b []byte, main bool) {
if t := title(e.Data.Title); t != "" {
s.Named = t
}
case "session/title-llm-request":
if main {
for _, m := range e.Data.Messages {
if m.Role == "user" {
s.Convs = append(s.Convs, dshConvs(m.Content)...)
break
}
}
}
case "session/end-seed":
if h.Version >= 2 && h.IsSeeded && e.Data.Inherited {
// the events a fork was seeded with end here: what was
@@ -380,3 +397,67 @@ func dshNum(b []byte, key string) int64 {
}
return n
}
// dshConvs are the conversation ids magpie's gateway gives the requests a
// message starts (gateway's conversationID). dsh sends no session id on
// its chat-completions and messages routes, so the gateway keys each such
// request by the hash of its first user message as sent, and the Context
// page finds the session only through it (Kumo31 on Discord). A message
// of one text part goes out as a plain string, or, as the last user
// message on the messages route, as that part with a cache mark: each
// spelling is hashed. Anything else (an image, several parts) gives none.
func dshConvs(content json.RawMessage) []string {
var parts []struct {
Type string `json:"type"`
Text string `json:"text"`
}
if json.Unmarshal(content, &parts) != nil || len(parts) != 1 || parts[0].Type != "text" || parts[0].Text == "" {
return nil
}
t := jsString(parts[0].Text)
out := make([]string, 0, 3)
for _, m := range []string{
`{"role":"user","content":` + t + `}`,
`{"role":"user","content":[{"type":"text","text":` + t + `}]}`,
`{"role":"user","content":[{"type":"text","text":` + t + `,"cache_control":{"type":"ephemeral"}}]}`,
} {
sum := sha256.Sum256([]byte(m))
out = append(out, "magpie-"+hex.EncodeToString(sum[:12]))
}
return out
}
// jsString is a string as JavaScript's JSON.stringify writes it, the way
// dsh's requests carry it: unlike encoding/json it leaves <, >, &, U+2028
// and U+2029 as they are.
func jsString(s string) string {
var b strings.Builder
b.Grow(len(s) + 2)
b.WriteByte('"')
for _, r := range s {
switch r {
case '"':
b.WriteString(`\"`)
case '\\':
b.WriteString(`\\`)
case '\b':
b.WriteString(`\b`)
case '\f':
b.WriteString(`\f`)
case '\n':
b.WriteString(`\n`)
case '\r':
b.WriteString(`\r`)
case '\t':
b.WriteString(`\t`)
default:
if r < 0x20 {
fmt.Fprintf(&b, `\u%04x`, r)
} else {
b.WriteRune(r)
}
}
}
b.WriteByte('"')
return b.String()
}
+8 -1
View File
@@ -149,6 +149,9 @@ type Session struct {
// WSL is the WSL distro the session ran in, its files read through
// \\wsl.localhost (see wsl.go); "" for this computer's own
WSL string `json:"wsl,omitempty"`
// Convs are the ids magpie's gateway keys the session's requests by
// when they carry no session id of their own (dshConvs)
Convs []string `json:"-"`
}
// PriceOf is the effective price of a model as a session names it, at the
@@ -193,6 +196,7 @@ type state struct {
Named string `json:"named,omitempty"` // the agent's own title for it
Custom string `json:"custom,omitempty"` // the name the user gave it
First string `json:"first,omitempty"` // the first message, when no prompt looked typed
Convs []string `json:"convs,omitempty"` // the gateway's ids for its requests (dshConvs)
Start time.Time `json:"start"`
Last time.Time `json:"last"`
Models map[string]Tokens `json:"models,omitempty"`
@@ -363,6 +367,7 @@ func (s *state) clone() *state {
t := *s.Total
c.Total = &t
}
c.Convs = slices.Clone(s.Convs)
c.CodexSpawnNames = maps.Clone(s.CodexSpawnNames)
c.CodexSpawnConflicts = maps.Clone(s.CodexSpawnConflicts)
c.CodexAgentIDs = maps.Clone(s.CodexAgentIDs)
@@ -685,7 +690,8 @@ func CachePath() string { return filepath.Join(filepath.Dir(catalog.CachePath())
// 19: the names the user gave Claude Code's and WorkBuddy's (custom-title).
// 20: Codex's source and direct parent thread identity.
// 21: Codex subagent nicknames and parent spawn task names.
const cacheVersion = 21
// 22: dsh's gateway conversation ids (Convs).
const cacheVersion = 22
type cacheFile struct {
Version int `json:"version"`
@@ -1229,6 +1235,7 @@ func assembleListed(fs []file, price func(string) *catalog.Price) (Session, bool
if first == "" {
first = st.First
}
s.Convs = append(s.Convs, st.Convs...)
}
if s.Agent == "codex" && st.CodexNickname != "" {
s.Nickname = st.CodexNickname
@@ -0,0 +1,2 @@
{"path": "/v1/chat/completions", "headers": {"host": "127.0.0.1:3597", "connection": "keep-alive", "Accept": "application/json", "X-Stainless-Retry-Count": "0", "X-Stainless-Lang": "js", "X-Stainless-Package-Version": "6.40.0", "X-Stainless-OS": "MacOS", "X-Stainless-Arch": "arm64", "X-Stainless-Runtime": "node", "X-Stainless-Runtime-Version": "v22.22.0", "authorization": "Bearer sk-test", "user-agent": "deepseek-harness/0.2.0-rc.2 (+https://github.com/deepseek-ai/deepseek-harness)", "content-type": "application/json", "accept-language": "*", "sec-fetch-mode": "cors", "accept-encoding": "gzip, deflate", "content-length": "733"}}
{"model":"group/flash","messages":[{"role":"system","content":"Create a concise title for an AI coding-assistant session from the supplied human messages.\nReturn only the title on one line, **in plain text of natural language**, with no quotes, prefix, explanation, Markdown, XML, or terminal control codes. No code is allowed.\nUse the language of the messages.\nAim for about 5 words in non-CJK languages or 10 CJK characters."},{"role":"user","content":"Generate the session title from this JSON array of human messages:\n[{\"seq\":8,\"text\":\"Fix the login bug in auth.go — 中文 <b>&</b> \\\"q\\\" é\\nsecond line\\ttab\"}]"}],"stream":true,"stream_options":{"include_usage":true},"store":false,"max_completion_tokens":64}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
{"path": "/v1/messages?beta=true", "headers": {"host": "127.0.0.1:3597", "connection": "keep-alive", "X-Stainless-Retry-Count": "0", "X-Stainless-Timeout": "600", "X-Stainless-Lang": "js", "X-Stainless-Package-Version": "0.124.0", "X-Stainless-OS": "MacOS", "X-Stainless-Arch": "arm64", "X-Stainless-Runtime": "node", "X-Stainless-Runtime-Version": "v22.22.0", "anthropic-version": "2023-06-01", "x-api-key": "sk-test", "accept": "application/json", "anthropic-dangerous-direct-browser-access": "true", "user-agent": "deepseek-harness/0.2.0-rc.2 (+https://github.com/deepseek-ai/deepseek-harness)", "content-type": "application/json", "accept-language": "*", "sec-fetch-mode": "cors", "accept-encoding": "gzip, deflate", "content-length": "753"}}
{"model":"group/flash","messages":[{"role":"user","content":[{"type":"text","text":"Generate the session title from this JSON array of human messages:\n[{\"seq\":8,\"text\":\"Fix the login bug in auth.go — 中文 <b>&</b> \\\"q\\\" é\"}]","cache_control":{"type":"ephemeral"}}]}],"max_tokens":64,"stream":true,"system":[{"type":"text","text":"Create a concise title for an AI coding-assistant session from the supplied human messages.\nReturn only the title on one line, **in plain text of natural language**, with no quotes, prefix, explanation, Markdown, XML, or terminal control codes. No code is allowed.\nUse the language of the messages.\nAim for about 5 words in non-CJK languages or 10 CJK characters.","cache_control":{"type":"ephemeral"}}]}
File diff suppressed because one or more lines are too long