routing: a dsh fork's requests are named by the reply its client was given (#5491)

dsh's chat and messages routes send no session id, so Routing and Context
found a dsh session by the hash of the conversation's opening. A fork
repeats its source's opening, so every request the fork made showed under
the source, and the fork's name never appeared.

Flandern1211's patch, ported:
- The gateway keeps the id of the reply it gave the client
  (Route.ResponseID). It is set from clientResponseID in the same update
  that marks the route done, so a poll that sees Done also sees the id,
  with no race against the usage ledger. When magpie translates, it is
  the id after translation, e.g. chatcmpl-…, not the upstream's msg_….
- sessions reads dsh's replayState.response.responseId into
  Session.ResponseIDs. Only main files are read, only replies served by
  the gateway, and only the fork's own replies after its session/end-seed
  (seedLength for version 1).
- Routing (pricedRoutes) and Context (joinConvs) look up a finished
  request by its reply id first, then by its opening. A request logged
  before this keeps the opening's session.

Changed from the patch:
- A reply id names a session over the opening only when the opening is
  that session's own, or a session it was forked from, or the opening is
  unknown. Vendors' ids can repeat: an encoder keeps the upstream's id,
  and Ollama's is chatcmpl-<0..999>. Without the guard, two unrelated
  conversations could swap names. Session.ForkOf comes from the fork
  header's parentSession, isSeeded and delegationDepth 0, which is how
  dsh's buildForkSeed writes it. ownerOf walks that chain, so a fork of a
  fork works too.
- Poll cost: dsh never writes down some reply ids (a title call, a
  refused turn). Under the patch, each such id made Routing list every
  session again every 2s, for as long as the route was on the page. Now
  an id is waited for only up to a minute (convsKept) after its request
  ended (looseKeys). After that the regular one-minute rebuild covers it.
- A page whose loose routes carry only a reply id still builds the map
  (looseRoute).
- The patch's synthetic fork headers gain parentSession, as dsh writes
  them.
- docs/subsystems/gateway-routing.md describes the reply-id join.

Tests:
- TestDshForkNamedByTheReplyTheGatewayGave sends dsh 0.2.0-rc.2's real
  captured completions request (testdata/dsh-gateway) through
  gateway.New() twice, to an Anthropic-only upstream, so the reply is
  translated. It writes the source's real session file with the first
  client id, and a fork shaped like dsh's buildForkSeed output with the
  second. It then checks that pricedRoutes and contextOf put each request
  under its own session, and an old route without an id under the source.
- TestDshForkOfARealSessionListsItsOwnReplies forks the real fixture
  session: the fork lists only its own reply and ForkOf, the source
  keeps [c1].
- TestDshReplyIDOfAnotherConversationNamesNoOne covers the guard.
- TestRoutingWaitsForAReplyIDOnlyAWhile covers the poll bound.
- The patch's own tests: TestDoneRouteKeepsTheClientResponseID (json and
  stream), TestDshResponseIDs*, TestRoutingTellsAForkByItsReply,
  TestContextTellsAForkByItsReply.

Run on mote (mote-run), at this tree on origin/main be5e8f29f. The vet and
go test lines below were run again after rebasing on e6b9d1199, which
changed only the README and library (ok):
- gofmt -l internal/ printed nothing.
- go vet ./internal/... . is clean.
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  internal/{sessions,gui,gateway} are ok.
- go test ./internal/sessions ./internal/gateway ./internal/gui -run
  'Dsh|ResponseID|Fork|Routing|Context|Conv' -count=1: ok.
- GUI: routing-by-key, routing-ctx-sessions, routing-request-metrics,
  routing-sessions, routing-session-folder, sessions-empty-range,
  ctx-route, context-map and panel-routing pass in chromium (120/120)
  and webkit (120/120).

Broken by hand, each red, then restored:
- guard off: TestDshReplyIDOfAnotherConversationNamesNoOne;
- poll bound off: TestRoutingWaitsForAReplyIDOnlyAWhile;
- end-seed keeps the inherited reply ids: TestDshResponseIDsSkipTheSeed,
  TestDshResponseIDsEndSeedAcrossReads and
  TestDshForkOfARealSessionListsItsOwnReplies;
- ForkOf not set: TestDshForkOfARealSessionListsItsOwnReplies,
  TestDshForkNamedByTheReplyTheGatewayGave,
  TestRoutingTellsAForkByItsReply and TestContextTellsAForkByItsReply;
- gateway keeps no id: TestDoneRouteKeepsTheClientResponseID and
  TestDshForkNamedByTheReplyTheGatewayGave.

Not tried:
- a real dsh fork against a running magpie. The session shapes come from
  the real rc.2 fixture and dsh's fork source.
- A request still running, or a failed one, still shows under the source
  until it has a reply id. The patch says the same.
- Delegated subagent files (delegationDepth > 0) are not read for reply
  ids; they stay under their parent as before.
- Not changed: the gateway's turn clock (sessionTurnKey) also falls back
  to the opening's hash, so a fork and its source running at once share
  one. Filed as #5496.

