Files
magpie/internal/gateway/search_workbuddy.go
T
yetone e5dd86965b pii: the masking model's requests take turns without holding the status, Stop or a restart (#3682)
After a restart, with Settings → Privacy's local model on, every request
queued for minutes on srv.mu in classify. That lock was held across
start() (up to 3m loading) and the model's answer (30s and more), and
Now(), Stop() and the idle timer took it too. The user saw a 504
"held this request for 2m0s without routing it to any provider".

Now:
- pf-serve's requests take turns through a one-slot channel (`turn`),
  so writes on its one pipe never interleave. srv.mu only guards state.
  Now() never waits: it reports Loading and how many are Waiting. Stop()
  never waits either: it kills a pf-serve that is loading or answering,
  and the request on it fails with errStopped (no retry). Fetch's
  upgrade stops pf-serve only once its turn is free (stopWhenFree).
- A request waits for its turn under its own context (FindContext). The
  gateway passes the request's context through a new gwmw.ContextTeller,
  so a client that went away, or a request the gateway answered 504,
  leaves the queue. A turn already begun still finishes and caches.
- What Find learned is kept on disk (found-<model sha>.bin, beside the
  model): a text's sha256 and its spans' offsets and labels, never the
  text. Written via temp-and-rename. A bad, cut-short or over-long file
  is read as empty, and a cached span that doesn't fit its text is
  asked again. A restart no longer asks about every history again.
- A request waiting for its turn reads the cache again when it gets it,
  so requests queued with the same history ask the model once.
- The guarantee stays: a request the model can't mask is held back, never
  sent masked by the rules alone. A wait that ends panics inside
  gwmw.Safely, as a failed model did, and the request fails closed.
- The 504 for a request held while masking says it waited for the local
  masking model, what the model was doing (loading, or masking another
  request with N waiting), that what it read is kept, and that the model
  can be turned off in Settings → Privacy (unroutedMsg).

Tests (each red on the fix broken by hand, in the sandbox HOME):
- TestStatusAndStopDontWaitForARequest / ...ForALoad: red with Now()
  taking the turn (Now waited), and the suite hung with Stop() taking it.
- TestWaiterLeavesWhenItsContextEnds: red with the waiter ignoring ctx.
- TestQueuedRequestReadsWhatTheOneAheadLearned: red without the re-read.
- TestRestartReadsWhatWasFound: red with loadCache a no-op. It also
  checks the file never holds the text.
- TestBadCacheFileIsReadAsEmpty: red with a cut-short file's entries kept.
- TestCachedSpanOutsideItsTextIsAskedAgain: red without the fits check.
- gateway TestHeldForTheMaskingModelSaysSo: red with the masker handed
  context.Background() (the wait never let go), without noteMasking, and
  with the old message. TestUnroutedMsgNamesTheModelOnlyWhenItIsOn: red
  with the old message.
- TestMaskingOnAndOff's panicky fixture embeds masking.Masker, which now
  has the Context methods. It panics on those too, and still refuses.

Run at this head (base origin/main 098ac9696, fetched before the commit),
in a sandbox HOME, load ~25:
- go test -timeout 45m -count=1 on internal/pii, internal/redact,
  internal/gwmw, internal/gateway, internal/gui and plugins/redact/...:
  all ok, apart from TestMaskingOnAndOff (the fixture above). After its
  fix, internal/gateway and internal/pii were run again whole: ok.
  internal/masking has no tests.
- go test -race -count=1 ./internal/pii/: ok.
- gofmt -l clean; go vet ./... (darwin); GOOS=linux and GOOS=windows
  go vet -tags nogui on the changed packages and internal/gui, and
  go build -tags nogui ./...: ok.

Not tried:
- A real pf-serve and model: everything above ran against the test's
  stand-in pf-serve. A real cold restart with the model on was not timed,
  and neither was Windows CPU.
- pf-serve is not warmed when magpie starts, so the first request after
  an update to the model still waits for its load. That wait now says so
  and can be left.
- The GUI does not show Loading/Waiting yet; GET /api/privacy-model carries
  them (status.loading, status.waiting).
2026-10-26 14:15:53 +08:00

134 lines
4.5 KiB
Go

