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.
153 lines
5.3 KiB
Go
153 lines
5.3 KiB
Go
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)
|
|
}
|
|
}
|
|
}
|