The full suite runs after the push.

Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
Reported-by: flandern1211_58540 (Discord)
This commit is contained in:
yetone
2026-11-06 17:22:52 +08:00
co-authored by Flandern1211
parent 8b4029adfe
commit e8df78f33e
12 changed files with 862 additions and 48 deletions
File diff suppressed because one or more lines are too long
+3
View File
@@ -5036,6 +5036,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
tries := 0 // the request's tries, as its route lists them
s.trace.update(tr, func(t *Route) {
t.Done, t.Status, t.Error, t.Millis = true, call.Status, call.Error, call.Millis
// the id the agent reads beside the reply, so the session that
// keeps it can be found after the fact (dsh's replays)
t.ResponseID = call.Usage.ResponseID
tries = len(t.Tries) + reasked
if t.TitleLink != nil && isTitleKind(t.Kind) && call.Status < 400 && call.Error == "" && !call.ResponseTruncated {
link := *t.TitleLink
+37
View File
@@ -139,3 +139,40 @@ func TestGatewayPersistsTranslatedClientResponseID(t *testing.T) {
})
}
}
// A done route keeps the id of the reply the client was given: the agent
// stores that id with the reply it keeps (dsh's replay state), so the
// session that made the request can be found again after the fact even
// when its conversation opening is one a fork copied.
func TestDoneRouteKeepsTheClientResponseID(t *testing.T) {
for _, stream := range []bool{false, true} {
t.Run(map[bool]string{true: "stream", false: "json"}[stream], func(t *testing.T) {
fresh(t)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Write([]byte("data: {\"id\":\"chatcmpl-upstream\",\"model\":\"model\",\"choices\":[{\"delta\":{\"content\":\"answer\"}}]}\n\ndata: {\"id\":\"chatcmpl-upstream\",\"choices\":[],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":2}}\n\ndata: [DONE]\n\n"))
}))
defer up.Close()
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Chat: up.URL + "/v1", Models: []string{"model"}}); err != nil {
t.Fatal(err)
}
body := `{"model":"fake/model","input":"hi","stream":` + map[bool]string{true: "true", false: "false"}[stream] + `}`
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
id := clientResponseID(t, provider.Responses, rec.Body.String(), stream)
s.trace.mu.Lock()
got := ""
if n := len(s.trace.routes); n > 0 {
got = s.trace.routes[n-1].ResponseID
}
s.trace.mu.Unlock()
if got == "" || got != id {
t.Fatalf("route's reply id %q, the client's %q", got, id)
}
})
}
}
+6
View File
@@ -184,6 +184,12 @@ type Route struct {
// Conv: the conversation a request without a session id is part of,
// as a digest of its first user turn (conversationID)
Conv string `json:"conv,omitempty"`
// ResponseID: the id of the reply object actually released to the
// client, as the client read it, set when the route is done. The agent
// stores that id with the reply (dsh's replay state), so a request
// whose agent keeps it can be found again after the fact even when its
// conversation opening is one a fork copied (dshConvs)
ResponseID string `json:"responseId,omitempty"`
// Folder: the last two levels of the folder its agent says it works
// in (shortFolder), never the whole path; a request that says none
// takes its session's, as said last (#1068)
+77 -20
View File
@@ -175,6 +175,7 @@ type ctxRec struct {
Time time.Time
Agent, Model, Kind, Sub string
Session, Parent, Conv string
ResponseID string
Done, Failed bool
Asked bool // it has a prompt of some tokens
Tokens, Window, MCP, Cache int
@@ -186,7 +187,7 @@ type ctxRec struct {
// recOf is r as the tab reads it, its whole prompt kept when whole.
func recOf(r gateway.Route, whole bool) ctxRec {
c := ctxRec{ID: r.ID, Time: r.Time, Agent: r.Agent, Model: r.Model, Kind: r.Kind, Sub: r.Sub,
Session: r.Session, Parent: r.ParentSession, Conv: r.Conv, Done: r.Done,
Session: r.Session, Parent: r.ParentSession, Conv: r.Conv, ResponseID: r.ResponseID, Done: r.Done,
Failed: r.Status >= 400 || r.Error != "", Cache: cacheOf(r), CacheKnown: cacheKnown(r)}
if p := r.Prompt; p != nil {
c.Asked = p.Tokens > 0
@@ -267,15 +268,18 @@ func sessionOfRec(r *ctxRec) string {
}
// 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.
// its reply or its conversation id was read from (sessions' ResponseIDs and
// 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). A hash is the conversation's opening, which a fork
// copies, so the reply's own id is asked first: a fork's reply has one its
// source does not, and names the fork. An id two sessions share stays as it
// is.
func joinConvs(routes []ctxRec, list func() []sessions.Session) {
loose := false
for _, r := range routes {
if r.Session == "" && r.Parent == "" && r.Conv != "" {
if r.Session == "" && r.Parent == "" && (r.ResponseID != "" || r.Conv != "") {
loose = true
break
}
@@ -283,29 +287,82 @@ func joinConvs(routes []ctxRec, list func() []sessions.Session) {
if !loose {
return
}
of := convOwners(list())
of := routeOwners(list())
for i, r := range routes {
if r.Session == "" && r.Parent == "" && r.Conv != "" {
if id := of[r.Agent+"\x00"+r.Conv]; id != "" {
if r.Session == "" && r.Parent == "" {
if id := ownerOf(r.Agent, r.ResponseID, r.Conv, of); id != "" {
routes[i].Session = id
}
}
}
}
// convOwners is each agent's conversation id (agent, NUL, the gateway's
// id) and the session of that agent it was read from (sessions' Convs);
// "" for an id two sessions share, which stays as it is.
func convOwners(list []sessions.Session) map[string]string {
// ownerOf is the session an agent's route that names none belongs to: the
// one whose own replies carry the route's reply id, and, when no one's does,
// the one whose conversation the route opens. A reply id is the vendor's,
// which some give out again (Ollama's chatcmpl-<0-998>), so it names a
// session over the opening only where the two agree: the opening is no
// one's, or two sessions', or the reply's session's own, or one it was
// forked from (sessions' ForkOf). Another session's opening goes by the
// opening, as it did before reply ids were read.
func ownerOf(agent, responseID, conv string, of map[string]string) string {
opened := ""
if conv != "" {
opened = of[ownerKey(agent, ownerConv, conv)]
}
if responseID != "" {
if id := of[ownerKey(agent, ownerResponse, responseID)]; id != "" && (opened == "" || forkedFrom(agent, id, opened, of)) {
return id
}
}
return opened
}
// forkedFrom says session id is from, or a fork of it, or of a fork of it.
func forkedFrom(agent, id, from string, of map[string]string) bool {
for n := 0; id != "" && n < 64; n++ {
if id == from {
return true
}
id = of[ownerKey(agent, ownerFork, id)]
}
return false
}
// The kinds of id a route without a session id is named by: the reply it
// got, and the conversation it opens; and a session's source, for the
// session a fork's reply names (ForkOf).
const (
ownerResponse = "response"
ownerConv = "conv"
ownerFork = "fork"
)
func ownerKey(agent, kind, id string) string { return agent + "\x00" + kind + "\x00" + id }
// routeOwners is each agent's reply ids and conversation ids (agent, NUL,
// kind, NUL, the id) and the session of that agent each was read from
// (sessions' ResponseIDs and Convs); "" for an id two sessions share, which
// stays as it is. A fork's session id is kept with the one it was forked
// from (ownerFork).
func routeOwners(list []sessions.Session) map[string]string {
of := map[string]string{}
put := func(k, id string) {
if was, ok := of[k]; ok && was != id {
of[k] = ""
} else if !ok {
of[k] = id
}
}
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
}
put(ownerKey(s.Agent, ownerConv, c), s.ID)
}
for _, r := range s.ResponseIDs {
put(ownerKey(s.Agent, ownerResponse, r), s.ID)
}
if s.ForkOf != "" {
of[ownerKey(s.Agent, ownerFork, s.ID)] = s.ForkOf
}
}
return of
+80
View File
@@ -0,0 +1,80 @@
package gui
import (
"os"
"path/filepath"
"strconv"
"testing"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/sessions"
)
// The Context page names a dsh fork's requests as Routing does: by the reply
// each got (Route.ResponseID), where the conversation's opening is the
// source's. A request of the source's own still opens under the source.
func TestContextTellsAForkByItsReply(t *testing.T) {
sandboxHome(t)
home := t.TempDir()
t.Setenv("DSH_HOME", home)
sessions.Reset()
t.Cleanup(sessions.Reset)
const opening = `{"type":"user/message","seq":1,"time":1000,"data":{"source":{"kind":"user"},"content":[{"type":"text","text":"same first prompt"}]}}`
const endSeed = `{"type":"session/end-seed","seq":2,"time":1000,"data":{"inherited":true}}`
reply := func(seq int, id string) string {
return `{"type":"assistant/message","seq":` + strconv.Itoa(seq) + `,"time":1000,"data":{"message":{"source":{"provider":"magpie","model":"group/flash","replayState":{"response":{"provider":"magpie","responseId":"` + id + `"}}}}}}`
}
write := func(name, header string, lines ...string) {
dir := filepath.Join(home, "sessions", "proj", name)
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
b := header + "\n"
for _, l := range lines {
b += l + "\n"
}
if err := os.WriteFile(filepath.Join(dir, "session.v4.jsonl"), []byte(b), 0o600); err != nil {
t.Fatal(err)
}
}
write("session-source", `{"type":"session","version":4,"id":"session-source","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":false}`,
opening, reply(2, "reply-source"))
write("session-fork", `{"type":"session","version":4,"id":"session-fork","cwd":"/w","createdAt":1000,"delegationDepth":0,"parentSession":"session-source","isSeeded":true}`,
opening, reply(2, "reply-source"), endSeed, reply(4, "reply-fork"))
var openingHash string
for _, s := range sessions.List(0) {
if s.ID == "session-source" && len(s.Convs) > 0 {
openingHash = s.Convs[0]
}
}
if openingHash == "" {
t.Fatal("the fixture session names no conversation id")
}
conv := func(id int64, c string) gateway.Route {
r := ctxRoute(id, "dsh", "", 20000, int(1000*id), 128000, 0)
r.Conv = c
return r
}
fork := conv(1, openingHash)
fork.ResponseID = "reply-fork"
source := conv(2, openingHash)
source.ResponseID = "reply-source"
loose := conv(3, openingHash)
out := contextOf([]gateway.Route{fork, source, loose}, 7)
keys := map[string]string{}
for _, s := range out.Sessions {
keys[s.Key] = s.Title
}
// the fork's own turn is the fork; the source's is the source; the
// opening alone is the source's, whose it is
for _, k := range []string{"session-fork", "session-source"} {
if _, ok := keys[k]; !ok {
t.Fatalf("no %s among %v", k, keys)
}
}
if len(keys) != 2 {
t.Fatalf("sessions %v, want the fork and its source", keys)
}
}
+302
View File
@@ -0,0 +1,302 @@
package gui
import (
"bufio"
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
)
// #5491 (Flandern1211): a dsh fork's requests were listed under the session
// it was forked from. Here the requests are real dsh 0.2.0-rc.2's, captured
// on its chat-completions route (sessions' testdata/dsh-gateway), sent
// through the gateway twice, byte for byte the same as a fork's and its
// source's are. The vendor answers on the messages protocol and streams, so
// the id dsh reads is magpie's translation of the vendor's. The first reply
// is written into the source's file, the second into a fork of it made as
// dsh's buildForkSeed makes one: the source's events up to the boundary, a
// session/end-seed, then its own turn, under a header naming parentSession.
func TestDshForkNamedByTheReplyTheGatewayGave(t *testing.T) {
sandboxHome(t)
fixture := filepath.Join("..", "sessions", "testdata", "dsh-gateway")
const source = "session-508e7b0a-37c0-41f7-ac62-e48ab3146111"
const fork = "session-5e1c0f3a-8d2b-4c6e-9a71-2f4b6d8e0c13"
var n atomic.Int32
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
if !strings.HasSuffix(r.URL.Path, "/messages") {
http.Error(w, "messages only", 404)
return
}
id := "msg_up" + string(rune('0'+n.Add(1)))
w.Header().Set("Content-Type", "text/event-stream")
for _, ev := range []string{
`{"type":"message_start","message":{"id":"` + id + `","type":"message","role":"assistant","model":"m1","content":[],"usage":{"input_tokens":9,"output_tokens":0}}}`,
`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Done."}}`,
`{"type":"content_block_stop","index":0}`,
`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`,
`{"type":"message_stop"}`,
} {
var typ struct{ Type string }
json.Unmarshal([]byte(ev), &typ)
io.WriteString(w, "event: "+typ.Type+"\ndata: "+ev+"\n\n")
}
}))
defer up.Close()
if err := provider.Save(provider.Provider{ID: "fake", Name: "FAKE", Key: "k", Models: []string{"m1"}, Anthropic: up.URL}); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(filepath.Join(fixture, "requests", "completions-turn.json"))
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)
}
// only the model is changed, to one this gateway has
body = bytes.Replace(body, []byte(`"model":"group/flash"`), []byte(`"model":"fake/m1"`), 1)
s := gateway.New()
ask := func() string {
t.Helper()
r := httptest.NewRequest("POST", captured.Path, bytes.NewReader(body))
for k, v := range captured.Headers {
r.Header.Set(k, v)
}
r.Header.Del("Content-Length")
r.Header.Del("Accept-Encoding")
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("%d %.300s", w.Code, w.Body)
}
// the id dsh reads: its chunks' (pi-ai's responseId)
sc := bufio.NewScanner(w.Body)
for sc.Scan() {
var c struct{ ID string }
if d, ok := strings.CutPrefix(sc.Text(), "data: "); ok && json.Unmarshal([]byte(d), &c) == nil && c.ID != "" {
return c.ID
}
}
t.Fatal("no reply id in the stream")
return ""
}
sourceReply, forkReply := ask(), ask()
if sourceReply == forkReply || strings.HasPrefix(sourceReply, "msg_") {
t.Fatalf("client ids %q, %q: not two chat-completions ids", sourceReply, forkReply)
}
routes := s.Trace(context.Background(), 0, 0).Routes
if len(routes) != 2 || routes[0].Conv == "" || routes[0].Conv != routes[1].Conv {
t.Fatalf("routes %+v: want two of one conversation", routes)
}
for _, r := range routes {
if r.Agent != "dsh" || r.Session != "" {
t.Fatalf("route %d: agent %q session %q", r.ID, r.Agent, r.Session)
}
if r.ResponseID != sourceReply && r.ResponseID != forkReply {
t.Fatalf("route %d keeps %q, the client read %q or %q", r.ID, r.ResponseID, sourceReply, forkReply)
}
}
// dsh writes the replies down: the source's own, then the fork's
home := t.TempDir()
if err := os.CopyFS(filepath.Join(home, "sessions"), os.DirFS(filepath.Join(fixture, "sessions"))); err != nil {
t.Fatal(err)
}
t.Setenv("DSH_HOME", home)
srcPath := filepath.Join(home, "sessions", "--work-proj--", source, "session.v4.jsonl")
src, err := os.ReadFile(srcPath)
if err != nil {
t.Fatal(err)
}
src = bytes.Replace(src, []byte(`"responseId":"c1"`), []byte(`"responseId":"`+sourceReply+`"`), 1)
if err := os.WriteFile(srcPath, src, 0o600); err != nil {
t.Fatal(err)
}
writeDshFork(t, filepath.Join(home, "sessions", "--work-proj--", fork), fork, source, src, forkReply)
sessions.Reset()
t.Cleanup(sessions.Reset)
resetRouteConvs(t)
// old history: a route from before reply ids were kept
old := routes[0]
old.ID, old.ResponseID = 99, ""
want := map[string]string{sourceReply: source, forkReply: fork, "": source}
priced := pricedRoutes(append(routes, old))
for _, r := range priced {
if w := want[r.ResponseID]; r.Session != w {
t.Errorf("Routing: route %d (reply %q) under %q, want %q", r.ID, r.ResponseID, r.Session, w)
}
}
out := contextOf(append(routes, old), 7)
keys := map[string]bool{}
for _, s := range out.Sessions {
keys[s.Key] = true
}
if !keys[source] || !keys[fork] || len(keys) != 2 {
t.Errorf("Context: sessions %v, want %s and %s", keys, source, fork)
}
}
// A reply id is the vendor's, and some vendors give one out again (Ollama's
// chatcmpl-<0-998>): a route that opens another session's conversation
// stays that session's though its reply's id is one a fork kept.
func TestDshReplyIDOfAnotherConversationNamesNoOne(t *testing.T) {
sandboxHome(t)
of := routeOwners([]sessions.Session{
{Agent: "dsh", ID: "source", Convs: []string{"magpie-open"}, ResponseIDs: []string{"chatcmpl-1"}},
{Agent: "dsh", ID: "fork", ForkOf: "source", ResponseIDs: []string{"chatcmpl-217"}},
{Agent: "dsh", ID: "fork2", ForkOf: "fork", ResponseIDs: []string{"chatcmpl-5"}},
{Agent: "dsh", ID: "other", Convs: []string{"magpie-other"}, ResponseIDs: []string{"chatcmpl-9"}},
})
for _, c := range []struct{ reply, conv, want string }{
{"chatcmpl-217", "magpie-open", "fork"}, // the fork's own turn
{"chatcmpl-5", "magpie-open", "fork2"}, // a fork of the fork
{"chatcmpl-217", "magpie-other", "other"}, // another conversation's, the same id
{"chatcmpl-9", "magpie-open", "source"}, // another's id on the source's opening
{"chatcmpl-217", "magpie-unknown", "fork"},
{"chatcmpl-unknown", "magpie-open", "source"},
{"", "magpie-open", "source"},
} {
if got := ownerOf("dsh", c.reply, c.conv, of); got != c.want {
t.Errorf("reply %s, conv %s: %q, want %q", c.reply, c.conv, got, c.want)
}
}
}
// The Routing page polls every second or two. A dsh reply whose id dsh never
// writes down (a title call's, one that failed) is listed nowhere, and the
// sessions were listed again every convsFresh for as long as such a route
// was on the page; a route's reply is waited for only convsKept after it
// ended.
func TestRoutingWaitsForAReplyIDOnlyAWhile(t *testing.T) {
sandboxHome(t)
t.Setenv("DSH_HOME", t.TempDir())
sessions.Reset()
t.Cleanup(sessions.Reset)
resetRouteConvs(t)
now := time.Now()
conv := ownerKey("dsh", ownerConv, "magpie-open")
built := now.Add(-3 * convsFresh)
routeConvs.Lock()
routeConvs.of, routeConvs.at = map[string]string{conv: "source"}, built
routeConvs.Unlock()
listed := func(r gateway.Route) bool {
routeSessions(true, looseKeys(r, now))
routeConvs.Lock()
defer routeConvs.Unlock()
again := !routeConvs.at.Equal(built)
routeConvs.of, routeConvs.at = map[string]string{conv: "source"}, built
return again
}
old := gateway.Route{Agent: "dsh", Conv: "magpie-open", ResponseID: "chatcmpl-title", Done: true, Time: now.Add(-2 * convsKept), Millis: 900}
if listed(old) {
t.Fatal("a route ended long ago, whose reply id no session has, listed the sessions again")
}
recent := old
recent.Time = now.Add(-5 * time.Second)
if !listed(recent) {
t.Fatal("a route just ended, its reply not yet listed, did not list the sessions again")
}
}
func resetRouteConvs(t *testing.T) {
reset := func() {
routeConvs.Lock()
routeConvs.of, routeConvs.at = nil, time.Time{}
routeConvs.Unlock()
}
reset()
t.Cleanup(reset)
}
// writeDshFork writes a fork of the session file src as dsh does
// (buildForkSeed, api-session-controller's fork): every event of src, a
// session/end-seed after them at the last one's time, then a turn of its
// own whose reply has the id given, copied from src's own reply.
func writeDshFork(t *testing.T, dir, id, parent string, src []byte, reply string) {
t.Helper()
lines := bytes.Split(bytes.TrimSpace(src), []byte("\n"))
var out bytes.Buffer
out.WriteString(`{"type":"session","version":4,"id":"` + id + `","createdAt":1792664880000,"cwd":"/work/proj","parentSession":"` + parent + `","isSeeded":true}` + "\n")
var last struct {
Seq int `json:"seq"`
Time int64 `json:"time"`
}
var answer []byte
for _, l := range lines[1:] {
out.Write(l)
out.WriteByte('\n')
json.Unmarshal(l, &last)
if bytes.Contains(l, []byte(`"type":"assistant/message"`)) {
answer = l
}
}
if answer == nil {
t.Fatal("the source has no reply to copy")
}
seq, n := last.Seq+1, strconv.Itoa
out.WriteString(`{"type":"session/end-seed","seq":` + n(seq) + `,"time":` + strconv.FormatInt(last.Time, 10) + `,"data":{"inherited":true}}` + "\n")
seq++
out.WriteString(`{"type":"user/message","seq":` + n(seq) + `,"time":` + strconv.FormatInt(last.Time+int64(seq), 10) + `,"data":{"content":[{"type":"text","text":"Now the tests"}],"source":{"kind":"user"},"role":"user","id":"0b7c1d2e-3f40-4a51-8b62-7c83d94ea5f6"},"surfaceOp":"append"}` + "\n")
seq++
var at struct {
Seq int `json:"seq"`
Time int64 `json:"time"`
}
json.Unmarshal(answer, &at)
was := `"seq":` + n(at.Seq) + `,"time":` + strconv.FormatInt(at.Time, 10)
if !bytes.Contains(answer, []byte(was)) {
t.Fatalf("the source's reply has no %s", was)
}
own := bytes.Replace(answer, []byte(was), []byte(`"seq":`+n(seq)+`,"time":`+strconv.FormatInt(last.Time+int64(seq), 10)), 1)
// the reply's own id (replayState.response.responseId), wherever it sits
var ids struct {
Data struct {
Message struct {
Source struct {
ReplayState struct {
Response struct {
ResponseID string `json:"responseId"`
} `json:"response"`
} `json:"replayState"`
} `json:"source"`
} `json:"message"`
} `json:"data"`
}
json.Unmarshal(answer, &ids)
from := ids.Data.Message.Source.ReplayState.Response.ResponseID
if from == "" {
t.Fatal("the source's reply has no responseId")
}
own = bytes.ReplaceAll(own, []byte(`"responseId":"`+from+`"`), []byte(`"responseId":"`+reply+`"`))
out.Write(own)
out.WriteByte('\n')
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "session.v4.jsonl"), out.Bytes(), 0o600); err != nil {
t.Fatal(err)
}
}
+44 -23
View File
@@ -97,17 +97,19 @@ func pricedRoutes(routes []gateway.Route) []routeJSON {
}
titles := sessions.CodexTitles(ids)
var loose []string
need, now := false, time.Now()
for _, r := range routes {
if k := looseConv(r); k != "" {
loose = append(loose, k)
}
need = need || looseRoute(r)
loose = append(loose, looseKeys(r, now)...)
}
owners := convSessions(loose)
owners := routeSessions(need, loose)
pub := publicRefs()
for _, r := range routes {
r = publicRoute(r, pub)
if k := looseConv(r); k != "" && owners[k] != "" {
r.Session = owners[k]
if looseRoute(r) {
if id := ownerOf(r.Agent, r.ResponseID, r.Conv, owners); id != "" {
r.Session = id
}
}
r.Usage = cacheCounted(r.Usage)
recs := make([]usage.Record, len(r.Usage))
@@ -131,25 +133,43 @@ func pricedRoutes(routes []gateway.Route) []routeJSON {
}
// convAgents are the agents whose own session files say which of the
// gateway's conversation ids are theirs (sessions' Convs): dsh's, whose
// chat-completions and messages routes send no session id
// (changqiu4890 on Discord: Routing put every dsh request under "No
// session ID").
// gateway's reply and conversation ids are theirs (sessions' ResponseIDs
// and Convs): dsh's, whose chat-completions and messages routes send no
// session id (changqiu4890 on Discord: Routing put every dsh request under
// "No session ID").
var convAgents = map[string]bool{"dsh": true}
// looseConv is the agent and conversation id (convOwners' key) of a route
// of such an agent that names no session, "" for any other.
func looseConv(r gateway.Route) string {
if r.Session != "" || r.ParentSession != "" || r.Conv == "" || !convAgents[r.Agent] {
return ""
// looseKeys are the agent and ids (ownerKey's) a route of such an agent
// that names no session is to be found by, and whose absence from the
// listing means it is behind: its conversation's, and its reply's while
// dsh may still be writing the reply down — up to convsKept after the
// route ended. A reply dsh keeps no id of (a title call's, a refusal's)
// is never listed, and the page polls every second or two: past that it
// would list every agent's sessions again each convsFresh. None for any
// other route.
func looseKeys(r gateway.Route, now time.Time) []string {
if !looseRoute(r) {
return nil
}
return r.Agent + "\x00" + r.Conv
var out []string
if r.ResponseID != "" && r.Done && now.Sub(r.Time.Add(time.Duration(r.Millis)*time.Millisecond)) < convsKept {
out = append(out, ownerKey(r.Agent, ownerResponse, r.ResponseID))
}
if r.Conv != "" {
out = append(out, ownerKey(r.Agent, ownerConv, r.Conv))
}
return out
}
// routeConvs is convOwners of the sessions listed, for every trace the
// looseRoute says r is a route of such an agent that names no session.
func looseRoute(r gateway.Route) bool {
return r.Session == "" && r.ParentSession == "" && convAgents[r.Agent] && (r.ResponseID != "" || r.Conv != "")
}
// routeConvs is routeOwners of the sessions listed, for every trace the
// Routing page polls: listing the sessions reads every agent's folder, so
// it is made again only when it is convsKept old, or convsFresh old and a
// route's conversation isn't in it (a session begun since).
// route's id isn't in it (a reply or a session begun since).
var routeConvs struct {
sync.Mutex
at time.Time
@@ -158,10 +178,11 @@ var routeConvs struct {
var convsFresh, convsKept = 2 * time.Second, time.Minute
// convSessions is convOwners for keys (looseConv's), nil when there are
// none, so a page with no such route lists nothing.
func convSessions(keys []string) map[string]string {
if len(keys) == 0 {
// routeSessions is routeOwners for the routes of a page that has a route
// that names no session (need), nil for one with none, so it lists
// nothing; keys are looseKeys'.
func routeSessions(need bool, keys []string) map[string]string {
if !need {
return nil
}
routeConvs.Lock()
@@ -177,7 +198,7 @@ func convSessions(keys []string) map[string]string {
}
}
if stale {
routeConvs.of, routeConvs.at = convOwners(sessions.List(0)), time.Now()
routeConvs.of, routeConvs.at = routeOwners(sessions.List(0)), time.Now()
}
return routeConvs.of
}
+85
View File
@@ -0,0 +1,85 @@
package gui
import (
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/sessions"
)
// A dsh fork copies its source's conversation, so the hash of the opening
// names both sessions and names neither: Routing showed the source for the
// fork's own requests too, or nothing at all. The reply's id is the fork's
// own — dsh keeps the one magpie's gateway put on it — and names it
// (Route.ResponseID, sessions' ResponseIDs).
func TestRoutingTellsAForkByItsReply(t *testing.T) {
sandboxHome(t)
home := t.TempDir()
t.Setenv("DSH_HOME", home)
sessions.Reset()
t.Cleanup(sessions.Reset)
resetRouteConvs := func() {
routeConvs.Lock()
routeConvs.of, routeConvs.at = nil, time.Time{}
routeConvs.Unlock()
}
resetRouteConvs()
t.Cleanup(resetRouteConvs)
defer func(f, k time.Duration) { convsFresh, convsKept = f, k }(convsFresh, convsKept)
convsFresh = 0
const opening = `{"type":"user/message","seq":1,"time":1000,"data":{"source":{"kind":"user"},"content":[{"type":"text","text":"same first prompt"}]}}`
const endSeed = `{"type":"session/end-seed","seq":2,"time":1000,"data":{"inherited":true}}`
reply := func(seq int, id string) string {
return `{"type":"assistant/message","seq":` + strconv.Itoa(seq) + `,"time":1000,"data":{"message":{"source":{"provider":"magpie","model":"group/flash","replayState":{"response":{"provider":"magpie","responseId":"` + id + `"}}}}}}`
}
write := func(name, header string, lines ...string) {
dir := filepath.Join(home, "sessions", "proj", name)
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
b := header + "\n"
for _, l := range lines {
b += l + "\n"
}
if err := os.WriteFile(filepath.Join(dir, "session.v4.jsonl"), []byte(b), 0o600); err != nil {
t.Fatal(err)
}
}
write("session-source", `{"type":"session","version":4,"id":"session-source","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":false}`,
opening, reply(2, "reply-source"))
write("session-fork", `{"type":"session","version":4,"id":"session-fork","cwd":"/w","createdAt":1000,"delegationDepth":0,"parentSession":"session-source","isSeeded":true}`,
opening, reply(2, "reply-source"), endSeed, reply(4, "reply-fork"))
var openingHash string
for _, s := range sessions.List(0) {
if s.ID == "session-source" && len(s.Convs) > 0 {
openingHash = s.Convs[0]
}
}
if openingHash == "" {
t.Fatal("the fixture session names no conversation id")
}
routes := []gateway.Route{
{ID: 1, Agent: "dsh", Conv: openingHash, ResponseID: "reply-fork"}, // the fork's own turn
{ID: 2, Agent: "dsh", Conv: openingHash}, // the opening alone: its source's
{ID: 3, Agent: "dsh", Conv: openingHash, ResponseID: "reply-source"}, // the source's
{ID: 4, Agent: "dsh", ResponseID: "reply-fork"}, // the reply alone
}
got := map[int64]string{}
for _, r := range pricedRoutes(routes) {
got[r.ID] = r.Session
}
// 2 is the opening alone: the fork's inherited copy of it is its
// source's (the seed ends before its own turns), so it names the source
want := map[int64]string{1: "session-fork", 2: "session-source", 3: "session-source", 4: "session-fork"}
for id, w := range want {
if got[id] != w {
t.Errorf("route %d: session %q, want %q", id, got[id], w)
}
}
}
+11
View File
@@ -204,6 +204,10 @@ type dshResponse struct {
Model string `json:"model"`
Provider string `json:"provider"`
ResponseModel string `json:"responseModel"`
// ResponseID is the id of the reply object the vendor's own response
// carried, as dsh read it: the same id magpie's gateway wrote on the
// route that served it (Route.ResponseID)
ResponseID string `json:"responseId"`
}
// dshReplay is a reply's replay state, where dsh keeps what the vendor's own
@@ -374,6 +378,13 @@ func dshCount(s *state, h *dshHead, b []byte, main bool) {
if h.Version < 2 && e.Seq != nil && *e.Seq < h.SeedLength {
return
}
if e.Type == "assistant/message" && main {
if src := e.Data.Message.Source; dshGatewayProvider(src) {
if id := src.ReplayState.Response.ResponseID; id != "" {
s.ResponseIDs = append(s.ResponseIDs, id)
}
}
}
at := ms(e.Time)
s.saw(at, main)
switch {
+189
View File
@@ -0,0 +1,189 @@
package sessions
import (
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
)
// dshReply is an assistant/message line holding a reply's replay state, as
// dsh writes it: the id is the one the gateway put on the reply.
func dshReplyWithID(seq int, id string) string {
return `{"type":"assistant/message","seq":` + strconv.Itoa(seq) + `,"time":1000,"data":{"message":{"source":{"provider":"magpie","model":"group/flash","replayState":{"response":{"kind":"pi-ai","version":2,"api":"openai-completions","provider":"magpie","model":"group/flash","responseId":"` + id + `","stopReason":"stop"}}}}}}`
}
// dshSessionFile writes a session file with the lines given and parses it.
func dshSessionFile(t *testing.T, lines []string) *state {
t.Helper()
p := filepath.Join(t.TempDir(), "session.jsonl")
b := ""
for _, l := range lines {
b += l + "\n"
}
if err := os.WriteFile(p, []byte(b), 0o600); err != nil {
t.Fatal(err)
}
st, err := os.Stat(p)
if err != nil {
t.Fatal(err)
}
return parseDsh(file{agent: "dsh", path: p, main: true, size: st.Size(), mod: st.ModTime()}, nil)
}
func TestDshResponseIDsSkipTheSeed(t *testing.T) {
head := `{"type":"session","version":4,"id":"session-child","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":true}`
s := dshSessionFile(t, []string{
head,
dshReplyWithID(1, "inherited-1"),
dshReplyWithID(2, "inherited-2"),
`{"type":"session/end-seed","seq":3,"time":1000,"data":{"inherited":true}}`,
dshReplyWithID(4, "own-1"),
dshReplyWithID(5, "own-2"),
})
if want := []string{"own-1", "own-2"}; !slices.Equal(s.ResponseIDs, want) {
t.Fatalf("fork's own replies: %v, want %v", s.ResponseIDs, want)
}
}
// A file in the format before session/end-seed marks its inherited events by
// seq: those are its source's, not its own.
func TestDshResponseIDsSkipTheSeedLength(t *testing.T) {
head := `{"type":"session","version":1,"id":"session-old","cwd":"/w","createdAt":1000,"seedLength":2,"isSeeded":true}`
s := dshSessionFile(t, []string{
head,
dshReplyWithID(0, "inherited"),
dshReplyWithID(1, "inherited-2"),
dshReplyWithID(2, "own"),
})
if want := []string{"own"}; !slices.Equal(s.ResponseIDs, want) {
t.Fatalf("fork's own replies: %v, want %v", s.ResponseIDs, want)
}
}
// A session that is no fork owns every reply of its own.
func TestDshResponseIDsOfASession(t *testing.T) {
head := `{"type":"session","version":4,"id":"session-plain","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":false}`
s := dshSessionFile(t, []string{
head,
dshReplyWithID(1, "a"),
dshReplyWithID(2, "b"),
})
if want := []string{"a", "b"}; !slices.Equal(s.ResponseIDs, want) {
t.Fatalf("replies: %v, want %v", s.ResponseIDs, want)
}
}
// A reply dsh did not get from magpie's gateway is no route's to name: its id
// would match nothing, and is not kept.
func TestDshResponseIDsOnlyFromTheGateway(t *testing.T) {
head := `{"type":"session","version":4,"id":"session-plain","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":false}`
s := dshSessionFile(t, []string{
head,
`{"type":"assistant/message","seq":1,"time":1000,"data":{"message":{"source":{"provider":"deepseek","model":"deepseek-v4","replayState":{"response":{"provider":"deepseek","responseId":"vendor-1"}}}}}}`,
dshReplyWithID(2, "gw-1"),
})
if want := []string{"gw-1"}; !slices.Equal(s.ResponseIDs, want) {
t.Fatalf("replies: %v, want %v", s.ResponseIDs, want)
}
}
// A fork read before its seed's end lets its source's replies stand for it
// for that read; the marker, arriving later, takes them back (TestDshCalls-
// EndSeedAcrossReads reads the calls the same way).
func TestDshResponseIDsEndSeedAcrossReads(t *testing.T) {
head := `{"type":"session","version":4,"id":"session-child","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":true}`
dir := t.TempDir()
p := filepath.Join(dir, "session.jsonl")
write := func(lines ...string) {
f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if err != nil {
t.Fatal(err)
}
defer f.Close()
for _, l := range lines {
if _, err := f.WriteString(l + "\n"); err != nil {
t.Fatal(err)
}
}
}
f := func() file {
st, err := os.Stat(p)
if err != nil {
t.Fatal(err)
}
return file{agent: "dsh", path: p, main: true, size: st.Size(), mod: st.ModTime()}
}
write(head, dshReplyWithID(1, "inherited"))
first := parseDsh(f(), nil)
if len(first.ResponseIDs) != 1 {
t.Fatalf("before the marker: %v", first.ResponseIDs)
}
write(`{"type":"session/end-seed","seq":2,"time":1000,"data":{"inherited":true}}`, dshReplyWithID(3, "own"))
next := parseDsh(f(), first)
if want := []string{"own"}; !slices.Equal(next.ResponseIDs, want) {
t.Fatalf("after the marker: %v, want %v", next.ResponseIDs, want)
}
}
// A fork of a real dsh 0.2.0-rc.2 session (testdata/dsh-gateway), made as
// dsh's buildForkSeed makes one: the source's events, a session/end-seed,
// then its own turn, under a header naming the source (parentSession). The
// listing gives the fork its own reply only and the source its own, and
// names the source the fork was made from (ForkOf).
func TestDshForkOfARealSessionListsItsOwnReplies(t *testing.T) {
const source, fork = "session-508e7b0a-37c0-41f7-ac62-e48ab3146111", "session-5e1c0f3a-8d2b-4c6e-9a71-2f4b6d8e0c13"
manageSetup(t)
home := filepath.Join(t.TempDir(), "dsh")
if err := os.CopyFS(filepath.Join(home, "sessions"), os.DirFS(filepath.Join("testdata", "dsh-gateway", "sessions"))); err != nil {
t.Fatal(err)
}
src, err := os.ReadFile(filepath.Join(home, "sessions", "--work-proj--", source, "session.v4.jsonl"))
if err != nil {
t.Fatal(err)
}
lines := strings.Split(strings.TrimSpace(string(src)), "\n")
answer := ""
for _, l := range lines {
if strings.Contains(l, `"type":"assistant/message"`) {
answer = l
}
}
// the source's last event is seq 17 at 1792664874100
b := `{"type":"session","version":4,"id":"` + fork + `","createdAt":1792664880000,"cwd":"/work/proj","parentSession":"` + source + `","isSeeded":true}` + "\n" +
strings.Join(lines[1:], "\n") + "\n" +
`{"type":"session/end-seed","seq":18,"time":1792664874100,"data":{"inherited":true}}` + "\n" +
`{"type":"user/message","seq":19,"time":1792664880100,"data":{"content":[{"type":"text","text":"Now the tests"}],"source":{"kind":"user"},"role":"user","id":"0b7c1d2e-3f40-4a51-8b62-7c83d94ea5f6"},"surfaceOp":"append"}` + "\n" +
strings.NewReplacer(`"seq":14,"time":1792664874092`, `"seq":20,"time":1792664880200`, `"responseId":"c1"`, `"responseId":"chatcmpl-fork1"`).Replace(answer) + "\n"
if !strings.Contains(b, `"seq":20,`) || !strings.Contains(b, "chatcmpl-fork1") {
t.Fatal("the fixture's reply is not the one this fork copies")
}
dir := filepath.Join(home, "sessions", "--work-proj--", fork)
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "session.v4.jsonl"), []byte(b), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("DSH_HOME", home)
ageDsh(home)
Reset()
byID := map[string]Session{}
for _, s := range List(0) {
if s.Agent == "dsh" {
byID[s.ID] = s
}
}
if got := byID[source].ResponseIDs; !slices.Equal(got, []string{"c1"}) {
t.Errorf("source's replies %v, want [c1]", got)
}
f := byID[fork]
if !slices.Equal(f.ResponseIDs, []string{"chatcmpl-fork1"}) || f.ForkOf != source || len(f.Convs) != 0 {
t.Errorf("fork's replies %v, forked from %q, convs %v; want its own reply, from %s, no opening of its own", f.ResponseIDs, f.ForkOf, f.Convs, source)
}
if byID[source].ForkOf != "" {
t.Errorf("the source is forked from %q", byID[source].ForkOf)
}
}
+27 -4
View File
@@ -156,6 +156,16 @@ type Session struct {
// 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:"-"`
// ResponseIDs are the ids of the replies the session's own requests
// got, as the gateway wrote them on its routes and the agent kept them
// with the reply (dsh's replay state): a fork's inherited replies are
// its source's, and are not counted here (Route.ResponseID)
ResponseIDs []string `json:"-"`
// ForkOf is the session a dsh fork was seeded from (its header's
// parentSession, isSeeded): the fork's requests open as that one's do,
// so a reply id that names the fork is taken over the opening only for
// a fork of the opening's session (gui's ownerOf)
ForkOf string `json:"-"`
// Copies are the ids of the sessions that are copies of its
// conversation, not listed apart from it (ccCopies)
Copies []string `json:"-"`
@@ -215,9 +225,14 @@ type state struct {
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 named[Tokens] `json:"models,omitempty"`
// ResponseIDs are the ids of the replies its own requests got, as the
// gateway wrote them on its routes and the agent kept them with the
// reply (dsh's replay state): they name a request after the fact, where
// a conversation id is only its opening (Route.ResponseID)
ResponseIDs []string `json:"response_ids,omitempty"`
Start time.Time `json:"start"`
Last time.Time `json:"last"`
Models named[Tokens] `json:"models,omitempty"`
// Days is Models again, split by the local date each message was
// written on: a session that runs past midnight counts on both days.
Days named[*day] `json:"days,omitempty"`
@@ -378,6 +393,7 @@ func (s *state) clone() *state {
c.Total = &t
}
c.Convs = slices.Clone(s.Convs)
c.ResponseIDs = slices.Clone(s.ResponseIDs)
c.CodexSpawnNames = maps.Clone(s.CodexSpawnNames)
c.CodexSpawnConflicts = maps.Clone(s.CodexSpawnConflicts)
c.CodexAgentIDs = maps.Clone(s.CodexAgentIDs)
@@ -1143,7 +1159,10 @@ const cacheVersion = 29
//
// codex 2: only a fork's copies are; its own calls after them are its own,
// whatever their numbers.
var parseVersions = map[string]int{"codex": 3, "zcode": 1}
//
// dsh 1: the ids of the replies its own requests got (ResponseIDs), for
// the routes that carry no session id and an opening a fork copies.
var parseVersions = map[string]int{"codex": 3, "zcode": 1, "dsh": 1}
type cacheFile struct {
Version int `json:"version"`
@@ -1853,6 +1872,10 @@ func assembleListed(fs []file, price func(string) *catalog.Price, codexTitle fun
s.App = "claude-desktop"
}
s.Convs = append(s.Convs, st.Convs...)
s.ResponseIDs = append(s.ResponseIDs, st.ResponseIDs...)
if d := st.Dsh; d != nil && d.Head.IsSeeded && d.Head.DelegationDepth == 0 {
s.ForkOf = d.Head.ParentSession
}
}
if s.Agent == "codex" && st.CodexNickname != "" {
s.Nickname = st.CodexNickname