itieniu asked for a "ding" when a long Claude Code or OpenCode task
finishes. magpie sees every request an agent sends through it, so the
gateway now follows each agent session's turn and the app notifies at
its end.
Gateway (turndone.go): a request is of the turn unless it is one the
agent makes on the side (Kind) or a Claude Code subagent's. Its reply is
scanned on the way to the agent for a tool call in every wire format
(Anthropic tool_use, Chat tool_calls/function_call, Responses
function_call/custom_tool_call/local_shell_call/..., Gemini
functionCall), as a JSON value, never a key ("tool_calls":[]) or text.
The turn is done when no request of it is going, the last reply was
whole, under 400 and called no tool, and nothing more came for 4s; a
session idle past 30m starts over. The ChatGPT backend path is followed
too. Only a turn at least Settings' TurnDoneAlert seconds long is told,
and only when the app set gateway.TurnDone: magpie serve follows nothing.
Settings: turnDoneAlert (seconds, 0 = off, the default, at most a day).
GUI: Settings › Usage "Task done alert": Off / 1 / 3 / 10 min; the
notification says "Codex is done", "Took 1m 8s · folder", in en, zh,
zh-TW, ja and de. A click on it doesn't open the Usage page.
Tests: TestTurnDoneSaidAtTheTurnsEnd (chat and anthropic through the
gateway: a tool reply, a subagent's last reply and a short turn don't
fire; a final reply fires once with session and folder),
TestTurnDoneCodexBackend, TestTurnDoneWaitsForEveryRequest,
TestTurnDoneOff, TestToolScan (every split point), TestTurnDoneText,
settings' range. Broken by hand: without the capture's scan, without the
subagent exclusion, or without the codex backend's scan, they go red.
turn-done.test.cjs: every language, 900 and 380px, chromium and webkit.
The new row moved the Usage tab's geometry: usage-alert and currency
now wheel their row clear of the header before clicking it, as a reader
would (both green 5/5 here; on base they were green as before).
Run: gofmt -l; go vet darwin, GOOS=windows ./..., GOOS=linux gateway and
settings; go test ./... (gateway alone: ok, 863s under a GUI suite's
load); the full GUI suite in both engines. codex-credits and
gateway-key-models fail now and then here on base 398f8469b too
(codex-credits filed as #1622).
Real use: a sandbox HOME, the app's dev build on 3486/3487, "1 min"
clicked in its Settings › Usage (settings.json got turnDoneAlert 60);
then the gateway in that HOME with a TurnDone that logs, and real Codex (codex exec, ChatGPT sign-in, openai_base_url at the
sandbox gateway) running `sleep 62` then answering: the turn's end came
once, agent codex (Codex), its session, folder turnproj, took 1m8s; a
short "reply hi" turn after it didn't fire. The macOS notification
itself wasn't seen: an unbundled dev binary can't post one ("require a
valid bundle identifier"); the notifier is the one usage alerts use.
Claude Code and OpenCode weren't run live; their wire formats are in
the tests.
174 lines
4.1 KiB
Go
174 lines
4.1 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/yetone/magpie/internal/redact"
|
|
"github.com/yetone/magpie/internal/usage"
|
|
)
|
|
|
|
// Recent-call bodies are diagnostics, not an unbounded traffic log. Keeping the
|
|
// first 256 KiB is enough to inspect ordinary prompts and responses while
|
|
// preventing images or long streams from multiplying into tens of MiB across
|
|
// 40 calls.
|
|
const callBodyLimit = 256 << 10
|
|
|
|
// wholeBodyLimit asks a spool for every byte it is given, for a body the OTLP
|
|
// export wants uncut (#538).
|
|
const wholeBodyLimit = -1
|
|
|
|
type capturedBody struct {
|
|
buf bytes.Buffer
|
|
truncated bool
|
|
}
|
|
|
|
func (c *capturedBody) add(p []byte) {
|
|
if c.buf.Len() >= callBodyLimit {
|
|
c.truncated = c.truncated || len(p) > 0
|
|
return
|
|
}
|
|
n := min(len(p), callBodyLimit-c.buf.Len())
|
|
_, _ = c.buf.Write(p[:n])
|
|
if n < len(p) {
|
|
c.truncated = true
|
|
}
|
|
}
|
|
|
|
func (c *capturedBody) text() string { return c.buf.String() }
|
|
|
|
func captureRequestBody(p []byte) (string, bool) {
|
|
var c capturedBody
|
|
c.add(p)
|
|
return c.text(), c.truncated
|
|
}
|
|
|
|
type captureResponseWriter struct {
|
|
http.ResponseWriter
|
|
body capturedBody
|
|
// full: the whole body, for the request archive, when it is on
|
|
full *spool
|
|
// otel: the whole body, for the OTLP export, when it asks for it uncut (#538)
|
|
otel *spool
|
|
// tools: whether the reply calls a tool, for a turn's end (turns)
|
|
tools *toolScan
|
|
}
|
|
|
|
func (w *captureResponseWriter) Write(p []byte) (int, error) {
|
|
w.body.add(p)
|
|
w.tools.add(p)
|
|
if w.full != nil {
|
|
w.full.add(p)
|
|
}
|
|
if w.otel != nil {
|
|
w.otel.add(p)
|
|
}
|
|
return w.ResponseWriter.Write(p)
|
|
}
|
|
|
|
// spool keeps a body whole for the request archive, beyond the first 256
|
|
// KiB Recent calls holds: in a temporary file, not in memory, up to limit
|
|
// bytes; past that only its size is counted. A negative limit keeps every
|
|
// byte (#538). A file that can't be written leaves what was kept so far, cut.
|
|
type spool struct {
|
|
pattern string // empty uses the request archive
|
|
|
|
f *os.File
|
|
limit, kept int64
|
|
size int64 // every byte that came, kept or not
|
|
failed bool
|
|
}
|
|
|
|
func (s *spool) add(p []byte) {
|
|
s.size += int64(len(p))
|
|
if s.failed || (s.limit >= 0 && s.kept >= s.limit) || len(p) == 0 {
|
|
return
|
|
}
|
|
if s.f == nil {
|
|
pattern := s.pattern
|
|
if pattern == "" {
|
|
pattern = "magpie-archive-*"
|
|
}
|
|
f, err := os.CreateTemp("", pattern)
|
|
if err != nil {
|
|
s.failed = true
|
|
return
|
|
}
|
|
s.f = f
|
|
}
|
|
n := int64(len(p))
|
|
if s.limit >= 0 {
|
|
n = min(n, s.limit-s.kept)
|
|
}
|
|
if _, err := s.f.Write(p[:n]); err != nil {
|
|
s.failed = true
|
|
return
|
|
}
|
|
s.kept += n
|
|
}
|
|
|
|
// cut is whether less than the whole body was kept.
|
|
func (s *spool) cut() bool { return s.kept < s.size }
|
|
|
|
// read is what was kept, the file gone after.
|
|
func (s *spool) read() ([]byte, error) {
|
|
if s.f == nil {
|
|
return nil, nil
|
|
}
|
|
defer s.discard()
|
|
if _, err := s.f.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
return io.ReadAll(io.LimitReader(s.f, s.kept))
|
|
}
|
|
|
|
// discard removes the file: nothing is kept.
|
|
func (s *spool) discard() {
|
|
if s.f != nil {
|
|
s.f.Close()
|
|
os.Remove(s.f.Name())
|
|
s.f = nil
|
|
}
|
|
}
|
|
|
|
func (w *captureResponseWriter) Flush() {
|
|
if f, ok := w.ResponseWriter.(http.Flusher); ok {
|
|
f.Flush()
|
|
}
|
|
}
|
|
|
|
// withBodies hands a call's captured request and reply to its usage
|
|
// record when the OTLP export sends them (#538) — their secrets scrubbed
|
|
// as the request archive's are, on top of the placeholders Mask secrets
|
|
// puts in — and leaves the record without them otherwise. A call captured
|
|
// whole (OTelWhole) carries them in otelIn/otelOut; otherwise the first
|
|
// 256 KiB Recent calls keeps is what goes.
|
|
func withBodies(rec *usage.Record, c *Call) {
|
|
if !usage.OTelBodies() {
|
|
return
|
|
}
|
|
in, inCut := c.RequestBody, c.RequestTruncated
|
|
if c.otelIn != nil {
|
|
in, inCut = string(c.otelIn), c.otelInCut
|
|
}
|
|
out, outCut := c.ResponseBody, c.ResponseTruncated
|
|
if c.otelOut != nil {
|
|
out, outCut = string(c.otelOut), c.otelOutCut
|
|
}
|
|
rec.BodyIn = bodyForExport(in, inCut)
|
|
rec.BodyOut = bodyForExport(out, outCut)
|
|
}
|
|
|
|
func bodyForExport(body string, cut bool) string {
|
|
if body == "" {
|
|
return ""
|
|
}
|
|
body = string(redact.ScrubJSON([]byte(body)))
|
|
if cut {
|
|
body += usage.BodyCut
|
|
}
|
|
return body
|
|
}
|