context: a request's text and reply from the request archive (wangbinyq)
wangbinyq on Discord: with the request archive on, clicking a block of
the context window card still said "只保留最近 10 个请求的原文", since the
card read only the last 10 bodies magpie keeps in memory.
What changed:
- /api/context/text tries memory first, then the request archive's copy
when the route names one (Route.Archive, the route found in the trace
or in the history file of the card's ?day=, HistoryRoute looks a day
either side). gateway.ArchivedPromptText parses it as PromptText does
and masks it through maskedCopy, as the body in memory is; it is
marked from "archive" and the card says so.
- New /api/context/reply: the reply to the request, from the Recent
calls (Server.ReplyBody) or the archive's Response. gateway.ReplyPieces
reads it into thinking/assistant/call pieces (conversationOutput, split
out of conversationTurn) after redact.ScrubJSON, and masks every piece
through maskedCopy. The card's text view has a Reply button beside
Close that shows it and goes back to the part.
- What is shown is what the archive stores, masked as the memory copy
would be, nothing more. A body or reply that can't be masked shows
nothing (404 "unread"); one the archive cut short isn't parsed ("cut");
one it names and doesn't have says so ("missing"), and one with no
archive copy keeps the old "only the last 10" line ("off"). A failed
bucket read is an error, not "gone".
- The archive read is capped at archiveReadMost and the last copy read is
kept 5 minutes, so the items opened one by one read it once.
- ctxtext.js takes the route (id and time) instead of the id; context.js
passes it (its one-line change paid for by a comment cut, core budget
not raised). New strings in zh, zh-TW, ja and de.
- docs/subsystems/gateway-routing.md (Prompt) and gui-shell.md.
Run on f3335dd1b (main has since d73f2254d, textcalls_anthropic.go and
its test only, none of these files), on mote (macOS 27):
- go test -run 'TestArchivedPromptText|TestReplyPieces|TestPromptText|
TestConversation|TestContext|TestCoreScriptBudget' ./internal/gateway
./internal/gui: ok.
- Whole ./internal/gui and ./internal/gateway (before the last rebase,
same change): ok except TestMainWindowCorners/macOS_26_SDK (#3949) and
TestCodexPoolSaysTheClientsVersion (#4807, fixed on main by 17f2387e1
since).
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of both: ok;
gofmt -l clean.
- GUI, both engines, every language, 1100 and 420 wide: every file that
reaches the context card (context-text, context-map, context-window,
context-map-live, context-scroll-end, context-scripts, context-tune,
ctx-route, compact-one-value, routing-ctx-*, routing-context-fold,
routing-live-patch, routing-return-cost) plus i18n-keys: 514 of 518.
The 4 reds are context-map's webkit 420px "two tiles overlap", red the
same on origin/main f3335dd1b run alone (5 of 10 webkit there), #3488.
- The whole GUI suite is running on the Linux box (wsl-run) as this is
pushed; mote had another session's full suite on it.
Broken by hand (each went red):
- maskReplyPieces skipped: TestReplyPiecesAreMasked (phone unmasked).
- ArchivedPromptText's masking skipped: TestArchivedPromptTextIsMasked
and TestContextTextFromTheArchive (phone in the 200 body).
- ctxtext.js's "missing" reason dropped: context-text.test.cjs, 10 of 10
chromium.
Not tried: a real archived request in the running app, the bucket
(WebDAV) archive with a real server, and a reply cut short by the
archive's size in a real call.
This commit is contained in:
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -140,6 +140,20 @@ func conversationTurn(proto provider.Protocol, input, output []byte) sessions.Ga
|
||||
t.Input = append(t.Input, conversationParts(m.Role, m.Parts)...)
|
||||
}
|
||||
}
|
||||
var cut bool
|
||||
t.Output, cut = conversationOutput(proto, output)
|
||||
t.Cut = t.Cut || cut
|
||||
return t
|
||||
}
|
||||
|
||||
// conversationOutput reads a reply, a whole JSON body or a stream, into
|
||||
// parts; cut when it couldn't all be read or ended before it was whole.
|
||||
func conversationOutput(proto provider.Protocol, output []byte) ([]sessions.Part, bool) {
|
||||
t := struct {
|
||||
Output []sessions.Part
|
||||
Cut bool
|
||||
}{Output: []sessions.Part{}}
|
||||
var err error
|
||||
trim := bytes.TrimSpace(output)
|
||||
if json.Valid(trim) {
|
||||
t.Output, err = conversationJSON(proto, trim)
|
||||
@@ -197,7 +211,7 @@ func conversationTurn(proto provider.Protocol, input, output []byte) sessions.Ga
|
||||
} else if len(trim) > 0 {
|
||||
t.Cut = true
|
||||
}
|
||||
return t
|
||||
return t.Output, t.Cut
|
||||
}
|
||||
|
||||
// Reuse the request readers for whole replies by placing the actual output in
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// wangbinyq on Discord: with the request archive on, the context window
|
||||
// card still said a request's text was gone once it left memory. The
|
||||
// archive's copy is read instead, masked as the copy in memory is: a phone
|
||||
// number in it shows as its placeholder, as it would from memory.
|
||||
func TestArchivedPromptTextIsMasked(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const phone = "13800138000"
|
||||
body := []byte(`{"model":"m","system":"You are the release agent.","messages":[
|
||||
{"role":"user","content":"call me at ` + phone + ` once it ships"},
|
||||
{"role":"assistant","content":"Shipping."}]}`)
|
||||
pt, ok := ArchivedPromptText(provider.Anthropic, body, 7, PartChat, true, 0)
|
||||
if !ok || pt.From != "archive" || len(pt.Items) == 0 {
|
||||
t.Fatalf("%v %+v", ok, pt)
|
||||
}
|
||||
b, _ := json.Marshal(pt)
|
||||
if strings.Contains(string(b), phone) || !strings.Contains(string(b), "once it ships") {
|
||||
t.Fatalf("archived text %s", b)
|
||||
}
|
||||
sys, ok := ArchivedPromptText(provider.Anthropic, body, 7, PartSystem, true, 0)
|
||||
if b, _ := json.Marshal(sys); !ok || !strings.Contains(string(b), "You are the release agent.") {
|
||||
t.Fatalf("system %s", b)
|
||||
}
|
||||
// a body cut short reads as nothing
|
||||
if _, ok := ArchivedPromptText(provider.Anthropic, []byte(`{"model":`), 8, PartChat, true, 0); ok {
|
||||
t.Fatal("read a body cut short")
|
||||
}
|
||||
}
|
||||
|
||||
// The reply beside the prompt: its text, its thinking and its calls, from
|
||||
// a whole reply or a stream, masked as the prompt's text is.
|
||||
func TestReplyPiecesAreMasked(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const phone = "13800138000"
|
||||
whole := `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[
|
||||
{"type":"thinking","thinking":"The user wants a call."},
|
||||
{"type":"text","text":"I will call ` + phone + ` when it ships."},
|
||||
{"type":"tool_use","id":"c1","name":"Deploy","input":{"env":"prod","notify":"` + phone + `"}}],
|
||||
"stop_reason":"tool_use","usage":{"input_tokens":3,"output_tokens":9}}`
|
||||
pieces, cut, ok := ReplyPieces(provider.Anthropic, []byte(whole), false)
|
||||
if !ok || cut {
|
||||
t.Fatalf("%v %v", ok, cut)
|
||||
}
|
||||
var roles []string
|
||||
for _, p := range pieces {
|
||||
roles = append(roles, p.Role+":"+p.Name)
|
||||
if strings.Contains(p.Text, phone) {
|
||||
t.Fatalf("%s unmasked: %s", p.Role, p.Text)
|
||||
}
|
||||
}
|
||||
if got := strings.Join(roles, " "); got != "thinking: assistant: call:Deploy" {
|
||||
t.Fatalf("pieces %s", got)
|
||||
}
|
||||
if !strings.Contains(pieces[1].Text, "when it ships") || !strings.Contains(pieces[2].Text, `"prod"`) {
|
||||
t.Fatalf("%+v", pieces)
|
||||
}
|
||||
stream := sse(
|
||||
"event: message_start\ndata: "+`{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[],"usage":{"input_tokens":3,"output_tokens":0}}}`,
|
||||
"event: content_block_start\ndata: "+`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
|
||||
"event: content_block_delta\ndata: "+`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Reach me at `+phone+`."}}`,
|
||||
"event: content_block_stop\ndata: "+`{"type":"content_block_stop","index":0}`,
|
||||
"event: message_stop\ndata: "+`{"type":"message_stop"}`)
|
||||
pieces, _, ok = ReplyPieces(provider.Anthropic, []byte(stream), false)
|
||||
if !ok || len(pieces) != 1 || pieces[0].Role != "assistant" || strings.Contains(pieces[0].Text, phone) || !strings.Contains(pieces[0].Text, "Reach me at") {
|
||||
t.Fatalf("stream %v %+v", ok, pieces)
|
||||
}
|
||||
if _, _, ok := ReplyPieces(provider.Anthropic, nil, false); ok {
|
||||
t.Fatal("read an empty reply")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package gateway
|
||||
|
||||
// The reply beside the prompt's text (wangbinyq on Discord): the context
|
||||
// window card's text view shows what the model answered too, read from the
|
||||
// reply as the agent got it, from the Recent calls in memory or from the
|
||||
// request archive's copy. It is masked as the prompt's text is, so the view
|
||||
// shows no value the prompt's own text would have masked.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/redact"
|
||||
)
|
||||
|
||||
// PromptReply is a request's reply, piece by piece: the answer's text, its
|
||||
// thinking and its tool calls.
|
||||
type PromptReply struct {
|
||||
ID int64 `json:"id"`
|
||||
Pieces []PromptPiece `json:"pieces"`
|
||||
// Cut: only the reply's start was kept, or it ended before it was whole
|
||||
Cut bool `json:"cut,omitempty"`
|
||||
// From: "memory" (the Recent calls) or "archive"
|
||||
From string `json:"from"`
|
||||
}
|
||||
|
||||
// ReplyBody is the reply to request route id as the Recent calls keep it,
|
||||
// with the protocol it was written in; false once the call has left them.
|
||||
func (s *Server) ReplyBody(id int64) (provider.Protocol, []byte, bool, bool) {
|
||||
c, ok := s.RouteCall(id)
|
||||
if !ok || c.ResponseBody == "" {
|
||||
return "", nil, false, false
|
||||
}
|
||||
return c.From, []byte(c.ResponseBody), c.ResponseTruncated, true
|
||||
}
|
||||
|
||||
// ReplyPieces reads a reply body (JSON or a stream) written in proto into
|
||||
// pieces, masked as a prompt's text is; false when nothing in it can be
|
||||
// read, or masking failed.
|
||||
func ReplyPieces(proto provider.Protocol, body []byte, cut bool) ([]PromptPiece, bool, bool) {
|
||||
parts, outCut := conversationOutput(proto, redact.ScrubJSON(body))
|
||||
var pieces []PromptPiece
|
||||
for _, p := range parts {
|
||||
pc := PromptPiece{Role: "assistant", Text: p.Text}
|
||||
switch p.Kind {
|
||||
case "thinking":
|
||||
pc.Role = "thinking"
|
||||
case "tool_use":
|
||||
pc.Role, pc.Name = "call", p.Name
|
||||
}
|
||||
pieces = append(pieces, pc)
|
||||
}
|
||||
if len(pieces) == 0 {
|
||||
return nil, false, false
|
||||
}
|
||||
if !maskReplyPieces(pieces) {
|
||||
return nil, false, false
|
||||
}
|
||||
for i := range pieces {
|
||||
if pieces[i].Role == "call" {
|
||||
pieces[i] = rawPiece("call", pieces[i].Name, []byte(pieces[i].Text)).read()
|
||||
}
|
||||
}
|
||||
return pieces, cut || outCut, true
|
||||
}
|
||||
|
||||
// maskReplyPieces masks the pieces' text in place, through the masker a
|
||||
// request's body goes through: put as a conversation's assistant turns, so
|
||||
// each text is masked as message text is.
|
||||
func maskReplyPieces(pieces []PromptPiece) bool {
|
||||
type msg struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
in := struct {
|
||||
Messages []msg `json:"messages"`
|
||||
}{}
|
||||
for _, pc := range pieces {
|
||||
in.Messages = append(in.Messages, msg{Role: "assistant", Content: pc.Text})
|
||||
}
|
||||
body, err := json.Marshal(in)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
masked := maskedCopy(context.Background(), body)
|
||||
if masked == nil {
|
||||
return false
|
||||
}
|
||||
var out struct {
|
||||
Messages []msg `json:"messages"`
|
||||
}
|
||||
if json.Unmarshal(masked, &out) != nil || len(out.Messages) != len(pieces) {
|
||||
return false
|
||||
}
|
||||
for i := range pieces {
|
||||
pieces[i].Text = out.Messages[i].Content
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -14,10 +14,12 @@ package gateway
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
@@ -104,6 +106,10 @@ type PromptText struct {
|
||||
Items []PromptEntry `json:"items"`
|
||||
// Kept is how many requests' text is kept, for the GUI to say so
|
||||
Kept int `json:"kept"`
|
||||
// From is "archive" when the text was read from the request archive's
|
||||
// copy, the body having left memory (wangbinyq on Discord); "" from
|
||||
// memory
|
||||
From string `json:"from,omitempty"`
|
||||
}
|
||||
|
||||
// PromptKept is how many requests' text the trace keeps.
|
||||
@@ -126,7 +132,74 @@ func (s *Server) PromptText(id int64, kind string, withText bool) (PromptText, b
|
||||
}
|
||||
s.trace.maskedBody(id, kb.body)
|
||||
}
|
||||
b, ok := promptPieces(kb.from, kb.body)
|
||||
tokens := 0
|
||||
s.trace.mu.Lock()
|
||||
for _, r := range s.trace.routes {
|
||||
if r.ID == id && r.Prompt != nil {
|
||||
tokens = r.Prompt.Tokens
|
||||
}
|
||||
}
|
||||
s.trace.mu.Unlock()
|
||||
return promptTextOf(kb.from, kb.body, id, kind, withText, tokens)
|
||||
}
|
||||
|
||||
// ArchivedPromptText is PromptText read from the request archive's copy of
|
||||
// request id's body, for a request whose body has left memory (wangbinyq
|
||||
// on Discord: the card said the text was gone with the archive on). The
|
||||
// archive keeps the body as the agent sent it, its secrets taken out; it
|
||||
// is masked here as the body in memory is, so the card shows no more from
|
||||
// the archive than from memory. tokens is the route's prompt as counted,
|
||||
// to scale the sizes as the card does. One masked body is kept, in memory,
|
||||
// for the item clicked next. False when the body can't be read: the
|
||||
// archive kept only its start, or masking failed.
|
||||
func ArchivedPromptText(from provider.Protocol, body []byte, id int64, kind string, withText bool, tokens int) (PromptText, bool) {
|
||||
if !slices.Contains(partOrder, kind) {
|
||||
return PromptText{}, false
|
||||
}
|
||||
body, ok := archivedMasked(id, body)
|
||||
if !ok {
|
||||
return PromptText{}, false
|
||||
}
|
||||
pt, ok := promptTextOf(from, body, id, kind, withText, tokens)
|
||||
pt.From = "archive"
|
||||
return pt, ok
|
||||
}
|
||||
|
||||
// lastArchived is the archived body last masked for the card, so opening
|
||||
// its items one by one masks it once
|
||||
var lastArchived struct {
|
||||
sync.Mutex
|
||||
id int64
|
||||
sum [32]byte
|
||||
body []byte
|
||||
}
|
||||
|
||||
func archivedMasked(id int64, body []byte) ([]byte, bool) {
|
||||
if len(body) == 0 || len(body) > promptBodyMax {
|
||||
return nil, false
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
lastArchived.Lock()
|
||||
if lastArchived.id == id && lastArchived.sum == sum {
|
||||
b := lastArchived.body
|
||||
lastArchived.Unlock()
|
||||
return b, true
|
||||
}
|
||||
lastArchived.Unlock()
|
||||
masked := maskedCopy(context.Background(), body)
|
||||
if masked == nil {
|
||||
return nil, false
|
||||
}
|
||||
lastArchived.Lock()
|
||||
lastArchived.id, lastArchived.sum, lastArchived.body = id, sum, masked
|
||||
lastArchived.Unlock()
|
||||
return masked, true
|
||||
}
|
||||
|
||||
// promptTextOf is the part kind of a prompt read from body, its sizes
|
||||
// scaled to tokens, the prompt as the vendor counted it.
|
||||
func promptTextOf(from provider.Protocol, body []byte, id int64, kind string, withText bool, tokens int) (PromptText, bool) {
|
||||
b, ok := promptPieces(from, body)
|
||||
if !ok {
|
||||
return PromptText{}, false
|
||||
}
|
||||
@@ -138,13 +211,9 @@ func (s *Server) PromptText(id int64, kind string, withText bool) (PromptText, b
|
||||
}
|
||||
}
|
||||
scale := 1.0
|
||||
s.trace.mu.Lock()
|
||||
for _, r := range s.trace.routes {
|
||||
if r.ID == id && r.Prompt != nil && r.Prompt.Tokens > 0 && est > 0 {
|
||||
scale = float64(r.Prompt.Tokens) / float64(est)
|
||||
}
|
||||
if tokens > 0 && est > 0 {
|
||||
scale = float64(tokens) / float64(est)
|
||||
}
|
||||
s.trace.mu.Unlock()
|
||||
out := PromptText{ID: id, Kind: kind, Items: []PromptEntry{}, Kept: promptBodies}
|
||||
for key, it := range b.parts[kind] {
|
||||
e := PromptEntry{Name: it.Name, Tag: it.Tag, Tokens: int(float64(it.Tokens)*scale + 0.5)}
|
||||
|
||||
@@ -724,7 +724,7 @@
|
||||
parts = cur = null;
|
||||
return;
|
||||
}
|
||||
rid = r.id;
|
||||
rid = r;
|
||||
const window = p.window || 0;
|
||||
const full = window ? p.tokens / window : 0;
|
||||
const live = !r.done;
|
||||
@@ -971,11 +971,7 @@
|
||||
|
||||
// A part of the card clicked opens what the request sent there, read
|
||||
// from the request's body: an item alone (a tool, a file, a turn), or
|
||||
// the part's items, each opened to its text. magpie keeps the last few
|
||||
// requests' bodies, masked, in memory only, so an older one's text is
|
||||
// gone. A long text comes a stretch at a time, so a prompt of megabytes
|
||||
// doesn't hold the window up.
|
||||
// in ctxtext.js, loaded when a part is first opened
|
||||
// the part's items, each opened to its text (ctxtext.js, loaded then)
|
||||
const openCtxText = (...a) => import("./ctxtext.js").then((m) => m.open({ fmtK, partName, itemName, itemLabel, tagOf }, ...a)).catch(statusErr);
|
||||
window.openCtxText = openCtxText;
|
||||
window.ctxFmt = fmtK;
|
||||
|
||||
@@ -1,19 +1,28 @@
|
||||
// The text of a part of the context window card (context.js): what the
|
||||
// request sent there, opened from the card. context.js imports this when a
|
||||
// part is first opened, so it weighs nothing on the core.
|
||||
// part is first opened, so it weighs nothing on the core. A request whose
|
||||
// body has left memory is read from the request archive, when it kept one,
|
||||
// and the reply beside it (wangbinyq on Discord).
|
||||
const TEXT_STEP = 20000, ITEM_STEP = 100;
|
||||
const ROLE_NAMES = {
|
||||
system: "System prompt", user: "You", assistant: "Assistant", thinking: "Thinking",
|
||||
call: "Tool call", result: "Tool result", tool: "Tool definition", image: "Image", sealed: "Sealed",
|
||||
};
|
||||
async function readText(id, kind, item) {
|
||||
const q = "id=" + encodeURIComponent(id) + "&kind=" + encodeURIComponent(kind) + (item === undefined ? "" : "&item=" + item);
|
||||
// read: /api/context/<what>; a 404 is {archive: why}, why it is gone
|
||||
async function read(what, q) {
|
||||
// fetched, not api(): the text isn't looked through for accounts
|
||||
const res = await fetch("/api/context/text?" + q);
|
||||
if (res.status === 404) return null;
|
||||
const res = await fetch("/api/context/" + what + "?" + new URLSearchParams(q));
|
||||
if (res.status === 404) return { gone: (await res.json().catch(() => ({}))).archive || "off" };
|
||||
if (!res.ok) throw new Error((await res.text()).trim() || res.statusText);
|
||||
return res.json();
|
||||
}
|
||||
const GONE = {
|
||||
off: "This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.",
|
||||
missing: "Not in the request archive: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)",
|
||||
cut: "The request archive kept only the start of this request, so it can't be read",
|
||||
unread: "The request archive's copy couldn't be read or masked, so none of it is shown",
|
||||
};
|
||||
const gone = (why, n) => el("p", "ctx-view-gone", t(GONE[why] || GONE.off, { n }));
|
||||
// a stretch of text, and a button for the next
|
||||
function longText(text) {
|
||||
const box = el("div", "ctx-text-box");
|
||||
@@ -77,9 +86,13 @@ function pieceView(pc) {
|
||||
}
|
||||
return box;
|
||||
}
|
||||
export async function open(kit, id, kind, pick) {
|
||||
export async function open(kit, route, kind, pick) {
|
||||
const { fmtK, partName, itemName, itemLabel, tagOf } = kit;
|
||||
const id = route?.id;
|
||||
if (!id) return;
|
||||
// the day the history keeps it under, for one the gateway no longer holds
|
||||
const day = String(route.time || "").slice(0, 10);
|
||||
const readText = (kind, item) => read("text", { id, kind, day, ...(item === undefined ? {} : { item }) });
|
||||
const ed = el("div", "editor ctx-view wide");
|
||||
const head = el("div", "ehead");
|
||||
const title = el("b", "", partName(kind));
|
||||
@@ -90,19 +103,50 @@ export async function open(kit, id, kind, pick) {
|
||||
const bar = el("div", "bar");
|
||||
const close = el("button", "text primary", t("Close"));
|
||||
close.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); };
|
||||
bar.append(el("span", "grow"), close);
|
||||
// the reply beside it: what the model answered, from memory or the archive
|
||||
const reply = el("button", "text", t("Reply"));
|
||||
reply.type = "button";
|
||||
let view = null;
|
||||
reply.onclick = async (e) => {
|
||||
e.stopPropagation();
|
||||
if (reply.classList.toggle("on")) {
|
||||
reply.textContent = partName(kind);
|
||||
title.textContent = t("Reply");
|
||||
total.textContent = "";
|
||||
body.replaceChildren(el("div", "ctx-view-wait", t("Reading…")));
|
||||
let r;
|
||||
try { r = await read("reply", { id, day }); } catch (err) { r = { err }; }
|
||||
if (confirmAsk !== ed || !reply.classList.contains("on")) return;
|
||||
if (r.err) return body.replaceChildren(el("p", "ctx-view-gone", r.err.message));
|
||||
if (r.gone) return body.replaceChildren(gone(r.gone, 10));
|
||||
const note = el("p", "ctx-view-note", t(r.from === "archive" ? "The reply as the agent got it, read from the request archive, masked where masking is on." : "The reply as the agent got it, masked where masking is on."));
|
||||
body.replaceChildren(note, ...r.pieces.map(pieceView));
|
||||
if (r.cut) body.append(el("p", "ctx-view-note", t("Only the start of the reply was kept")));
|
||||
} else {
|
||||
reply.textContent = t("Reply");
|
||||
title.textContent = partName(kind);
|
||||
if (view) view(); else body.replaceChildren(el("div", "ctx-view-wait", t("Reading…")));
|
||||
}
|
||||
};
|
||||
bar.append(reply, el("span", "grow"), close);
|
||||
ed.append(head, body, bar);
|
||||
confirmAsk = ed;
|
||||
openModal(ed);
|
||||
$("#modal").classList.add("lib");
|
||||
const gone = (n) => el("p", "ctx-view-gone", t("This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.", { n }));
|
||||
let list;
|
||||
try { list = await readText(id, kind); } catch (err) { body.replaceChildren(el("p", "ctx-view-gone", err.message)); return; }
|
||||
const failed = (err) => { view = () => body.replaceChildren(el("p", "ctx-view-gone", err.message)); };
|
||||
try { list = await readText(kind); } catch (err) { failed(err); }
|
||||
if (confirmAsk !== ed) return;
|
||||
if (!list) return body.replaceChildren(gone(10));
|
||||
if (!list) return reply.classList.contains("on") || view();
|
||||
if (list.gone) {
|
||||
view = () => body.replaceChildren(gone(list.gone, 10));
|
||||
return reply.classList.contains("on") || view();
|
||||
}
|
||||
const items = list.items || [];
|
||||
total.textContent = fmtK(items.reduce((s, it) => s + it.tokens, 0)) + " " + t("tokens");
|
||||
const note = el("p", "ctx-view-note", t("As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.", { n: list.kept }));
|
||||
const sum = () => fmtK(items.reduce((s, it) => s + it.tokens, 0)) + " " + t("tokens");
|
||||
const note = el("p", "ctx-view-note", list.from === "archive"
|
||||
? t("As magpie sent it, read from the request archive, masked where masking is on.")
|
||||
: t("As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.", { n: list.kept }));
|
||||
// an item: its text alone; "N more" or the earlier turns: the part's list
|
||||
const at = pick && pick.tag !== "more" && pick.tag !== "turns"
|
||||
? items.findIndex((it) => it.name === pick.name && (it.tag || "") === (pick.tag || "")) : -1;
|
||||
@@ -127,9 +171,9 @@ export async function open(kit, id, kind, pick) {
|
||||
box.classList.toggle("open", on);
|
||||
if (!on || read) return;
|
||||
text.replaceChildren(el("div", "ctx-view-wait", t("Reading…")));
|
||||
read = readText(id, kind, i).then((one) => {
|
||||
read = readText(kind, i).then((one) => {
|
||||
const pieces = one?.items?.[i]?.pieces;
|
||||
if (!pieces) { read = null; text.replaceChildren(gone(list.kept)); return; }
|
||||
if (!pieces) { read = null; text.replaceChildren(gone(one?.gone, list.kept)); return; }
|
||||
text.replaceChildren(...(pieces.length ? pieces.map(pieceView) : [el("div", "ctx-piece-note", t("Empty"))]));
|
||||
}).catch((err) => { read = null; text.replaceChildren(el("p", "ctx-view-gone", err.message)); });
|
||||
};
|
||||
@@ -139,7 +183,9 @@ export async function open(kit, id, kind, pick) {
|
||||
return box;
|
||||
};
|
||||
const showAll = () => {
|
||||
view = showAll;
|
||||
title.textContent = partName(kind);
|
||||
total.textContent = sum();
|
||||
const rows = el("div", "ctx-vi-list");
|
||||
let shown = 0;
|
||||
const more = el("button", "text ctx-text-more");
|
||||
@@ -155,18 +201,23 @@ export async function open(kit, id, kind, pick) {
|
||||
step();
|
||||
body.replaceChildren(note, items.length ? rows : el("div", "ctx-empty", t("Nothing in it")), more);
|
||||
};
|
||||
if (at < 0) return showAll();
|
||||
// the item alone, the part's other items a click away
|
||||
title.textContent = partName(kind) + " · " + itemName(items[at]);
|
||||
total.textContent = fmtK(items[at].tokens) + " " + t("tokens");
|
||||
const all = el("button", "text ctx-view-all", t("All of {part} · {n}", { part: partName(kind), n: items.length }));
|
||||
all.type = "button";
|
||||
all.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
all.remove();
|
||||
total.textContent = fmtK(items.reduce((s, it) => s + it.tokens, 0)) + " " + t("tokens");
|
||||
showAll();
|
||||
};
|
||||
if (items.length > 1) bar.prepend(all);
|
||||
body.replaceChildren(note, entry(items[at], at, true));
|
||||
if (at < 0) view = showAll;
|
||||
else {
|
||||
// the item alone, the part's other items a click away
|
||||
const all = el("button", "text ctx-view-all", t("All of {part} · {n}", { part: partName(kind), n: items.length }));
|
||||
all.type = "button";
|
||||
all.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
all.remove();
|
||||
if (reply.classList.contains("on")) reply.click();
|
||||
showAll();
|
||||
};
|
||||
if (items.length > 1) bar.prepend(all);
|
||||
view = () => {
|
||||
title.textContent = partName(kind) + " · " + itemName(items[at]);
|
||||
total.textContent = fmtK(items[at].tokens) + " " + t("tokens");
|
||||
body.replaceChildren(note, entry(items[at], at, true));
|
||||
};
|
||||
}
|
||||
if (!reply.classList.contains("on")) view();
|
||||
}
|
||||
|
||||
@@ -94,6 +94,13 @@ const I18N = {
|
||||
"Sealed by the vendor, {n} bytes: only the vendor can read it": "服务商已加密,{n} 字节:只有服务商能读",
|
||||
"This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "这个请求的原文已不再保留:magpie 只在运行期间、仅在内存中保留最近 {n} 个请求的原文。",
|
||||
"As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "即 magpie 发出的内容,开启脱敏时为脱敏后的内容。仅在内存中保留最近 {n} 个请求。",
|
||||
"Not in the request archive: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)": "不在请求存档中:存档在调用结束后才保存,超出存档大小时最早的会被删除,也可能保存失败了(原因见 magpie 的日志)",
|
||||
"The request archive kept only the start of this request, so it can't be read": "请求存档只保留了这个请求的开头,无法读取",
|
||||
"The request archive's copy couldn't be read or masked, so none of it is shown": "无法读取或脱敏请求存档中的副本,因此不显示任何内容",
|
||||
"As magpie sent it, read from the request archive, masked where masking is on.": "即 magpie 发出的内容,读自请求存档,开启脱敏时为脱敏后的内容。",
|
||||
"The reply as the agent got it, read from the request archive, masked where masking is on.": "即 agent 收到的回复,读自请求存档,开启脱敏时为脱敏后的内容。",
|
||||
"The reply as the agent got it, masked where masking is on.": "即 agent 收到的回复,开启脱敏时为脱敏后的内容。",
|
||||
"Only the start of the reply was kept": "只保留了回复的开头",
|
||||
"All of {part} · {n}": "全部{part} · {n}",
|
||||
"{n} on {date}": "{date} {n}",
|
||||
"roles": "角色",
|
||||
@@ -4580,6 +4587,13 @@ const I18N = {
|
||||
"Sealed by the vendor, {n} bytes: only the vendor can read it": "服務商已加密,{n} 位元組:只有服務商能讀",
|
||||
"This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "這個請求的原文已不再保留:magpie 只在執行期間、僅在記憶體中保留最近 {n} 個請求的原文。",
|
||||
"As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "即 magpie 送出的內容,開啟遮罩時為遮罩後的內容。僅在記憶體中保留最近 {n} 個請求。",
|
||||
"Not in the request archive: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)": "不在請求存檔中:存檔在呼叫結束後才儲存,超出存檔大小時最早的會被刪除,也可能儲存失敗了(原因見 magpie 的日誌)",
|
||||
"The request archive kept only the start of this request, so it can't be read": "請求存檔只保留了這個請求的開頭,無法讀取",
|
||||
"The request archive's copy couldn't be read or masked, so none of it is shown": "無法讀取或遮罩請求存檔中的副本,因此不顯示任何內容",
|
||||
"As magpie sent it, read from the request archive, masked where masking is on.": "即 magpie 送出的內容,讀自請求存檔,開啟遮罩時為遮罩後的內容。",
|
||||
"The reply as the agent got it, read from the request archive, masked where masking is on.": "即 agent 收到的回覆,讀自請求存檔,開啟遮罩時為遮罩後的內容。",
|
||||
"The reply as the agent got it, masked where masking is on.": "即 agent 收到的回覆,開啟遮罩時為遮罩後的內容。",
|
||||
"Only the start of the reply was kept": "只保留了回覆的開頭",
|
||||
"All of {part} · {n}": "全部{part} · {n}",
|
||||
"{n} on {date}": "{date} {n}",
|
||||
"roles": "角色",
|
||||
@@ -9041,6 +9055,13 @@ const I18N = {
|
||||
"Sealed by the vendor, {n} bytes: only the vendor can read it": "ベンダーが暗号化済み、{n} バイト:読めるのはベンダーだけです",
|
||||
"This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "このリクエストの本文はもう保持されていません。magpie は直近 {n} 件のリクエストの本文を、実行中にメモリ内だけで保持します。",
|
||||
"As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "magpie が送信したとおりの内容です(マスキングが有効ならマスク済み)。直近 {n} 件のリクエストだけをメモリ内に保持します。",
|
||||
"Not in the request archive: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)": "リクエストアーカイブにありません。アーカイブは呼び出しの直後に保存され、サイズを超えると古いものから削除されます。保存に失敗した可能性もあります(理由は magpie のログにあります)",
|
||||
"The request archive kept only the start of this request, so it can't be read": "リクエストアーカイブにはこのリクエストの先頭しか残っていないため、読み取れません",
|
||||
"The request archive's copy couldn't be read or masked, so none of it is shown": "リクエストアーカイブのコピーを読み取れないかマスクできないため、何も表示しません",
|
||||
"As magpie sent it, read from the request archive, masked where masking is on.": "magpie が送信したとおりの内容です。リクエストアーカイブから読み取り、マスキングが有効ならマスク済みです。",
|
||||
"The reply as the agent got it, read from the request archive, masked where masking is on.": "エージェントが受け取ったとおりの返信です。リクエストアーカイブから読み取り、マスキングが有効ならマスク済みです。",
|
||||
"The reply as the agent got it, masked where masking is on.": "エージェントが受け取ったとおりの返信です(マスキングが有効ならマスク済み)。",
|
||||
"Only the start of the reply was kept": "返信の先頭だけが残っています",
|
||||
"All of {part} · {n}": "{part}をすべて · {n}",
|
||||
"{n} on {date}": "{date} {n}",
|
||||
"roles": "ロール",
|
||||
@@ -13509,6 +13530,13 @@ const I18N = {
|
||||
"Sealed by the vendor, {n} bytes: only the vendor can read it": "Vom Anbieter versiegelt, {n} Bytes: nur der Anbieter kann es lesen",
|
||||
"This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "Der Text dieser Anfrage wird nicht mehr aufbewahrt: magpie behält den Text der letzten {n} Anfragen nur im Arbeitsspeicher, solange es läuft.",
|
||||
"As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "So, wie magpie es gesendet hat, maskiert, wo Maskierung an ist. Nur für die letzten {n} Anfragen im Arbeitsspeicher aufbewahrt.",
|
||||
"Not in the request archive: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)": "Nicht im Anfragearchiv: Es wird direkt nach dem Aufruf gespeichert, die ältesten werden über der Archivgröße entfernt, oder das Speichern ist fehlgeschlagen (magpies Protokoll sagt, warum)",
|
||||
"The request archive kept only the start of this request, so it can't be read": "Das Anfragearchiv hat nur den Anfang dieser Anfrage behalten, daher lässt sie sich nicht lesen",
|
||||
"The request archive's copy couldn't be read or masked, so none of it is shown": "Die Kopie im Anfragearchiv ließ sich nicht lesen oder maskieren, daher wird nichts davon gezeigt",
|
||||
"As magpie sent it, read from the request archive, masked where masking is on.": "So, wie magpie es gesendet hat, aus dem Anfragearchiv gelesen, maskiert, wo Maskierung an ist.",
|
||||
"The reply as the agent got it, read from the request archive, masked where masking is on.": "Die Antwort, wie der Agent sie bekam, aus dem Anfragearchiv gelesen, maskiert, wo Maskierung an ist.",
|
||||
"The reply as the agent got it, masked where masking is on.": "Die Antwort, wie der Agent sie bekam, maskiert, wo Maskierung an ist.",
|
||||
"Only the start of the reply was kept": "Nur der Anfang der Antwort wurde behalten",
|
||||
"All of {part} · {n}": "Alle: {part} · {n}",
|
||||
"{n} on {date}": "{n} am {date}",
|
||||
"roles": "Rollen",
|
||||
|
||||
+12
-8
@@ -766,7 +766,8 @@ func contextRoutesAPI(mux *http.ServeMux) {
|
||||
// the text of a part of a request's prompt (masaka on Discord): the
|
||||
// part's items, and one item's text when item is given. From the
|
||||
// gateway this GUI runs, which keeps the last requests' masked bodies
|
||||
// in memory only; 404 when the request's is no longer kept.
|
||||
// in memory only, else from the request archive; 404 with why when
|
||||
// neither has it.
|
||||
mux.HandleFunc("GET /api/context/text", func(rw http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
id, err := strconv.ParseInt(q.Get("id"), 10, 64)
|
||||
@@ -781,15 +782,17 @@ func contextRoutesAPI(mux *http.ServeMux) {
|
||||
return
|
||||
}
|
||||
}
|
||||
gw := served.Load()
|
||||
if gw == nil {
|
||||
http.Error(rw, "not kept", http.StatusNotFound)
|
||||
return
|
||||
var pt gateway.PromptText
|
||||
ok := false
|
||||
if gw := served.Load(); gw != nil {
|
||||
pt, ok = gw.PromptText(id, q.Get("kind"), item >= 0)
|
||||
}
|
||||
pt, ok := gw.PromptText(id, q.Get("kind"), item >= 0)
|
||||
if !ok {
|
||||
http.Error(rw, "not kept", http.StatusNotFound)
|
||||
return
|
||||
// gone from memory: the request archive's copy, when it
|
||||
// kept one (context_archive.go)
|
||||
if pt, ok = archivedPromptText(rw, r, id, q.Get("kind"), item >= 0); !ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
if item >= 0 {
|
||||
// the one item's text; the rest by name and size only
|
||||
@@ -809,4 +812,5 @@ func contextRoutesAPI(mux *http.ServeMux) {
|
||||
rw.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(rw, pt)
|
||||
})
|
||||
contextReplyAPI(mux)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
package gui
|
||||
|
||||
// The context window card's text, and the reply beside it, read from the
|
||||
// request archive once a request's body has left memory (wangbinyq on
|
||||
// Discord: with the archive on, the card still said the text was gone, as
|
||||
// magpie keeps only the last 10 requests' bodies in memory). The archive
|
||||
// keeps the body as the agent sent it and the reply as the agent got it,
|
||||
// their secrets taken out; gateway.ArchivedPromptText and
|
||||
// gateway.ReplyPieces mask them as the body in memory is, so the archive
|
||||
// shows nothing the memory's copy wouldn't.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/davsync"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// ctxGone says why a request's text can't be shown, for the card to say:
|
||||
// "off" when the archive has no copy named for the request (it was off,
|
||||
// or the route is gone), "missing" when it names one the archive doesn't
|
||||
// have (not saved or uploaded yet, or removed past its size), "cut" when
|
||||
// the archive kept only the start of it, "unread" when it can't be read
|
||||
// or masked: nothing is shown unmasked in its place.
|
||||
type ctxGone struct {
|
||||
Archive string `json:"archive"`
|
||||
}
|
||||
|
||||
func writeGone(rw http.ResponseWriter, why string) {
|
||||
rw.Header().Set("Content-Type", "application/json")
|
||||
rw.Header().Set("Cache-Control", "no-store")
|
||||
rw.WriteHeader(http.StatusNotFound)
|
||||
json.NewEncoder(rw).Encode(ctxGone{Archive: why})
|
||||
}
|
||||
|
||||
// ctxRouteOf is request id's route, from the gateway this GUI runs or, for a
|
||||
// request it no longer holds, the history of day (the page's ?day=).
|
||||
func ctxRouteOf(r *http.Request, id int64) (gateway.Route, bool) {
|
||||
if gw := served.Load(); gw != nil {
|
||||
for _, route := range gw.Trace(r.Context(), 0, 0).Routes {
|
||||
if route.ID == id {
|
||||
return route, true
|
||||
}
|
||||
}
|
||||
}
|
||||
day, err := time.Parse("2006-01-02", r.URL.Query().Get("day"))
|
||||
if err != nil {
|
||||
return gateway.Route{}, false
|
||||
}
|
||||
return gateway.HistoryRoute(id, day)
|
||||
}
|
||||
|
||||
// archivedCopy is a call as the archive kept it, read from this computer's
|
||||
// archive, else the bucket, as the Routing page's archivePanel reads it
|
||||
// (openArchive). The last one read is kept, in memory, so the items opened
|
||||
// one by one read it once.
|
||||
type archivedCopy struct {
|
||||
name string
|
||||
from provider.Protocol
|
||||
request gateway.ArchivePart
|
||||
response gateway.ArchivePart
|
||||
}
|
||||
|
||||
// lastCallFor is how long the last call read is kept
|
||||
const lastCallFor = 5 * time.Minute
|
||||
|
||||
var lastCall struct {
|
||||
sync.Mutex
|
||||
c archivedCopy
|
||||
}
|
||||
|
||||
var errNotArchived = errors.New("not archived")
|
||||
|
||||
func readArchived(ctx context.Context, archive string) (archivedCopy, error) {
|
||||
date, id, ok := strings.Cut(archive, "/")
|
||||
if !ok {
|
||||
return archivedCopy{}, errNotArchived
|
||||
}
|
||||
name, ok := gateway.ArchiveName(date, id)
|
||||
if !ok {
|
||||
return archivedCopy{}, errNotArchived
|
||||
}
|
||||
lastCall.Lock()
|
||||
if lastCall.c.name == name {
|
||||
c := lastCall.c
|
||||
lastCall.Unlock()
|
||||
return c, nil
|
||||
}
|
||||
lastCall.Unlock()
|
||||
body, size, err := openArchiveName(ctx, name)
|
||||
if err != nil {
|
||||
return archivedCopy{}, err
|
||||
}
|
||||
defer body.Close()
|
||||
if size > archiveReadMost {
|
||||
return archivedCopy{}, errArchiveCut
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(body, archiveReadMost+1))
|
||||
if err != nil {
|
||||
return archivedCopy{}, err
|
||||
}
|
||||
if len(data) > archiveReadMost {
|
||||
return archivedCopy{}, errArchiveCut
|
||||
}
|
||||
var a gateway.Archived
|
||||
if err := json.Unmarshal(data, &a); err != nil {
|
||||
return archivedCopy{}, errArchiveCut
|
||||
}
|
||||
c := archivedCopy{name: name, from: a.Call.From, request: a.Request, response: a.Response}
|
||||
lastCall.Lock()
|
||||
lastCall.c = c
|
||||
lastCall.Unlock()
|
||||
// let go of it once the card is likely closed: it can be two bodies
|
||||
// of the archive's 32 MiB
|
||||
time.AfterFunc(lastCallFor, func() {
|
||||
lastCall.Lock()
|
||||
if lastCall.c.name == name {
|
||||
lastCall.c = archivedCopy{}
|
||||
}
|
||||
lastCall.Unlock()
|
||||
})
|
||||
return c, nil
|
||||
}
|
||||
|
||||
var errArchiveCut = errors.New("the archive's copy can't be read whole")
|
||||
|
||||
// openArchiveName opens the archive's file name, this computer's first;
|
||||
// errNotArchived when neither it nor the bucket has it.
|
||||
func openArchiveName(ctx context.Context, name string) (io.ReadCloser, int64, error) {
|
||||
if body, size, err := localArchive().Open(ctx, name); !errors.Is(err, gateway.ErrNotArchived) {
|
||||
return body, size, err
|
||||
}
|
||||
b, ok := archiveBucket()
|
||||
if !ok {
|
||||
return nil, 0, errNotArchived
|
||||
}
|
||||
body, size, err := b.Open(ctx, name)
|
||||
if errors.Is(err, davsync.ErrNoObject) {
|
||||
return nil, 0, errNotArchived
|
||||
}
|
||||
return body, size, err
|
||||
}
|
||||
|
||||
// archiveGone is the ctxGone of an error reading a route's archive; ""
|
||||
// for one the page shows as it is (a bucket that failed to answer: not
|
||||
// known to be gone).
|
||||
func archiveGone(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, errNotArchived):
|
||||
return "missing"
|
||||
case errors.Is(err, errArchiveCut):
|
||||
return "cut"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// archivedPromptText answers /api/context/text from the archive, for a
|
||||
// request whose body has left memory.
|
||||
func archivedPromptText(rw http.ResponseWriter, r *http.Request, id int64, kind string, withText bool) (gateway.PromptText, bool) {
|
||||
route, ok := ctxRouteOf(r, id)
|
||||
if !ok || route.Archive == "" {
|
||||
writeGone(rw, "off")
|
||||
return gateway.PromptText{}, false
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
|
||||
defer cancel()
|
||||
c, err := readArchived(ctx, route.Archive)
|
||||
if err != nil {
|
||||
if why := archiveGone(err); why != "" {
|
||||
writeGone(rw, why)
|
||||
} else {
|
||||
fail(rw, err)
|
||||
}
|
||||
return gateway.PromptText{}, false
|
||||
}
|
||||
if c.request.Truncated {
|
||||
writeGone(rw, "cut")
|
||||
return gateway.PromptText{}, false
|
||||
}
|
||||
tokens := 0
|
||||
if route.Prompt != nil {
|
||||
tokens = route.Prompt.Tokens
|
||||
}
|
||||
pt, ok := gateway.ArchivedPromptText(c.from, []byte(c.request.Body), id, kind, withText, tokens)
|
||||
if !ok {
|
||||
writeGone(rw, "unread")
|
||||
return gateway.PromptText{}, false
|
||||
}
|
||||
return pt, true
|
||||
}
|
||||
|
||||
// contextReplyAPI serves the reply to a request the card shows: from the
|
||||
// gateway's Recent calls while it holds the call, else from the archive.
|
||||
func contextReplyAPI(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/context/reply", func(rw http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
http.Error(rw, "invalid route id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
out := gateway.PromptReply{ID: id, From: "memory"}
|
||||
var (
|
||||
from provider.Protocol
|
||||
body []byte
|
||||
cut bool
|
||||
have bool
|
||||
)
|
||||
if gw := served.Load(); gw != nil {
|
||||
from, body, cut, have = gw.ReplyBody(id)
|
||||
}
|
||||
if !have {
|
||||
route, ok := ctxRouteOf(r, id)
|
||||
if !ok || route.Archive == "" {
|
||||
writeGone(rw, "off")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
|
||||
defer cancel()
|
||||
c, err := readArchived(ctx, route.Archive)
|
||||
if err != nil {
|
||||
if why := archiveGone(err); why != "" {
|
||||
writeGone(rw, why)
|
||||
} else {
|
||||
fail(rw, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
from, body, cut, out.From = c.from, []byte(c.response.Body), c.response.Truncated, "archive"
|
||||
}
|
||||
pieces, cut, ok := gateway.ReplyPieces(from, body, cut)
|
||||
if !ok {
|
||||
writeGone(rw, "unread")
|
||||
return
|
||||
}
|
||||
out.Pieces, out.Cut = pieces, cut
|
||||
rw.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(rw, out)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/gwmw"
|
||||
"github.com/yetone/magpie/internal/masking"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// wangbinyq on Discord: clicking a block of the context window card said
|
||||
// its text was gone, as magpie keeps only the last 10 requests' bodies in
|
||||
// memory, with the request archive on. The archive's copy is read instead,
|
||||
// the reply beside it, masked as the copy in memory is; a request the
|
||||
// archive has no copy of says why.
|
||||
func TestContextTextFromTheArchive(t *testing.T) {
|
||||
h := archiveHome(t, fakeArchive{objs: map[string][]byte{}})
|
||||
archiveBucket = func() (archiveStore, bool) { return nil, false }
|
||||
unmask := gwmw.Mask(masking.Masker{})
|
||||
t.Cleanup(unmask)
|
||||
prev := served.Swap(nil)
|
||||
t.Cleanup(func() { served.Store(prev) })
|
||||
if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true, RequestArchiveLocal: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lastCall.Lock()
|
||||
lastCall.c = archivedCopy{}
|
||||
lastCall.Unlock()
|
||||
|
||||
const phone = "13800138000"
|
||||
req := `{"model":"m","system":"You are the release agent.","messages":[{"role":"user","content":"call me at ` + phone + ` once it ships"}]}`
|
||||
res := `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"I will call ` + phone + ` when it ships."}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":9}}`
|
||||
obj, _ := json.Marshal(gateway.Archived{ID: "2026-10-02/101010-00000000000000aa", Call: gateway.Call{Model: "p/m", Status: 200, From: provider.Anthropic},
|
||||
Request: gateway.ArchivePart{Method: "POST", Path: "/v1/messages", Body: req, Size: int64(len(req))},
|
||||
Response: gateway.ArchivePart{Status: 200, Body: res, Size: int64(len(res))}})
|
||||
if err := gateway.LocalArchive().Put(context.Background(), archiveObject, obj); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
day := time.Date(2026, 10, 2, 10, 10, 10, 0, time.Local)
|
||||
route := func(id int64, archive string) []byte {
|
||||
r := ctxRoute(id, "claude", "s1", 3000, 1000, 200000, 0)
|
||||
r.Time, r.Archive = day, archive
|
||||
b, _ := json.Marshal(r)
|
||||
return append(b, '\n')
|
||||
}
|
||||
os.MkdirAll(gateway.HistoryDir(), 0o700)
|
||||
lines := append(route(41, "2026-10-02/101010-00000000000000aa"), route(42, "")...)
|
||||
lines = append(lines, route(43, "2026-10-02/101010-00000000000000bb")...)
|
||||
os.WriteFile(filepath.Join(gateway.HistoryDir(), "2026-10-02.jsonl"), lines, 0o600)
|
||||
|
||||
get := func(url string) (int, string) {
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest("GET", url, nil))
|
||||
return rec.Code, rec.Body.String()
|
||||
}
|
||||
code, body := get("/api/context/text?id=41&kind=chat&item=0&day=2026-10-02")
|
||||
var pt gateway.PromptText
|
||||
json.Unmarshal([]byte(body), &pt)
|
||||
if code != 200 || pt.From != "archive" || len(pt.Items) != 1 || !strings.Contains(body, "once it ships") || strings.Contains(body, phone) {
|
||||
t.Fatalf("text: %d %s", code, body)
|
||||
}
|
||||
if code, body := get("/api/context/text?id=41&kind=system&item=0&day=2026-10-02"); code != 200 || !strings.Contains(body, "You are the release agent.") {
|
||||
t.Fatalf("system: %d %s", code, body)
|
||||
}
|
||||
code, body = get("/api/context/reply?id=41&day=2026-10-02")
|
||||
var rp gateway.PromptReply
|
||||
json.Unmarshal([]byte(body), &rp)
|
||||
if code != 200 || rp.From != "archive" || len(rp.Pieces) != 1 || !strings.Contains(body, "when it ships") || strings.Contains(body, phone) {
|
||||
t.Fatalf("reply: %d %s", code, body)
|
||||
}
|
||||
// no copy named for it: the archive was off
|
||||
for _, url := range []string{"/api/context/text?id=42&kind=chat&day=2026-10-02", "/api/context/reply?id=42&day=2026-10-02", "/api/context/text?id=99&kind=chat"} {
|
||||
if code, body := get(url); code != http.StatusNotFound || !strings.Contains(body, `"archive":"off"`) {
|
||||
t.Fatalf("%s: %d %s", url, code, body)
|
||||
}
|
||||
}
|
||||
// one named and not there
|
||||
if code, body := get("/api/context/text?id=43&kind=chat&day=2026-10-02"); code != http.StatusNotFound || !strings.Contains(body, `"archive":"missing"`) {
|
||||
t.Fatalf("missing: %d %s", code, body)
|
||||
}
|
||||
// with masking wanted and the masker failing, nothing is shown: one
|
||||
// served last serves, whatever another test left registered
|
||||
broken := gwmw.Mask(failingMasker{})
|
||||
defer broken()
|
||||
if code, body := get("/api/context/reply?id=41&day=2026-10-02"); code != http.StatusNotFound || !strings.Contains(body, `"archive":"unread"`) || strings.Contains(body, phone) {
|
||||
t.Fatalf("unmasked: %d %s", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
// failingMasker is a masker that can't mask: Safely takes its panic as a
|
||||
// failure
|
||||
type failingMasker struct{}
|
||||
|
||||
func (failingMasker) JSON([]byte) ([]byte, int) { panic("can't mask") }
|
||||
func (failingMasker) Text(string) (string, int) { panic("can't mask") }
|
||||
func (failingMasker) Restore(s string, _ bool) string { return s }
|
||||
func (failingMasker) Writer(w http.ResponseWriter) (http.ResponseWriter, func()) { return w, func() {} }
|
||||
@@ -230,7 +230,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
|
||||
// an image the request sent inline is shown in its turn; one it
|
||||
// didn't send that way is named
|
||||
await page.evaluate(() => window.openCtxText(19, "chat"));
|
||||
await page.evaluate(() => window.openCtxText({ id: 19 }, "chat"));
|
||||
await view.locator(".ctx-vi-head").nth(1).click();
|
||||
const pic = view.locator(".ctx-vi.open .ctx-pic");
|
||||
await pic.locator("img").waitFor();
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
// the request sent there. A part of the legend opens its items, each
|
||||
// opened to its text; a row or a cell opens its item alone, the part's
|
||||
// other items a click away; a long text comes a stretch at a time; a
|
||||
// request whose text is no longer kept says so. Nothing moves the page,
|
||||
// request whose text is no longer kept says so. wangbinyq on Discord: with
|
||||
// the request archive on, an older request's text is read from it, and a
|
||||
// request's reply opens beside its text, from memory or the archive; one
|
||||
// the archive has no copy of says why. Nothing moves the page,
|
||||
// the keyboard opens it too, in every language, at a desk and a phone's
|
||||
// width.
|
||||
const assert = require("node:assert/strict");
|
||||
@@ -62,11 +65,22 @@ const texts = {
|
||||
chat: [{ name: "1", tag: "turn", tokens: 300, pieces: [{ role: "user", text: "port the parser" }, { role: "thinking", text: "", size: 900 }, { role: "call", name: "exec_command", text: "{\"cmd\": \"ls\"}" }] },
|
||||
{ name: "2", tag: "turn", tokens: 500, pieces: [{ role: "image" }, { role: "assistant", text: "Done." }] }],
|
||||
};
|
||||
// 19's in memory, 31's read from the archive; 30's the archive never
|
||||
// kept, 32's it named and doesn't have
|
||||
function text(url, r) {
|
||||
if (url.searchParams.get("id") !== "19") return r.fulfill({ status: 404, body: "not kept" });
|
||||
const id = url.searchParams.get("id");
|
||||
if (id === "30") return r.fulfill({ status: 404, json: { archive: "off" } });
|
||||
if (id === "32") return r.fulfill({ status: 404, json: { archive: "missing" } });
|
||||
if (id !== "19" && id !== "31") return r.fulfill({ status: 404, body: "not kept" });
|
||||
const kind = url.searchParams.get("kind"), item = url.searchParams.get("item");
|
||||
const items = (texts[kind] || []).map((it, i) => item !== null && +item === i ? it : { ...it, pieces: undefined });
|
||||
return r.fulfill({ json: { id: 19, kind, items, kept: 10 } });
|
||||
return r.fulfill({ json: { id: +id, kind, items, kept: 10, ...(id === "31" ? { from: "archive" } : {}) } });
|
||||
}
|
||||
function reply(url, r) {
|
||||
const id = url.searchParams.get("id");
|
||||
if (id === "30") return r.fulfill({ status: 404, json: { archive: "off" } });
|
||||
const pieces = [{ role: "thinking", text: "Look first." }, { role: "assistant", text: "Ported, call me at [PHONE_1]." }, { role: "call", name: "exec_command", text: "{\"cmd\": \"go test\"}" }];
|
||||
return r.fulfill({ json: { id: +id, pieces, cut: id === "31", from: id === "31" ? "archive" : "memory" } });
|
||||
}
|
||||
|
||||
function serve(lang, asked) {
|
||||
@@ -78,12 +92,13 @@ function serve(lang, asked) {
|
||||
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/context") {
|
||||
asked.push(url.searchParams.get("days"));
|
||||
asked.push("days=" + url.searchParams.get("days"));
|
||||
return json(context(+url.searchParams.get("days")));
|
||||
}
|
||||
// the text comes a moment after it is asked, as it does under load:
|
||||
// the dialog says "Reading…" first, and the test waits past it
|
||||
if (url.pathname === "/api/context/text") { await new Promise((ok) => setTimeout(ok, 200)); return text(url, r); }
|
||||
if (url.pathname === "/api/context/text") { asked.push("text?" + url.searchParams); await new Promise((ok) => setTimeout(ok, 200)); return text(url, r); }
|
||||
if (url.pathname === "/api/context/reply") { await new Promise((ok) => setTimeout(ok, 200)); return reply(url, r); }
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) return new Promise(() => {});
|
||||
return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
|
||||
@@ -125,11 +140,11 @@ async function wheelTo(page, l) {
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { tools: "Tools", files: "Files", close: "Close", sys: "System prompt", all: "All of" },
|
||||
zh: { tools: "工具", files: "文件", close: "关闭", sys: "系统提示词", all: "全部" },
|
||||
"zh-TW": { tools: "工具", files: "檔案", close: "關閉", sys: "系統提示詞", all: "全部" },
|
||||
ja: { tools: "ツール", files: "ファイル", close: "閉じる", sys: "システムプロンプト", all: "すべて" },
|
||||
de: { tools: "Tools", files: "Dateien", close: "Schließen", sys: "Systemprompt", all: "Alle" },
|
||||
en: { tools: "Tools", files: "Files", close: "Close", sys: "System prompt", all: "All of", reply: "Reply", archive: "request archive" },
|
||||
zh: { tools: "工具", files: "文件", close: "关闭", sys: "系统提示词", all: "全部", reply: "回复", archive: "请求存档" },
|
||||
"zh-TW": { tools: "工具", files: "檔案", close: "關閉", sys: "系統提示詞", all: "全部", reply: "回覆", archive: "請求存檔" },
|
||||
ja: { tools: "ツール", files: "ファイル", close: "閉じる", sys: "システムプロンプト", all: "すべて", reply: "返信", archive: "リクエストアーカイブ" },
|
||||
de: { tools: "Tools", files: "Dateien", close: "Schließen", sys: "Systemprompt", all: "Alle", reply: "Antwort", archive: "Anfragearchiv" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
@@ -219,10 +234,49 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.equal(await view.locator(".ctx-vi.open .ctx-piece-note").count(), 1, "the sealed reasoning is named");
|
||||
await close();
|
||||
|
||||
// a request whose text is no longer kept says so
|
||||
await page.evaluate(() => window.openCtxText(30, "tools"));
|
||||
// the text asks for the request's day, for the archive to find it
|
||||
assert.ok(asked.some((q) => /^text\?id=19&kind=\w+&day=\d{4}-\d\d-\d\d/.test(q)), asked.join(" "));
|
||||
|
||||
// a request's reply beside its text, and back
|
||||
const replyBtn = () => view.locator(".bar button", { hasText: w.reply });
|
||||
await leg.click();
|
||||
await view.locator(".ctx-vi-head").first().waitFor();
|
||||
await replyBtn().click();
|
||||
await view.locator(".ctx-text", { hasText: "Ported, call me at [PHONE_1]." }).waitFor();
|
||||
assert.equal(await view.locator(".ctx-piece").count(), 3);
|
||||
assert.match(await view.locator(".ehead b").innerText(), new RegExp(w.reply));
|
||||
assert.doesNotMatch(await view.locator(".ctx-view-note").first().innerText(), new RegExp(w.archive));
|
||||
await view.locator(".bar button", { hasText: w.tools }).click();
|
||||
await view.locator(".ctx-vi-head", { hasText: "exec_command" }).waitFor();
|
||||
assert.match(await view.locator(".ehead b").innerText(), new RegExp(w.tools));
|
||||
await close();
|
||||
|
||||
// an older request's text from the archive, its reply too, cut short
|
||||
const old = { id: 31, time: ago(60 * 30) };
|
||||
await page.evaluate((r) => window.openCtxText(r, "tools"), old);
|
||||
await view.locator(".ctx-vi-head", { hasText: "exec_command" }).waitFor();
|
||||
assert.match(await view.locator(".ctx-view-note").innerText(), new RegExp(w.archive));
|
||||
await replyBtn().click();
|
||||
await view.locator(".ctx-text", { hasText: "Ported" }).waitFor();
|
||||
assert.equal(await view.locator(".ctx-view-note").count(), 2, "the reply says it is read from the archive, and cut short");
|
||||
assert.match(await view.locator(".ctx-view-note").first().innerText(), new RegExp(w.archive));
|
||||
await close();
|
||||
|
||||
// a request whose text is no longer kept says so, its reply too
|
||||
await page.evaluate(() => window.openCtxText({ id: 30, time: new Date().toISOString() }, "tools"));
|
||||
await view.locator(".ctx-view-gone").waitFor();
|
||||
assert.match(await view.locator(".ctx-view-gone").innerText(), /10/);
|
||||
await replyBtn().click();
|
||||
await view.locator(".ctx-view-gone").waitFor();
|
||||
assert.match(await view.locator(".ctx-view-gone").innerText(), /10/);
|
||||
await close();
|
||||
|
||||
// one the archive named and doesn't have says the archive lost it
|
||||
await page.evaluate(() => window.openCtxText({ id: 32, time: new Date().toISOString() }, "tools"));
|
||||
await view.locator(".ctx-view-gone").waitFor();
|
||||
const lost = await view.locator(".ctx-view-gone").innerText();
|
||||
assert.match(lost, new RegExp(w.archive));
|
||||
assert.doesNotMatch(lost, /10/);
|
||||
await close();
|
||||
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), "the page scrolls sideways");
|
||||
|
||||
Reference in New Issue
Block a user