* gateway: a Chat upstream gets a mended tool exchange — Kimi turns a broken one away 400 ("tool_call_id is not found"): a turn's tool results all go ahead of its own text, in the calls' order; a result whose call is gone gets a synthetic call (unknown_tool) so it survives; an unanswered call gets a synthetic error result; a thinking-only assistant turn, which an aborted stream leaves behind, is dropped
* gateway: a translated reply whose stream the upstream cuts off mid-way goes on instead of failing — the same conversation is asked again with what the client already has of the reply sent back as its last message, for the model to go on from (vk-relay dropping Kimi K3 and DeepSeek streams mid-reply: "API Error: Server error mid-response"). The reply so far goes back with its reasoning for models that read reasoning_content back (Kimi, DeepSeek), a full echo of it is dropped, and the continuation's fresh thinking isn't shown again; the client waits with keepalives between tries, up to two. A reply a tool call of has begun can't be prefilled, and a refusal isn't asked again: both end with the error in the stream, as they used to. A stream's own error event mid-reply ends its read at once rather than waiting on a vendor that keeps the connection open. TestStreamCutMidReplyContinues (reply goes on, one message), TestStreamCutContinuationEchoDropped, TestStreamCutAfterToolCallEndsAsBefore, TestStreamCutContinuesOnlySoLong, TestStreamCutMidThinkingContinues(WithoutReasoning), TestStreamErrorMidReplyContinuesAtOnce and TestContinuationUnecho cover it; TestStreamErrorKeptOpenFailsOverAtOnce and the severed-stream tests pass unchanged. go vet ./internal/gateway, go build (darwin, GOOS=linux, GOOS=windows), go test of gateway, provider, catalog and imagemcp pass.
* gateway: a Chat upstream's mended tool exchange — an orphaned or late result reaches the model as a user message, the Responses path's policy, so no call is made up and no id is used twice; an empty assistant is dropped only inside a pending exchange, where it would break adjacency, and passes through outside one; a second answer to a call is dropped, the first stands; the session replay harness gives way to fixed fixtures
* gateway: a cut reply is asked to go on only where the upstream goes on from a prefill — a trailing assistant message isn't one on most Chat APIs: the model answers it again from the start, reworded, and the client, an exact echo alone dropped, kept its part and the re-answer spliced as one reply with no error to tell (api.deepseek.com did so 5 times in 6). It goes on only where the prefill is real: an Anthropic Messages upstream natively (a model that turns one away answers 400 and the reply ends as it used to; the newest Claude among them), a Chat one in its vendor's own mode — DeepSeek's prefix, asked of its /beta endpoint with "prefix": true on the message, Kimi's "partial": true — a relay on this machine or the LAN serving one of their models taken to front the vendor, as geminiCompat takes one to front Gemini; everywhere else the reply ends with the error, as it used to, for the agent to try the turn again. reasoning_content goes back with the prefill by the same decision (reasoningBack named any kimi model on any host); the prefill's trailing whitespace, which Anthropic turns the request away for, is trimmed, the client having it already; and the tries' usages are summed into the reply's, the client's and the ledger's, where only the last try's was kept while the vendor billed each (a cut try's is only what it said before the cut). New tests: a re-answering upstream is never asked to go on (the client reads the error, not the garble), DeepSeek's /beta prefix mode and Kimi's partial on the wire, an Anthropic upstream's native prefill (text, thinking-only, whitespace trimmed, a refused prefill ending as it used to), the tries' usages summed, chatPrefill and prefillHow themselves. go vet, builds (darwin, nogui) and go test -count=1 -race ./internal/gateway pass (2146; gui's TestSetPortMovesTheGateway fails on main too).
* tests: three environment- and drift-broken suites pass again — port: a moved gateway finishes the connections it has (Relisten's handover), so answers() pooled a keep-alive one from its start-up polls and the old port answered from it forever; it now dials with keep-alive off, asking what the test means to: does the old port take NEW connections. plugin: TestBunIsGivenTheSystemsRoots read the shell's ambient NODE_EXTRA_CA_CERTS as the user's own (it wins by design); the test sets its own. accounts: forgetting the account in use puts the one left first since 30d952cf, which updated the provider and GUI tests but not accounts_plugin_cli_test.go; it now expects that. All three failed on upstream/main on a machine with a proxy CA configured; the full nogui suite passes.
174 lines
5.6 KiB
Go
174 lines
5.6 KiB
Go
package gui
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/gateway"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// freePort is a port nothing listens on now.
|
|
func freePort(t *testing.T) int {
|
|
t.Helper()
|
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer ln.Close()
|
|
return ln.Addr().(*net.TCPAddr).Port
|
|
}
|
|
|
|
// answers says whether a magpie gateway answers on port p. Keep-alive is
|
|
// off: a moved gateway finishes the connections it has (Relisten), so a
|
|
// pooled one from the polls above would answer from the old port forever
|
|
// and say nothing about new connections to it.
|
|
func answers(p int) bool {
|
|
c := &http.Client{Timeout: time.Second, Transport: &http.Transport{DisableKeepAlives: true}}
|
|
res, err := c.Get(fmt.Sprintf("http://127.0.0.1:%d/", p))
|
|
if err != nil {
|
|
return false
|
|
}
|
|
res.Body.Close()
|
|
return res.StatusCode == http.StatusOK
|
|
}
|
|
|
|
// Settings' gateway port (Magic_zero on Discord) moves the gateway this
|
|
// magpie serves: it answers on the new port and no longer on the old one,
|
|
// and magpie's URL, the CLI's and the agents', follows. A port another
|
|
// program has is refused with its reason, the gateway left where it was;
|
|
// one out of range or under MAGPIE_ADDR is refused too.
|
|
func TestSetPortMovesTheGateway(t *testing.T) {
|
|
sandboxHome(t)
|
|
t.Setenv("MAGPIE_ADDR", "")
|
|
from := freePort(t)
|
|
s := settings.Load()
|
|
s.Port = from
|
|
if err := settings.Save(s); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if gateway.URL() != fmt.Sprintf("http://127.0.0.1:%d", from) {
|
|
t.Fatalf("Settings' port isn't the gateway's: %s", gateway.URL())
|
|
}
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
gw := gateway.New()
|
|
done := make(chan struct{})
|
|
go func() { defer close(done); gw.ListenAndServe(ctx) }()
|
|
served.Store(gw)
|
|
t.Cleanup(func() { served.Store(nil); cancel(); <-done })
|
|
for deadline := time.Now().Add(5 * time.Second); !answers(from); time.Sleep(20 * time.Millisecond) {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("the gateway didn't start")
|
|
}
|
|
}
|
|
|
|
handler := Handler(nil, nil)
|
|
post := func(body string) (int, map[string]any) {
|
|
w := httptest.NewRecorder()
|
|
handler.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/settings/port", strings.NewReader(body)))
|
|
var out map[string]any
|
|
json.Unmarshal(w.Body.Bytes(), &out)
|
|
return w.Code, out
|
|
}
|
|
|
|
// a port another program listens on
|
|
taken, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer taken.Close()
|
|
tp := taken.Addr().(*net.TCPAddr).Port
|
|
code, out := post(fmt.Sprintf(`{"port":%d}`, tp))
|
|
if code != http.StatusBadRequest || !strings.Contains(fmt.Sprint(out["error"]), "in use") {
|
|
t.Fatalf("a taken port: %d %v", code, out)
|
|
}
|
|
if settings.Load().Port != from || !answers(from) {
|
|
t.Fatal("a taken port moved the gateway")
|
|
}
|
|
for _, bad := range []int{80, 70000} {
|
|
if code, out := post(fmt.Sprintf(`{"port":%d}`, bad)); code != http.StatusBadRequest || !strings.Contains(fmt.Sprint(out["error"]), "1024 to 65535") {
|
|
t.Fatalf("port %d: %d %v", bad, code, out)
|
|
}
|
|
}
|
|
|
|
to := freePort(t)
|
|
code, out = post(fmt.Sprintf(`{"port":%d}`, to))
|
|
if code != http.StatusOK {
|
|
t.Fatalf("moving: %d %v", code, out)
|
|
}
|
|
if p, _ := out["port"].(map[string]any); p == nil || p["port"] != float64(to) {
|
|
t.Fatalf("the answer: %v", out)
|
|
}
|
|
if st, _ := out["settings"].(map[string]any); st["gateway"] != fmt.Sprintf("http://127.0.0.1:%d", to) || st["port"] != float64(to) {
|
|
t.Fatalf("Settings say: %v", st)
|
|
}
|
|
if !answers(to) {
|
|
t.Fatal("the gateway doesn't answer on the new port")
|
|
}
|
|
if answers(from) {
|
|
t.Fatal("the gateway still answers on the old port")
|
|
}
|
|
if !gateway.Running() {
|
|
t.Fatal("magpie doesn't find its own gateway on the new port")
|
|
}
|
|
|
|
// the Settings page's other choices, saved, leave the port as it is
|
|
w := httptest.NewRecorder()
|
|
handler.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/settings", strings.NewReader(`{"theme":"dark"}`)))
|
|
if w.Code != http.StatusOK || settings.Load().Port != to {
|
|
t.Fatalf("saving Settings took the port: %d %s, port %d", w.Code, w.Body, settings.Load().Port)
|
|
}
|
|
|
|
// MAGPIE_ADDR comes first: the port is set there, not here
|
|
t.Setenv("MAGPIE_ADDR", "127.0.0.1:3426")
|
|
if code, out := post(fmt.Sprintf(`{"port":%d}`, freePort(t))); code != http.StatusBadRequest || !strings.Contains(fmt.Sprint(out["error"]), "MAGPIE_ADDR") {
|
|
t.Fatalf("under MAGPIE_ADDR: %d %v", code, out)
|
|
}
|
|
w = httptest.NewRecorder()
|
|
handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/settings", nil))
|
|
if !strings.Contains(w.Body.String(), `"addrEnv":"127.0.0.1:3426"`) {
|
|
t.Fatalf("Settings don't say MAGPIE_ADDR: %s", w.Body)
|
|
}
|
|
}
|
|
|
|
// The port magpie was on taken by another program (Magic_zero's 3425), it
|
|
// serves nothing: setting another port starts the gateway there.
|
|
func TestSetPortServesWhenTheOldOneWasTaken(t *testing.T) {
|
|
sandboxHome(t)
|
|
t.Setenv("MAGPIE_ADDR", "")
|
|
other, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer other.Close()
|
|
srv := &http.Server{Handler: http.NotFoundHandler()}
|
|
go srv.Serve(other)
|
|
defer srv.Close()
|
|
s := settings.Load()
|
|
s.Port = other.Addr().(*net.TCPAddr).Port
|
|
if err := settings.Save(s); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
served.Store(nil)
|
|
t.Cleanup(func() { served.Store(nil) })
|
|
if gateway.Running() {
|
|
t.Fatal("another program taken for magpie")
|
|
}
|
|
to := freePort(t)
|
|
if _, err := setPort(to); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for deadline := time.Now().Add(5 * time.Second); !answers(to); time.Sleep(20 * time.Millisecond) {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("the gateway didn't start on the new port")
|
|
}
|
|
}
|
|
}
|