diff --git a/internal/gui/context.go b/internal/gui/context.go index 15abf283a..b0eb2d1ad 100644 --- a/internal/gui/context.go +++ b/internal/gui/context.go @@ -110,6 +110,10 @@ type ctxJSON struct { Days int `json:"days"` Agents []ctxAgent `json:"agents"` Sessions []ctxSession `json:"sessions"` + // held is set when a call was left out of every session, its reply not + // read yet (ctxRec.Unmatched): the answer then stands only until the + // page's next read, which is after the fork's file has been read again + held bool } // ctxSessions is how many sessions are listed, the latest; ctxPoints how @@ -171,12 +175,18 @@ func mcpTokens(p *gateway.Prompt) int { // at every refresh (Yayoi_no_yume on X: a 1-core server with 962 MB went // down with the tab open). type ctxRec struct { - ID int64 - Time time.Time - Agent, Model, Kind, Sub string - Session, Parent, Conv string - ResponseID string - Done, Failed, Canceled bool + ID int64 + Time time.Time + Millis int64 // how long it took: it ended at Time and this + Agent, Model, Kind, Sub string + Session, Parent, Conv string + ResponseID string + Done, Failed, Canceled bool + // Unmatched is a call whose opening a fork copied too, whose reply names + // no session yet, and that ended too recently for its reply to be read + // (waitingForReply): it is its source's or the fork's, and no evidence + // here says which, so the tab counts it in neither (joinConvs) + Unmatched bool Asked bool // it has a prompt of some tokens Tokens, Window, MCP, Cache int Counted, Tools, CacheKnown bool @@ -186,7 +196,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, + c := ctxRec{ID: r.ID, Time: r.Time, Millis: r.Millis, Agent: r.Agent, Model: r.Model, Kind: r.Kind, Sub: r.Sub, Session: r.Session, Parent: r.ParentSession, Conv: r.Conv, ResponseID: r.ResponseID, Done: r.Done, Failed: r.Status >= 400 || r.Error != "", Canceled: usage.CanceledBy(r.Status, r.Error), Cache: cacheOf(r), CacheKnown: cacheKnown(r)} @@ -277,6 +287,24 @@ func sessionOfRec(r *ctxRec) string { // 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. +// +// An opening a fork copied names neither of the two, though: the source owns +// it (the fork's copy was taken off Convs at its seed's end, sessions' +// SeedConvs), yet the fork's own requests open the same way. A call of theirs +// whose reply dsh hasn't written yet — in flight, or completed a moment +// before, while the page reads the session's file — has nothing to say which +// one it was, and counting it under the source moved the fork's own request +// there: the source's card climbed with every turn of the fork. Such a call +// is left out of both (ctxRec.Unmatched) until its reply names one, which the +// next read of the fork's file does (the answer keeps for as long as one is +// left out). +// +// Only a call that may yet be named is left out: one with a reply id, ended +// within convsKept (waitingForReply). A call without a reply id — dsh's +// history before #5491 recorded them, and a dsh that keeps none — goes by its +// opening as it always did, or the source's own card would lose its history +// and could vanish; and a call whose reply never comes falls back to its +// opening after that window, so the page stops re-reading the sessions for it. func joinConvs(routes []ctxRec, list func() []sessions.Session) { loose := false for _, r := range routes { @@ -289,15 +317,38 @@ func joinConvs(routes []ctxRec, list func() []sessions.Session) { return } of := routeOwners(list()) + now := time.Now() for i, r := range routes { - if r.Session == "" && r.Parent == "" { - if id := ownerOf(r.Agent, r.ResponseID, r.Conv, of); id != "" { - routes[i].Session = id - } + if r.Session != "" || r.Parent != "" { + continue } + id, byReply := ownerBy(r.Agent, r.ResponseID, r.Conv, of) + if !byReply && r.ResponseID != "" && of[ownerKey(r.Agent, ownerResponse, r.ResponseID)] != "" { + // the reply names another conversation, and the guard for a + // vendor's repeated ids keeps the opening: as it did before + // reply ids were read + routes[i].Session = id + continue + } + if !byReply && waitingForReply(&routes[i], sharedOpening(r.Agent, r.Conv, of), now) { + // its opening is the source's and a fork's both, and its reply + // names no one yet: it is neither's until it does + routes[i].Unmatched = true + continue + } + routes[i].Session = id } } +// waitingForReply says a call is one whose reply may still name its session: +// it has a reply id, its opening a fork copied too (shared), and it ended +// within convsKept — the window Routing's looseKeys waits in for the reply +// dsh writes after its file (trace.go). Past that no reply is coming: the +// call goes by its opening, as it did before reply ids were read. +func waitingForReply(r *ctxRec, shared bool, now time.Time) bool { + return shared && r.ResponseID != "" && now.Sub(r.Time.Add(time.Duration(r.Millis)*time.Millisecond)) < convsKept +} + // 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, @@ -308,16 +359,31 @@ func joinConvs(routes []ctxRec, list func() []sessions.Session) { // fork names no parent). 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 { + id, _ := ownerBy(agent, responseID, conv, of) + return id +} + +// ownerBy is ownerOf, and whether the reply named the session rather than +// the opening: a route whose opening a fork copied too, and whose reply names +// no session, belongs to neither (joinConvs). +func ownerBy(agent, responseID, conv string, of map[string]string) (id string, byReply bool) { opened := "" if conv != "" { opened = of[ownerKey(agent, ownerConv, conv)] } if responseID != "" { if id := of[ownerKey(agent, ownerResponse, responseID)]; id != "" && (opened == "" || forkedFrom(agent, id, opened, conv, of)) { - return id + return id, true } } - return opened + return opened, false +} + +// sharedOpening says conv is an opening a fork copied (sessions' SeedConvs): +// the session that owns it and the fork whose seed opened that way both do, +// so the opening alone doesn't say which one a route that opens that way is. +func sharedOpening(agent, conv string, of map[string]string) bool { + return conv != "" && of[ownerKey(agent, ownerCopied, conv)] != "" } // forkedFrom says session id is from, or a fork of it, or of a fork of it: @@ -338,13 +404,16 @@ func forkedFrom(agent, id, from, conv string, of map[string]string) bool { // 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), and the opening a fork's seed -// carried, kept on the fork itself (SeedConvs). +// session a fork's reply names (ForkOf), the opening a fork's seed carried, +// kept on the fork itself (SeedConvs), and that opening kept again among the +// openings a fork copied, which names neither the source nor the fork alone +// (ownerCopied). const ( ownerResponse = "response" ownerConv = "conv" ownerFork = "fork" ownerSeed = "seed" + ownerCopied = "copied" ) func ownerKey(agent, kind, id string) string { return agent + "\x00" + kind + "\x00" + id } @@ -353,7 +422,8 @@ func ownerKey(agent, kind, id string) string { return agent + "\x00" + kind + "\ // 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). +// from (ownerFork), and the openings its seed carried among the openings a +// fork copied (ownerCopied). func routeOwners(list []sessions.Session) map[string]string { of := map[string]string{} put := func(k, id string) { @@ -377,6 +447,7 @@ func routeOwners(list []sessions.Session) map[string]string { // the fork's own record that its seed opened c, the opening // it shares with the session it was copied from of[ownerKey(s.Agent, ownerSeed, s.ID+"\x00"+c)] = s.ID + of[ownerKey(s.Agent, ownerCopied, c)] = s.ID } } return of @@ -507,9 +578,15 @@ func contextOfRecs(routes []ctxRec, days int) ctxJSON { } acc.a.Window = max(acc.a.Window, window) key := sessionOfRec(r) - if key == "" || r.Sub != "" { + if key == "" || r.Sub != "" || r.Unmatched { // a subagent's prompt is its own conversation's, not the - // one whose session id it goes under + // one whose session id it goes under; a call whose opening + // a fork copied is neither's until its reply names one, and + // counting it under the source is what the fork's own card + // climbed with + if r.Unmatched { + out.held = true + } continue } acc.sessions[key] = true @@ -748,6 +825,13 @@ type ctxDay struct { // again after it. const ctxAgain = time.Minute +// ctxWhileUnmatched is how long an answer stands when a call was left out +// of every session, its reply not read yet (ctxRec.Unmatched): the page +// reads every 5 s, and the read after the fork's file is read again names +// it. Only a call within convsKept is left out (waitingForReply), so this +// ends with that window: one whose reply never comes goes by its opening. +const ctxWhileUnmatched = 5 * time.Second + // readingDay, in tests, is told each day the tab reads from the history. var readingDay func(day string) @@ -824,13 +908,18 @@ func contextRecsLocked(r *http.Request, days int) (out []ctxRec, stamp string) { } // contextFor is the tab's answer for the days asked for: the last one -// again when its routes are the same and it isn't ctxAgain old. +// again when its routes are the same and it isn't ctxAgain old, or +// ctxWhileUnmatched old when it left a route out of every session. func contextFor(r *http.Request, days int) ctxJSON { ctxKept.Lock() defer ctxKept.Unlock() recs, stamp := contextRecsLocked(r, days) stamp = strconv.Itoa(days) + "|" + stamp - if stamp == ctxKept.key && time.Since(ctxKept.at) < ctxAgain { + keep := ctxAgain + if ctxKept.out.held { + keep = ctxWhileUnmatched + } + if stamp == ctxKept.key && time.Since(ctxKept.at) < keep { return ctxKept.out } out := contextOfRecs(recs, days) diff --git a/internal/gui/context_dsh_response_test.go b/internal/gui/context_dsh_response_test.go index b81589075..8d3ee0bde 100644 --- a/internal/gui/context_dsh_response_test.go +++ b/internal/gui/context_dsh_response_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "strconv" "testing" + "time" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/sessions" @@ -67,8 +68,9 @@ func TestContextTellsAForkByItsReply(t *testing.T) { 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 + // the fork's own turn is the fork, the source's is the source, and the + // opening alone has no reply id: it goes by its opening, the source's, + // as it did before reply ids were read for _, k := range []string{"session-fork", "session-source"} { if _, ok := keys[k]; !ok { t.Fatalf("no %s among %v", k, keys) @@ -78,3 +80,96 @@ func TestContextTellsAForkByItsReply(t *testing.T) { t.Fatalf("sessions %v, want the fork and its source", keys) } } + +// A fork's request counts under the source only while its reply is unread: +// the opening they share is the source's, so the source's card climbed with +// every turn of the fork. Until the reply names one the tab counts the request +// in neither, and the read after dsh writes it down counts it in the fork. +func TestContextKeepsAForkRequestOffItsSource(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) + } + } + const sourceHead = `{"type":"session","version":4,"id":"session-source","cwd":"/w","createdAt":1000,"delegationDepth":0,"isSeeded":false}` + const forkHead = `{"type":"session","version":4,"id":"session-fork","cwd":"/w","createdAt":2000,"delegationDepth":0,"isSeeded":true}` + write("session-source", sourceHead, opening, reply(2, "reply-source")) + write("session-fork", forkHead, opening, reply(2, "reply-source"), endSeed) + + 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, tokens int) gateway.Route { + r := ctxRoute(id, "dsh", "", tokens, 0, 128000, 0) + r.Conv = openingHash + r.Time, r.Millis = time.Now(), 1000 + return r + } + source := conv(1, 20000) + source.ResponseID = "reply-source" + // dsh's history before reply ids were kept: no id to wait for, and it + // must stay on the source's card + old := conv(2, 18000) + old.Time, old.Millis = time.Now().Add(-48*time.Hour), 1000 + forked := conv(3, 30000) + forked.ResponseID = "reply-fork" + // the fork's reply is the gateway's, not in its file yet: the source's + // card keeps its own call and its history, and no row of the opening's + // hash appears + out := contextOf([]gateway.Route{source, old, forked}, 7) + if len(out.Sessions) != 1 || out.Sessions[0].Key != "session-source" { + t.Fatalf("sessions %v, want the source alone", ctxKeys(out)) + } + if s := out.Sessions[0]; s.Requests != 2 || s.Peak != 20000 { + t.Fatalf("the source's %d requests, peak %d; want its own 2, 20000", s.Requests, s.Peak) + } + if !out.held { + t.Fatal("an unread reply is waited for, and the answer says so") + } + // dsh writes the reply down; the next read names the fork + write("session-fork", forkHead, opening, reply(2, "reply-source"), endSeed, reply(4, "reply-fork")) + out = contextOf([]gateway.Route{source, old, forked}, 7) + peaks := map[string]int{} + for _, s := range out.Sessions { + peaks[s.Key] = s.Peak + } + if peaks["session-source"] != 20000 || peaks["session-fork"] != 30000 { + t.Fatalf("peaks %v, want the source's 20000 and the fork's 30000", peaks) + } + if out.held { + t.Fatal("nothing is left out once the reply names the fork") + } +} + +func ctxKeys(out ctxJSON) []string { + keys := make([]string, 0, len(out.Sessions)) + for _, s := range out.Sessions { + keys = append(keys, s.Key) + } + return keys +} diff --git a/internal/gui/context_kept_test.go b/internal/gui/context_kept_test.go index c7a9672b9..e62066573 100644 --- a/internal/gui/context_kept_test.go +++ b/internal/gui/context_kept_test.go @@ -210,3 +210,46 @@ func TestTuneReadsAFileOnce(t *testing.T) { t.Fatalf("after one grew: %d calls", again.Agents[0].Calls) } } + +// An answer that left a call out of every session, its reply not read yet +// (ctxJSON.held), stands ctxWhileUnmatched, so the read after dsh writes the +// reply down names it; any other answer stands ctxAgain, as before #5542: a +// held set for a call no reply will ever name would re-read every session at +// each 5 s refresh. +func TestContextHeldAnswerStandsOnlyWhileAReplyIsAwaited(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + mux := keptMux(t) + ctxKept.Lock() + ctxKept.days, ctxKept.key = map[string]ctxDay{}, "" + ctxKept.Unlock() + dir := gateway.HistoryDir() + os.MkdirAll(dir, 0o700) + r := ctxRoute(1, "claude", "s1", 30000, 1000, 200000, 0) + r.Time = time.Now() + j, _ := json.Marshal(r) + os.WriteFile(filepath.Join(dir, time.Now().Format("2006-01-02")+".jsonl"), append(j, '\n'), 0o600) + + var out ctxJSON + getJSON(t, mux, "/api/context?days=1", &out) + if out.Days != 1 { + t.Fatalf("first answer: %+v", out) + } + ask := func(held bool, age time.Duration) (kept bool) { + ctxKept.Lock() + ctxKept.out.Days, ctxKept.out.held, ctxKept.at = -1, held, time.Now().Add(-age) + ctxKept.Unlock() + var got ctxJSON + getJSON(t, mux, "/api/context?days=1", &got) + return got.Days == -1 + } + if !ask(false, 6*time.Second) { + t.Error("an answer that held no call out was worked out again after 6s, not ctxAgain") + } + if ask(true, 6*time.Second) { + t.Error("an answer that held a call out stood past ctxWhileUnmatched") + } + if !ask(true, time.Second) { + t.Error("an answer that held a call out was worked out again within ctxWhileUnmatched") + } +} diff --git a/internal/gui/dsh_fork_seed_test.go b/internal/gui/dsh_fork_seed_test.go index e96a0213d..4f0693796 100644 --- a/internal/gui/dsh_fork_seed_test.go +++ b/internal/gui/dsh_fork_seed_test.go @@ -2,6 +2,7 @@ package gui import ( "testing" + "time" "github.com/yetone/magpie/internal/sessions" ) @@ -31,3 +32,46 @@ func TestDshForkWithoutAParentIsNamedByItsReply(t *testing.T) { } } } + +// A fork's own request opens as its source's conversation does, and the reply +// id that names it is read from the fork's file a moment after the gateway +// ended the request: a call whose reply names no session yet is neither the +// source's nor the fork's, and the tab leaves it out of both rather than +// counting it under the source. A call without a reply id — dsh's history +// before #5491 recorded them — goes by its opening, the source's, as it always +// did, and so does one old enough that no reply is coming: the source's card +// keeps its history. The read after the reply is written names the fork. +func TestDshForkRouteAwaitingItsReplyIsNeithers(t *testing.T) { + source := sessions.Session{Agent: "dsh", ID: "source", Convs: []string{"magpie-open"}} + fork := sessions.Session{Agent: "dsh", ID: "fork", SeedConvs: []string{"magpie-open"}} + list := []sessions.Session{source, fork} + now := time.Now() + routes := []ctxRec{ + {Agent: "dsh", Conv: "magpie-open", ResponseID: "chatcmpl-fork", Done: true, Time: now}, // the fork's turn, its reply unread + {Agent: "dsh", Conv: "magpie-open", Done: true, Time: now}, // no reply id: its opening's + {Agent: "dsh", Conv: "magpie-open", ResponseID: "chatcmpl-gone", Done: true, + Time: now.Add(-2 * time.Minute)}, // older than convsKept: no reply is coming + {Agent: "dsh", Conv: "magpie-open", ResponseID: "chatcmpl-long", Done: true, + Time: now.Add(-2 * time.Minute), Millis: 100_000}, // begun before the window, ended within it + } + joinConvs(routes, func() []sessions.Session { return list }) + if routes[0].Session != "" || !routes[0].Unmatched { + t.Errorf("the fork's turn, its reply unread: session %q, unmatched %v; want neither's", routes[0].Session, routes[0].Unmatched) + } + if routes[3].Session != "" || !routes[3].Unmatched { + t.Errorf("a long call that ended 20s ago: session %q, unmatched %v; want neither's", routes[3].Session, routes[3].Unmatched) + } + for _, i := range []int{1, 2} { + if routes[i].Session != "source" || routes[i].Unmatched { + t.Errorf("route %d: session %q, unmatched %v; want the opening's, the source's", i, routes[i].Session, routes[i].Unmatched) + } + } + list[1].ResponseIDs = []string{"chatcmpl-fork"} + for i := range routes { + routes[i].Session, routes[i].Unmatched = "", false + } + joinConvs(routes, func() []sessions.Session { return list }) + if routes[0].Session != "fork" || routes[0].Unmatched { + t.Errorf("the fork's own turn: session %q, unmatched %v; want the fork", routes[0].Session, routes[0].Unmatched) + } +}