sessions: a session's details show how full its context was, request by request
liang_yongxiang on Discord: Routing tells how full one request's context window was; does Sessions have the same, each turn's share? A session's details on the Sessions page (and in Usage's Sessions list, which draws the same details) get a Context line when the gateway sent calls of it (s.via): the Context tab's spark of its prompts, request by request against its window, and the fullest one's share beside it, toned as the tab tones it. A point's tip says "Request 2: 80K of 200K (40%)" (the tab's spark says it too now, where the window is known); a point clicked opens that request in Routing with its card. A session the gateway never saw asks nothing; one it kept no prompt of shows no line. The data is the routing history the Context tab already reads. A new GET /api/context/session?agent=&id=&from=&to= reads only the days from the session's first to its last (30 at most), through the tab's per-day cache (daysRecsLocked, split out of contextRecsLocked, so the tab's cached days are not evicted), and keeps that one session (contextOfRecsFor), with up to 1000 of its requests. The tab keeps the latest 80 sessions and would leave an older one out. Subagent and side calls are left out as the tab leaves them out; the same id under another agent is that agent's. The line's code is in plugins/usage/page.js (sessCtxLine). context.js only exports spark and health, and pays for its tip by cutting comments, so the core's scripts are 10 bytes under main's, no budget raise. Run at this head (rebased one215d335a), on WSL (magpie-desktop, Linux; mote rebooted mid-run): - gofmt -l clean; go test -tags nogui -run 'TestContextSessionLine|TestCoreScriptBudget|TestContext' ./internal/gui/: ok (also ok on mote at this head). - node --test sessions-context-line (new: Chromium and WebKit, en zh zh-TW ja de, 1100 and 420 wide) and context-window: 44 of 44. Run on mote before the rebase, at627fd1a3b: - the whole internal/gui package: its one red, TestCoreScriptBudget (1,536,110 > 1,533,802), is why the line moved into the plugin. - sessions-context-line: 20 of 20. - gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok. - i18n-keys: "a plugin's words are its own" red, the same on origin/maine215d335a(#5327, #5332, #5426, #5482); the new strings pass its other checks. Broken by hand: - the one-session filter dropped: TestContextSessionLine red ("its requests' prompts: [21000]", another session's line). - the tip back to "Request {n}: {tokens} tokens": sessions-context-line red in de ("Anfrage 2: 80K Token" for "Anfrage 2: 80K von 200K (40%)"). - the details line turned off: sessions-context-line red in en and zh. Not tried: the whole GUI suite (it was running under mote's suite lock when mote rebooted; not run at push); a real magpie with real routing history (the GUI test stubs /api/context/session; the Go test reads real history files in a sandbox config); the Linux app's WebKitGTK. Reported-by: liang_yongxiang (Discord)
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -431,3 +431,7 @@ i.dot.free { background: var(--k-free); box-shadow: inset 0 0 0 1px color-mix(in
|
||||
.ctx-pic.open { cursor: zoom-out; }
|
||||
.ctx-pic.open img { max-width: 100%; max-height: none; }
|
||||
@media (prefers-reduced-motion: reduce) { .ctx-pic { transition: none; } }
|
||||
|
||||
/* a session's line in its details (Sessions page, Usage's Sessions list) */
|
||||
.sess-ctx .ctx-line { display: flex; align-items: center; gap: 10px; flex: 1 1 auto; min-width: 0; max-width: 320px; font-variant-numeric: tabular-nums; }
|
||||
.sess-ctx .ctx-spark { flex: 1; min-width: 72px; height: 22px; }
|
||||
|
||||
@@ -143,16 +143,12 @@
|
||||
return g > 0 ? Math.floor(free / g) : null;
|
||||
}
|
||||
|
||||
// count words a number with the phrase for one, or for many
|
||||
const count = (n, one, many) => n === 1 ? t(one) : t(many, { n });
|
||||
|
||||
// spark draws a session's prompts, request by request, against its
|
||||
// window; the one the card tells of is marked, and a point clicked opens
|
||||
// its request
|
||||
// a session's prompts against its window; a point opens its request
|
||||
function spark(series, at, window, onPoint) {
|
||||
const W = 240, H = 34, pad = 3;
|
||||
// scaled to the session's peak, so a session that never came near its
|
||||
// window still shows how it grew; the window's line shows once it is near
|
||||
// scaled to its peak; the window's line shows once it is near
|
||||
const peak = Math.max(...series.map((p) => p.tokens), 1);
|
||||
const top = window && peak > window * 0.6 ? Math.max(window, peak) : peak * 1.2;
|
||||
const x = (i) => series.length < 2 ? W / 2 : pad + (i / (series.length - 1)) * (W - pad * 2);
|
||||
@@ -186,7 +182,9 @@
|
||||
if (!onPoint) return;
|
||||
const hit = ns("rect", { x: x(i) - Math.max(2, W / series.length / 2), y: 0, width: Math.max(4, W / series.length), height: H, class: "hit" + (on ? " on" : "") });
|
||||
const tip = document.createElementNS("http://www.w3.org/2000/svg", "title");
|
||||
tip.textContent = t("Request {n}: {tokens} tokens", { n: i + 1, tokens: fmtK(p.tokens) });
|
||||
const w = p.window || window;
|
||||
tip.textContent = w ? t("Request {n}: {tokens} of {window} ({pct})", { n: i + 1, tokens: fmtK(p.tokens), window: fmtK(w), pct: pct(p.tokens / w) })
|
||||
: t("Request {n}: {tokens} tokens", { n: i + 1, tokens: fmtK(p.tokens) });
|
||||
hit.append(tip);
|
||||
hit.onclick = (e) => { e.stopPropagation(); onPoint(p); };
|
||||
});
|
||||
@@ -1159,6 +1157,8 @@
|
||||
return box;
|
||||
}
|
||||
|
||||
window.ctxSpark = spark;
|
||||
window.ctxHealth = health;
|
||||
|
||||
// ---------- tuned for you: the settings that would have spent the fewest tokens ----------
|
||||
|
||||
|
||||
@@ -296,6 +296,7 @@ const I18N = {
|
||||
"Filling up": "渐满",
|
||||
"Near full": "将满",
|
||||
"Request {n}: {tokens} tokens": "第 {n} 个请求:{tokens} token",
|
||||
"Request {n}: {tokens} of {window} ({pct})": "第 {n} 个请求:{tokens} / {window}({pct})",
|
||||
"Counted": "已计数",
|
||||
"Estimated": "估算",
|
||||
"The request is on its way: the prompt is estimated from what the agent sent": "请求进行中:提示词按 agent 发送的内容估算",
|
||||
@@ -5059,6 +5060,7 @@ const I18N = {
|
||||
"Filling up": "漸滿",
|
||||
"Near full": "將滿",
|
||||
"Request {n}: {tokens} tokens": "第 {n} 個請求:{tokens} token",
|
||||
"Request {n}: {tokens} of {window} ({pct})": "第 {n} 個請求:{tokens} / {window}({pct})",
|
||||
"Counted": "已計數",
|
||||
"Estimated": "預估",
|
||||
"The request is on its way: the prompt is estimated from what the agent sent": "請求進行中:提示詞依 agent 送出的內容預估",
|
||||
@@ -9769,6 +9771,7 @@ const I18N = {
|
||||
"Filling up": "埋まりつつある",
|
||||
"Near full": "ほぼ満杯",
|
||||
"Request {n}: {tokens} tokens": "リクエスト {n}:{tokens} トークン",
|
||||
"Request {n}: {tokens} of {window} ({pct})": "リクエスト {n}:{tokens} / {window}({pct})",
|
||||
"Counted": "カウント済み",
|
||||
"Estimated": "推定",
|
||||
"The request is on its way: the prompt is estimated from what the agent sent": "リクエスト送信中:プロンプトはエージェントが送った内容から推定しています",
|
||||
@@ -14500,6 +14503,7 @@ const I18N = {
|
||||
"Filling up": "Füllt sich",
|
||||
"Near full": "Fast voll",
|
||||
"Request {n}: {tokens} tokens": "Anfrage {n}: {tokens} Token",
|
||||
"Request {n}: {tokens} of {window} ({pct})": "Anfrage {n}: {tokens} von {window} ({pct})",
|
||||
"Counted": "Gezählt",
|
||||
"Estimated": "Geschätzt",
|
||||
"The request is on its way: the prompt is estimated from what the agent sent": "Die Anfrage läuft noch: Der Prompt ist aus dem geschätzt, was der Agent gesendet hat",
|
||||
|
||||
@@ -2798,6 +2798,44 @@ function sessModelsText(s) {
|
||||
return sessModelNames(s.models.slice(0, 2).map((m) => m.model)) + (s.models.length > 2 ? " +" + (s.models.length - 2) : "") + (via ? " " + via : "");
|
||||
}
|
||||
|
||||
// A session's line in its details, on the Sessions page and in the Usage
|
||||
// page's Sessions list (liang_yongxiang on Discord: Routing tells how full
|
||||
// one request's window was, the Sessions page told it of no turn): its
|
||||
// prompts request by request against its window, drawn as the Context tab
|
||||
// draws its sessions (context.js), and the fullest one's share. A point
|
||||
// opens its request in Routing, with its card. Asked of the server for a
|
||||
// session the gateway sent calls of (s.via) when its details are drawn,
|
||||
// kept a while so a redraw draws it at once; shown(false) when the gateway
|
||||
// kept none of its prompts.
|
||||
const sessCtxLines = new Map(); // agent/id -> { at, c, wait }
|
||||
const SESS_CTX_AGAIN = 30000;
|
||||
function sessCtxLine(s, shown) {
|
||||
const box = el("span", "ctx-line");
|
||||
const k = s.agent + "/" + s.id;
|
||||
const draw = (c) => {
|
||||
if (!c?.points?.length) { shown(false); return; }
|
||||
const fmtK = window.ctxFmt, fill = c.window ? c.peak / c.window : 0;
|
||||
const [tone] = window.ctxHealth(fill);
|
||||
const peak = el("span", "ctx-sess-peak " + tone, c.window ? Math.round(fill * 100) + "%" : fmtK(c.peak));
|
||||
peak.dataset.tt = t("Its largest prompt: {tokens} of {window}", { tokens: fmtK(c.peak), window: fmtK(c.window) });
|
||||
box.replaceChildren(window.ctxSpark(c.points, c.latestId, c.window, (pt) => {
|
||||
if (!featuresOff.has("routing")) window.openRoute(pt.id, pt.time, { context: true }).catch(statusErr);
|
||||
}), peak);
|
||||
shown(true);
|
||||
};
|
||||
let got = sessCtxLines.get(k);
|
||||
if (got?.c !== undefined) draw(got.c);
|
||||
else shown(false);
|
||||
if (!got || (!got.wait && Date.now() - got.at > SESS_CTX_AGAIN)) {
|
||||
got = { at: Date.now(), c: got?.c, wait: null };
|
||||
const q = new URLSearchParams({ agent: s.agent, id: s.id, from: s.start || s.last || "", to: s.last || "" });
|
||||
got.wait = api("context/session?" + q).then((d) => { got.c = d?.session || null; }, () => {}).finally(() => { got.wait = null; got.at = Date.now(); });
|
||||
sessCtxLines.set(k, got);
|
||||
}
|
||||
got.wait?.then(() => { if (box.isConnected) draw(got.c); });
|
||||
return box;
|
||||
}
|
||||
|
||||
// sessUsageDetail adds to a session's details what it spent by model, and
|
||||
// what the gateway sent its calls to, at what reasoning; line(label, value)
|
||||
// adds a line of the details
|
||||
@@ -2812,6 +2850,12 @@ function sessUsageDetail(d, s, line) {
|
||||
d.append(m);
|
||||
}
|
||||
(s.via || []).forEach((v, i) => line(i ? "" : t("Routed"), viaText(v) + " · " + t("{n} tokens", { n: fmtN(v.tokens) }) + (v.credited ? " · " + ledCredits(v).textContent : "")));
|
||||
// how full its context was, request by request
|
||||
if (s.via?.length && window.ctxSpark) {
|
||||
const l = el("div", "sess-line sess-ctx");
|
||||
l.append(el("span", "k", t("Context")), sessCtxLine(s, (on) => { l.hidden = !on; }));
|
||||
d.append(l);
|
||||
}
|
||||
}
|
||||
|
||||
// one place a session's calls went through magpie, in words
|
||||
|
||||
+96
-13
@@ -121,6 +121,8 @@ type ctxJSON struct {
|
||||
const (
|
||||
ctxSessions = 80
|
||||
ctxPoints = 160
|
||||
// ctxSessionPoints is how many a session's own line keeps, the latest
|
||||
ctxSessionPoints = 1000
|
||||
)
|
||||
|
||||
func median(xs []int) int {
|
||||
@@ -498,6 +500,13 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
|
||||
|
||||
// contextOfRecs is contextOf of the routes as the tab reads them.
|
||||
func contextOfRecs(routes []ctxRec, days int) ctxJSON {
|
||||
return contextOfRecsFor(routes, days, "")
|
||||
}
|
||||
|
||||
// contextOfRecsFor is contextOfRecs, and when only isn't "" it lists that
|
||||
// one session alone (agent + "\x00" + its id), with up to ctxSessionPoints
|
||||
// of its requests: a session's line on the Sessions page.
|
||||
func contextOfRecsFor(routes []ctxRec, days int, only string) ctxJSON {
|
||||
sort.SliceStable(routes, func(i, j int) bool { return routes[i].Time.Before(routes[j].Time) })
|
||||
out := ctxJSON{Days: days, Agents: []ctxAgent{}, Sessions: []ctxSession{}}
|
||||
type agentAcc struct {
|
||||
@@ -615,14 +624,21 @@ func contextOfRecs(routes []ctxRec, days int) ctxJSON {
|
||||
// the sessions, the latest first
|
||||
slices.SortFunc(order, func(a, b string) int { return sess[b].Last.Compare(sess[a].Last) })
|
||||
var codexIDs, desktopIDs, piIDs []string
|
||||
keep := ctxPoints
|
||||
if only != "" {
|
||||
keep = ctxSessionPoints
|
||||
}
|
||||
for _, sk := range order {
|
||||
s := sess[sk]
|
||||
if only != "" && sk != only {
|
||||
continue
|
||||
}
|
||||
if acc := agents[s.Agent]; acc != nil && s.Requests > 1 {
|
||||
acc.fills = append(acc.fills, float64(s.Peak)/float64(s.Window))
|
||||
}
|
||||
if len(out.Sessions) < ctxSessions {
|
||||
if len(s.Points) > ctxPoints {
|
||||
s.Points = s.Points[len(s.Points)-ctxPoints:]
|
||||
if len(s.Points) > keep {
|
||||
s.Points = s.Points[len(s.Points)-keep:]
|
||||
}
|
||||
out.Sessions = append(out.Sessions, *s)
|
||||
switch s.Agent {
|
||||
@@ -858,13 +874,33 @@ func contextRecs(r *http.Request, days int) (out []ctxRec, stamp string) {
|
||||
}
|
||||
|
||||
func contextRecsLocked(r *http.Request, days int) (out []ctxRec, stamp string) {
|
||||
seen := map[int64]bool{}
|
||||
now := time.Now()
|
||||
var key strings.Builder
|
||||
asked := map[string]bool{}
|
||||
list := make([]string, 0, days)
|
||||
for i := days - 1; i >= 0; i-- {
|
||||
day := now.AddDate(0, 0, -i).Format("2006-01-02")
|
||||
list = append(list, now.AddDate(0, 0, -i).Format("2006-01-02"))
|
||||
}
|
||||
out, stamp = daysRecsLocked(r, list)
|
||||
// a day out of the range is let go; the range's days are kept for the
|
||||
// next refresh
|
||||
asked := map[string]bool{}
|
||||
for _, day := range list {
|
||||
asked[day] = true
|
||||
}
|
||||
for day := range ctxKept.days {
|
||||
if !asked[day] {
|
||||
delete(ctxKept.days, day)
|
||||
}
|
||||
}
|
||||
return out, stamp
|
||||
}
|
||||
|
||||
// daysRecsLocked reads the routes of the days listed, from what is kept
|
||||
// of them when their files are as they were, and the live trace's not yet
|
||||
// in the history.
|
||||
func daysRecsLocked(r *http.Request, list []string) (out []ctxRec, stamp string) {
|
||||
seen := map[int64]bool{}
|
||||
var key strings.Builder
|
||||
for _, day := range list {
|
||||
st := dayStamp(day)
|
||||
fmt.Fprintf(&key, "%s=%s", day, st)
|
||||
d, ok := ctxKept.days[day]
|
||||
@@ -883,13 +919,6 @@ func contextRecsLocked(r *http.Request, days int) (out []ctxRec, stamp string) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// a day out of the range is let go; the range's days are kept for the
|
||||
// next refresh
|
||||
for day := range ctxKept.days {
|
||||
if !asked[day] {
|
||||
delete(ctxKept.days, day)
|
||||
}
|
||||
}
|
||||
if gw := served.Load(); gw != nil {
|
||||
for _, x := range gw.Trace(r.Context(), 0, 0).Routes {
|
||||
if x.Done && !seen[x.ID] {
|
||||
@@ -907,6 +936,46 @@ func contextRecsLocked(r *http.Request, days int) (out []ctxRec, stamp string) {
|
||||
return out, key.String()
|
||||
}
|
||||
|
||||
// ctxSessionDays is how far back a session's line reads: the Usage page's
|
||||
// Context tab's longest range
|
||||
const ctxSessionDays = 30
|
||||
|
||||
// contextSession is one agent's session as the Context tab counts it,
|
||||
// every request of it the gateway saw from the day of from to the day of
|
||||
// to (the session's first and last, as the Sessions page has them), read
|
||||
// within the last ctxSessionDays days; nil when the gateway saw none.
|
||||
// The days read stay kept until the tab's next read lets go of those
|
||||
// out of its range.
|
||||
func contextSession(r *http.Request, agent, id string, from, to time.Time) *ctxSession {
|
||||
now := time.Now()
|
||||
oldest := now.AddDate(0, 0, -(ctxSessionDays - 1))
|
||||
if from.IsZero() || from.Before(oldest) {
|
||||
from = oldest
|
||||
}
|
||||
if to.IsZero() || to.After(now) {
|
||||
to = now
|
||||
}
|
||||
// day by day at noon, which a change of clocks never moves to another day
|
||||
y, m, dd := from.Local().Date()
|
||||
last := to.Local().Format("2006-01-02")
|
||||
var list []string
|
||||
for d := time.Date(y, m, dd, 12, 0, 0, 0, time.Local); len(list) < ctxSessionDays; d = d.AddDate(0, 0, 1) {
|
||||
day := d.Format("2006-01-02")
|
||||
list = append(list, day)
|
||||
if day >= last {
|
||||
break
|
||||
}
|
||||
}
|
||||
ctxKept.Lock()
|
||||
recs, _ := daysRecsLocked(r, list)
|
||||
ctxKept.Unlock()
|
||||
out := contextOfRecsFor(recs, len(list), agent+"\x00"+id)
|
||||
if len(out.Sessions) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &out.Sessions[0]
|
||||
}
|
||||
|
||||
// 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, or
|
||||
// ctxWhileUnmatched old when it left a route out of every session.
|
||||
@@ -928,6 +997,20 @@ func contextFor(r *http.Request, days int) ctxJSON {
|
||||
}
|
||||
|
||||
func contextRoutesAPI(mux *http.ServeMux) {
|
||||
// one session's prompts, request by request, against its window: the
|
||||
// line the Sessions page draws in a session's details (liang_yongxiang
|
||||
// on Discord). from and to are its first and last, RFC 3339.
|
||||
mux.HandleFunc("GET /api/context/session", func(rw http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
agent, id := q.Get("agent"), q.Get("id")
|
||||
if agent == "" || id == "" {
|
||||
http.Error(rw, "agent and id are needed", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
from, _ := time.Parse(time.RFC3339, q.Get("from"))
|
||||
to, _ := time.Parse(time.RFC3339, q.Get("to"))
|
||||
writeJSON(rw, map[string]any{"session": contextSession(r, agent, id, from, to)})
|
||||
})
|
||||
mux.HandleFunc("GET /api/context", func(rw http.ResponseWriter, r *http.Request) {
|
||||
days, _ := strconv.Atoi(r.URL.Query().Get("days"))
|
||||
if days <= 0 || days > 30 {
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
)
|
||||
|
||||
// A session's details on the Sessions page show how full its context was,
|
||||
// request by request (liang_yongxiang on Discord: Routing told it for one
|
||||
// request, the Sessions page not at all). /api/context/session answers one
|
||||
// session's line: each of its requests the gateway saw, oldest first, over
|
||||
// every day from its first to its last and none outside them, however many
|
||||
// other sessions there were since (the Context tab lists the latest 80 and
|
||||
// would leave it out), and with neither a subagent's prompt nor another
|
||||
// agent's session of the same id in it.
|
||||
func TestContextSessionLine(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()
|
||||
reads := map[string]bool{}
|
||||
readingDay = func(day string) { reads[day] = true }
|
||||
t.Cleanup(func() { readingDay = nil })
|
||||
|
||||
dir := gateway.HistoryDir()
|
||||
os.MkdirAll(dir, 0o700)
|
||||
now := time.Now()
|
||||
dayOf := func(back int) time.Time {
|
||||
d := now.AddDate(0, 0, -back)
|
||||
return time.Date(d.Year(), d.Month(), d.Day(), 9, 0, 0, 0, time.Local)
|
||||
}
|
||||
files := map[string]*bytes.Buffer{}
|
||||
id := int64(0)
|
||||
add := func(back int, agent, session string, chat int, edit func(*gateway.Route)) time.Time {
|
||||
id++
|
||||
r := ctxRoute(id, agent, session, 20000, chat, 200000, 0)
|
||||
r.Time = dayOf(back).Add(time.Duration(id) * time.Second)
|
||||
if edit != nil {
|
||||
edit(&r)
|
||||
}
|
||||
day := r.Time.Format("2006-01-02")
|
||||
if files[day] == nil {
|
||||
files[day] = &bytes.Buffer{}
|
||||
}
|
||||
j, _ := json.Marshal(r)
|
||||
files[day].Write(append(j, '\n'))
|
||||
return r.Time
|
||||
}
|
||||
// a request of another session four days ago, outside the session's days
|
||||
add(4, "claude", "older", 1000, nil)
|
||||
first := add(3, "claude", "s1", 10000, nil)
|
||||
add(3, "claude", "s1", 30000, func(r *gateway.Route) { r.Sub = "explore" })
|
||||
add(2, "claude", "s1", 60000, nil)
|
||||
add(2, "codex", "s1", 90000, nil)
|
||||
last := add(1, "claude", "s1", 140000, nil)
|
||||
// 100 sessions since, on its last day after it
|
||||
for i := range 100 {
|
||||
add(1, "claude", fmt.Sprint("later-", i), 1000, nil)
|
||||
}
|
||||
for day, b := range files {
|
||||
os.WriteFile(filepath.Join(dir, day+".jsonl"), b.Bytes(), 0o600)
|
||||
}
|
||||
|
||||
ask := func(agent, sid string, from, to time.Time) *ctxSession {
|
||||
t.Helper()
|
||||
var got struct {
|
||||
Session *ctxSession `json:"session"`
|
||||
}
|
||||
q := url.Values{"agent": {agent}, "id": {sid}, "from": {from.UTC().Format(time.RFC3339Nano)}, "to": {to.UTC().Format(time.RFC3339Nano)}}
|
||||
getJSON(t, mux, "/api/context/session?"+q.Encode(), &got)
|
||||
return got.Session
|
||||
}
|
||||
s := ask("claude", "s1", first, last)
|
||||
if s == nil {
|
||||
t.Fatal("no line for a session the gateway saw")
|
||||
}
|
||||
var tokens []int
|
||||
for _, p := range s.Points {
|
||||
tokens = append(tokens, p.Tokens)
|
||||
}
|
||||
if fmt.Sprint(tokens) != "[30000 80000 160000]" {
|
||||
t.Fatalf("its requests' prompts: %v, want [30000 80000 160000]", tokens)
|
||||
}
|
||||
if s.Window != 200000 || s.Peak != 160000 || s.Requests != 3 || s.Agent != "claude" || s.Key != "s1" {
|
||||
t.Fatalf("session: %+v", s)
|
||||
}
|
||||
if reads[dayOf(4).Format("2006-01-02")] || reads[dayOf(0).Format("2006-01-02")] {
|
||||
t.Fatalf("read days outside the session's: %v", reads)
|
||||
}
|
||||
if !reads[dayOf(3).Format("2006-01-02")] || !reads[dayOf(1).Format("2006-01-02")] {
|
||||
t.Fatalf("didn't read the session's days: %v", reads)
|
||||
}
|
||||
|
||||
// the same id under another agent is that agent's own
|
||||
if c := ask("codex", "s1", first, last); c == nil || len(c.Points) != 1 || c.Points[0].Tokens != 110000 {
|
||||
t.Fatalf("codex's s1: %+v", c)
|
||||
}
|
||||
// a session the gateway never saw has no line
|
||||
if n := ask("claude", "nobody", first, last); n != nil {
|
||||
t.Fatalf("a session never seen: %+v", n)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, httptest.NewRequest("GET", "/api/context/session?agent=claude", nil))
|
||||
if rec.Code != 400 {
|
||||
t.Fatalf("no id: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -849,6 +849,15 @@ Chromium and WebKit, in English, Chinese, Japanese and German, at 1100px and
|
||||
420px. With the state answering after the history, the cards drawn by the
|
||||
agents' ids take their names once it is in, though the history is the same.
|
||||
|
||||
`sessions-context-line.test.cjs` opens a session's details on the Sessions
|
||||
page (liang_yongxiang on Discord): one the gateway sent calls of asks
|
||||
`/api/context/session` once, with its first and last, and draws a Context
|
||||
line, a point a request telling its share of the window and the fullest
|
||||
share beside it, toned; a point clicked opens that request in Routing with
|
||||
its card; one the gateway kept no prompt of, or never saw, has no line, and
|
||||
the second isn't asked; opened again it is drawn without asking — in
|
||||
Chromium and WebKit, in all five languages, at 1100px and 420px.
|
||||
|
||||
`tray-usages.test.cjs` picks several of the Usage page's cards for the menu
|
||||
bar in Settings: the menu keeps open as Codex and Claude Code are ticked
|
||||
beside Copilot, posts nothing till it closes and then the three once, in the
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A session's details on the Sessions page say how full its context was,
|
||||
// request by request (liang_yongxiang on Discord: Routing told it for one
|
||||
// request, the Sessions page for none). A session the gateway sent calls of
|
||||
// (via) asks /api/context/session for its line once, with its first and
|
||||
// last, and draws the Context tab's line of it: a point a request, each
|
||||
// telling its share of the window, and the fullest one's share beside it.
|
||||
// A point clicked opens that request in Routing, with its card. A session
|
||||
// the gateway never saw asks nothing and has no Context line, and one it
|
||||
// kept no prompt of has none either. Opened again, the line is drawn at
|
||||
// once, not asked again. In five languages, Chromium and WebKit, at 1100
|
||||
// and 420 wide.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const at = (min) => new Date(Date.now() - min * 60e3).toISOString();
|
||||
const VIA = [{ provider: "anthropic", model: "claude-sonnet-5", calls: 3, tokens: 270000 }];
|
||||
const POINTS = [
|
||||
{ id: 11, time: at(30), tokens: 30000, window: 200000 },
|
||||
{ id: 12, time: at(20), tokens: 80000, window: 200000 },
|
||||
{ id: 13, time: at(10), tokens: 160000, window: 200000 },
|
||||
];
|
||||
|
||||
function serve(lang, asked) {
|
||||
const base = { agent: "claude", cwd: "/work/c", models: [{ model: "claude-sonnet-5", input: 270000, output: 9000 }], size: 4096, messages: 6, files: 1, deletable: true };
|
||||
const sessions = [
|
||||
{ ...base, id: "seen-1", title: "Seen by the gateway", start: at(40), last: at(10), via: VIA },
|
||||
{ ...base, id: "kept-none", title: "Nothing kept", start: at(50), last: at(45), via: VIA },
|
||||
{ ...base, id: "own-only", title: "Never through magpie", start: at(60), last: at(55) },
|
||||
];
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/sessions/manage") {
|
||||
return json({ agents: [{ agent: "claude", count: sessions.length, deletable: true, name: "Claude Code", icon: "claude" }],
|
||||
agent: "claude", sessions, terminal: true, trash: [], trashDir: "~/trash" });
|
||||
}
|
||||
if (url.pathname === "/api/context/session") {
|
||||
const q = Object.fromEntries(url.searchParams);
|
||||
asked.push(q);
|
||||
if (q.id !== "seen-1") return json({ session: null });
|
||||
return json({ session: { agent: "claude", key: "seen-1", model: "claude-sonnet-5", first: POINTS[0].time, last: POINTS[2].time,
|
||||
requests: 3, peak: 160000, window: 200000, latestId: 13, points: POINTS } });
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
const body = await fs.readFile(file).catch(() => null);
|
||||
await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404 }));
|
||||
};
|
||||
}
|
||||
|
||||
const NAV = { en: "Sessions", zh: "会话", "zh-TW": "工作階段", ja: "セッション", de: "Sitzungen" };
|
||||
const CONTEXT = { en: "Context", zh: "上下文", "zh-TW": "上下文", ja: "コンテキスト", de: "Kontext" };
|
||||
const TIP = {
|
||||
en: "Request 2: 80K of 200K (40%)",
|
||||
zh: "第 2 个请求:80K / 200K(40%)",
|
||||
"zh-TW": "第 2 個請求:80K / 200K(40%)",
|
||||
ja: "リクエスト 2:80K / 200K(40%)",
|
||||
de: "Anfrage 2: 80K von 200K (40%)",
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
for (const width of [1100, 420]) {
|
||||
test(`${engine} ${lang} ${width}: a session's details show how full its context was, request by request`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-sessions-context-line.png`) });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const asked = [];
|
||||
await page.route("**/*", serve(lang, asked));
|
||||
await page.goto("http://magpie.test/?view=sessions");
|
||||
const view = page.locator("#view-sessions");
|
||||
if (!(await view.isVisible())) {
|
||||
const nav = page.locator("#nav").getByRole("button", { name: NAV[lang], exact: true });
|
||||
if (await nav.count()) await nav.click();
|
||||
}
|
||||
const open = async (id) => {
|
||||
const row = view.locator(`.row.sm-sess[data-id="${id}"]`);
|
||||
await row.waitFor();
|
||||
await row.locator(".who").click();
|
||||
const item = row.locator("xpath=..");
|
||||
await item.locator(".sess-detail").waitFor();
|
||||
return item.locator(".sess-detail");
|
||||
};
|
||||
|
||||
// the session the gateway saw
|
||||
let detail = await open("seen-1");
|
||||
const line = detail.locator(".sess-line.sess-ctx");
|
||||
await line.locator(".ctx-spark svg").waitFor();
|
||||
assert.equal(await line.locator(".k").textContent(), CONTEXT[lang]);
|
||||
assert.equal(asked.length, 1);
|
||||
assert.equal(asked[0].agent, "claude");
|
||||
assert.equal(asked[0].id, "seen-1");
|
||||
assert.ok(asked[0].from && asked[0].to && Date.parse(asked[0].from) < Date.parse(asked[0].to), `its first and last: ${JSON.stringify(asked[0])}`);
|
||||
const hits = line.locator(".ctx-spark rect.hit");
|
||||
assert.equal(await hits.count(), POINTS.length, "a point a request");
|
||||
assert.equal(await hits.nth(1).locator("title").textContent(), TIP[lang]);
|
||||
const peak = line.locator(".ctx-sess-peak");
|
||||
assert.equal(await peak.textContent(), "80%");
|
||||
assert.match(await peak.getAttribute("class"), /\bwarn\b/);
|
||||
|
||||
// inside the details, and the page never scrolls sideways
|
||||
const box = await line.evaluate((l) => {
|
||||
const r = l.getBoundingClientRect(), d = l.closest(".sess-detail").getBoundingClientRect();
|
||||
const s = l.querySelector(".ctx-spark").getBoundingClientRect();
|
||||
return { inside: r.right <= d.right + 0.5, spark: s.width, h: s.height };
|
||||
});
|
||||
assert.ok(box.inside, `the line stays inside the details at ${width}: ${JSON.stringify(box)}`);
|
||||
assert.ok(box.spark >= 60 && box.h > 10, `the line can be read: ${JSON.stringify(box)}`);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll");
|
||||
|
||||
// a point opens its request in Routing, with its card
|
||||
await page.evaluate(() => { window.__opened = []; window.openRoute = (id, time, o) => { window.__opened.push([id, time, o]); return Promise.resolve(); }; });
|
||||
await hits.nth(1).dispatchEvent("click");
|
||||
assert.deepEqual(await page.evaluate(() => window.__opened), [[12, POINTS[1].time, { context: true }]]);
|
||||
|
||||
// a session the gateway kept no prompt of: asked, no line
|
||||
const answered = page.waitForResponse((r) => r.url().includes("/api/context/session") && r.url().includes("id=kept-none"));
|
||||
detail = await open("kept-none");
|
||||
await answered;
|
||||
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => r())));
|
||||
assert.equal(await detail.locator(".sess-line.sess-ctx:not([hidden])").count(), 0);
|
||||
// one never through magpie: not asked, no line
|
||||
detail = await open("own-only");
|
||||
assert.equal(await detail.locator(".sess-line.sess-ctx").count(), 0);
|
||||
assert.equal(asked.filter((q) => q.id === "own-only").length, 0);
|
||||
|
||||
// opened again, drawn at once from what was read
|
||||
detail = await open("seen-1");
|
||||
assert.equal(await detail.locator(".sess-line.sess-ctx .ctx-spark rect.hit").count(), POINTS.length);
|
||||
assert.equal(asked.filter((q) => q.id === "seen-1").length, 1, "not asked again");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user