package gateway
import (
"bytes"
"cmp"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// A WorkBuddy plan, the China build's or WorkBuddy AI's, searches the web
// with its own search service, as WorkBuddy's own client does (its CLI's
// WebSearch tool, app.asar.unpacked/cli/dist/codebuddy.js: WEB_SEARCH_API_PATH):
// a POST to <site>/agenttool/v1/search of
//
// {"query":"…","type":"text2text","max_results":5}
//
// signed as the plan's chats are, answered with
//
// {"query","type","provider","results":[{"title","url","snippet","site","favicon"}],"total_results","response_time_ms"}
//
// or a refusal as {"code","msg"} (15001 is its search quota spent). Its
// models have no search tool of their own, so before, a Claude Code turn
// on WorkBuddy with nothing else in magpie that searches had the server
// tool taken away and WebSearch came back empty (#1798). As with a Kimi
// Code plan, a WorkBuddy model's searches are done here first, and only
// for its own models. It is the same for the built-in and for a WorkBuddy
// moved onto its plugin: magpie shapes the request, Sign and Do send it
// (the plugin's fetch signs it there).
// wbSearchPath is where a WorkBuddy site's search service is, and
// wbSearchResults how many results its client asks for.
const (
wbSearchPath = "/agenttool/v1/search"
wbSearchResults = 5
)
// wbSearches is whether p is a WorkBuddy plan that searches for its models.
func wbSearches(p provider.Provider) bool { return drawsWorkBuddy(p) }
// wbSearch asks p's WorkBuddy site to search the web.
func (s *Server) wbSearch(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) {
origin := p.Origin(ctx)
if origin == "" {
return "", nil, fmt.Errorf("%s: no site to search with", p.Name)
}
// its client gives the service 20 s
ctx, cancel := context.WithTimeout(s.metered(p.Via(ctx), p, ""), searchTimeout/2)
defer cancel()
q, err := maskedQuery(ctx, query, &p)
if err != nil {
return "", nil, err
}
body, _ := json.Marshal(map[string]any{"query": q, "type": "text2text", "max_results": wbSearchResults})
r, err := http.NewRequestWithContext(ctx, http.MethodPost, origin+wbSearchPath, bytes.NewReader(body))
if err != nil {
return "", nil, err
}
if err := p.Sign(ctx, r, provider.Chat, body); err != nil {
return "", nil, fmt.Errorf("%s: %w", p.Name, err)
}
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Accept", "application/json")
r.Header.Set("X-Requested-With", "XMLHttpRequest")
if r.Header.Get("X-Request-ID") == "" {
id := wbSearchID()
r.Header.Set("X-Request-ID", id)
r.Header.Set("X-Conversation-Message-ID", id)
}
res, err := p.Do(s.client, r) // a moved one's through its plugin
if err != nil {
if ctx.Err() != nil {
return "", nil, fmt.Errorf("%s: no answer in time", p.Name)
}
return "", nil, fmt.Errorf("%s: %w", p.Name, err)
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20))
if res.StatusCode >= 300 {
return "", nil, errors.New(p.Name + "'s search: " + provider.APIError(b, res.Status))
}
var out struct {
Code json.RawMessage `json:"code"`
Msg string `json:"msg"`
Results *[]struct {
Title string `json:"title"`
URL string `json:"url"`
Snippet string `json:"snippet"`
Site string `json:"site"`
} `json:"results"`
}
if err := json.Unmarshal(b, &out); err != nil {
return "", nil, fmt.Errorf("%s's search: unexpected reply: %s", p.Name, provider.APIError(b, res.Status))
}
if c := strings.Trim(string(out.Code), `"`); c != "" && c != "0" && c != "null" {
return "", nil, fmt.Errorf("%s's search: %s (%s)", p.Name, cmp.Or(out.Msg, "refused"), c)
}
if out.Results == nil {
return "", nil, fmt.Errorf("%s's search: unexpected reply: %s", p.Name, provider.APIError(b, res.Status))
}
var pages []foundPage
for _, x := range *out.Results {
if x.URL == "" {
continue
}
title := cmp.Or(searchPlain(x.Title), searchPlain(x.Site), x.URL)
pages = append(pages, foundPage{Title: title, URL: x.URL, Text: clipText(searchPlain(x.Snippet), pageText)})
if len(pages) == searchHits {
break
}
}
if len(pages) == 0 {
return "", nil, fmt.Errorf("%s found nothing", p.Name)
}
said, hits := pagesSaid(pages)
return said, hits, nil
}
// wbSearchID is a request id as WorkBuddy's client makes them: a UUID's
// hex without its dashes.
func wbSearchID() string {
var b [16]byte
rand.Read(b[:])
return hex.EncodeToString(b[:])
}