gateway: a Muse subscription draws with Muse Image on the Responses API (ljlwlcz on X)

magpie-muse-auth's accounts listed no image model, so Settings > Images and
generate_image could not use Muse. Meta's image generation page: POST
/v1/responses, model muse-image-1.0, the picture in image_generation_call.result.
The plugin signs /v1/responses only, so that is the path used; JSON and event
stream answers are both read. Video: Meta's API has no video generation.

UNTESTED against a real Muse account (none available); built from Meta's docs
and a fake plugin. Additive: a failure only affects the muse-image model.

Run at the pushed head (rebased on aebcfb93f): gofmt -l clean; GOOS=darwin and
GOOS=windows go vet ./internal/gateway clean (wsl-run); go test -run
'Draw|Muse|Image' ./internal/gateway ok, including TestMusePluginDraws (json
and stream). Broken by hand: before the draw dispatch was wired the test was red
(502 via the chat path). Not run: full suite, GUI tests, real Muse sign-in.
This commit is contained in:
yetone
2026-11-11 16:54:06 +08:00
parent aebcfb93f7
commit 52a37b75f7
3 changed files with 214 additions and 3 deletions
+24 -3
View File
@@ -224,6 +224,8 @@ func drawsFamily(p provider.Provider, id string) bool {
return strings.HasPrefix(id, grokDrawerFamily)
case drawsCodex(p):
return strings.HasPrefix(id, codexDrawerFamily)
case drawsMuse(p):
return strings.HasPrefix(id, "muse-image")
case p.Account == nil && p.Base(provider.Responses) != "" && strings.HasPrefix(id, codexDrawerFamily):
return slices.ContainsFunc(Drawers(p), func(m catalog.Model) bool {
return strings.HasPrefix(m.ID[strings.LastIndexByte(m.ID, '/')+1:], codexDrawerFamily)
@@ -277,7 +279,7 @@ func ListedDrawer(ref string) string {
// an account's own list of models (#474), picked in the editor from the
// chat models, can't name them, so it never bars one (heyiwei5 on X).
func listsCantName(p provider.Provider) bool {
return drawsCodex(p) || drawsGrok(p) || drawsWorkBuddy(p)
return drawsCodex(p) || drawsGrok(p) || drawsMuse(p) || drawsWorkBuddy(p)
}
// codexDrawer is the image model Codex CLI asks a ChatGPT account for, the
@@ -306,6 +308,19 @@ func drawsCopilot(p provider.Provider) bool {
return p.Account != nil && p.Account.Agent == "copilot"
}
// museDrawer is Meta's image model (Muse Image), which the Muse Code
// subscription's plans include and which draws on the Responses API, as
// Meta's image generation page shows: model muse-image-1.0, the picture in
// the answer's image_generation_call.
const museDrawer = "muse-image-1.0"
// drawsMuse is whether p is a Muse (Meta) subscription, a plugin's. The
// plugin signs POST /responses only, so it draws on that, not on the
// images endpoints.
func drawsMuse(p provider.Provider) bool {
return p.Account != nil && p.PluginProvider() == "muse" && p.Base(provider.Responses) != ""
}
// drawsCodex is whether p is a ChatGPT account, which draws at its Codex
// backend's images API.
func drawsCodex(p provider.Provider) bool {
@@ -327,6 +342,9 @@ func DrawersOf(p provider.Provider, avail func() []catalog.Model) []catalog.Mode
if drawsWorkBuddy(p) {
return wbDrawers(p)
}
if drawsMuse(p) {
return []catalog.Model{{ID: museDrawer, Name: "Muse Image", Provider: p.ID}}
}
if drawsCodex(p) || drawsGrok(p) {
out := slices.Clone(codexDrawers)
if drawsGrok(p) {
@@ -503,8 +521,8 @@ func AutoDrawer() string {
}
c := cand{ref: p.ID + "/" + m.ID, released: m.Released, cost: 1e9}
switch {
case drawsCodex(p), drawsGrok(p):
c.cost, c.priced = 0, true // a ChatGPT or Grok plan's images come with it
case drawsCodex(p), drawsGrok(p), drawsMuse(p):
c.cost, c.priced = 0, true // a ChatGPT, Grok or Muse plan's images come with it
case m.Price != nil:
c.cost, c.priced = m.Price.Input+m.Price.Output, true
}
@@ -1348,6 +1366,9 @@ func (s *Server) draw(ctx context.Context, p provider.Provider, model string, d
if drawsWorkBuddy(p) {
return s.drawWorkBuddy(ctx, p, model, d)
}
if drawsMuse(p) {
return s.drawMuse(ctx, p, model, d)
}
if drawsCodex(p) || drawsGrok(p) {
return s.drawImages(ctx, p, model, d)
}
+132
View File
@@ -0,0 +1,132 @@
package gateway
// A Muse (Meta) subscription draws with Muse Image on the Responses API:
// POST /responses with model muse-image-1.0 and the prompt as input, the
// picture coming back base64 in the answer's image_generation_call (Meta's
// "Image generation with Muse Image"). Reference images and an image to
// edit go in as input_image parts of the same input. The plugin signs
// POST /responses only, so the single-shot /images endpoints are not asked.
// Its fetch asks for an event stream, so the answer is read as either a
// JSON body or the stream's events.
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/yetone/magpie/internal/provider"
)
func (s *Server) drawMuse(ctx context.Context, p provider.Provider, model string, d drawing) (drawn, int, error) {
var input any = d.Prompt
if len(d.Images) > 0 {
parts := []map[string]any{{"type": "input_text", "text": d.Prompt}}
for _, pic := range d.Images {
u := pic.dataURL()
if pic.URL != "" {
u = pic.URL
}
parts = append(parts, map[string]any{"type": "input_image", "image_url": u})
}
input = []map[string]any{{"role": "user", "content": parts}}
}
body, _ := json.Marshal(map[string]any{"model": model, "input": input, "store": false})
url := strings.TrimRight(p.Base(provider.Responses), "/") + "/responses"
return s.eachDrawing(max(d.N, 1), func() (drawn, int, error) {
b, code, err := s.send(ctx, p, url, "application/json", body, true)
if err != nil {
return drawn{}, code, err
}
return readMuseAnswer(p, url, b, code)
})
}
// readMuseAnswer is the images in a Responses answer: the
// image_generation_call items' result, whether the answer is one JSON body
// or an event stream (its output_item.done and completed events).
func readMuseAnswer(p provider.Provider, url string, b []byte, code int) (drawn, int, error) {
type item struct {
Type string `json:"type"`
ID string `json:"id"`
Result string `json:"result"`
}
type response struct {
Output []item `json:"output"`
Usage struct {
Input int `json:"input_tokens"`
Output int `json:"output_tokens"`
} `json:"usage"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
var items []item
var res response
if t := bytes.TrimSpace(b); len(t) > 0 && t[0] == '{' {
if err := json.Unmarshal(t, &res); err != nil {
return drawn{}, 502, fmt.Errorf("%s's answer isn't a Responses API's: %v", p.Name, err)
}
items = res.Output
} else {
sc := bufio.NewScanner(bytes.NewReader(b))
sc.Buffer(make([]byte, 0, 1<<20), 256<<20)
for sc.Scan() {
data, ok := strings.CutPrefix(sc.Text(), "data:")
if !ok {
continue
}
var ev struct {
Type string `json:"type"`
Item item `json:"item"`
Response response `json:"response"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
if json.Unmarshal([]byte(strings.TrimSpace(data)), &ev) != nil {
continue
}
switch ev.Type {
case "response.output_item.done":
items = append(items, ev.Item)
case "response.completed":
items = append(items, ev.Response.Output...)
res.Usage = ev.Response.Usage
case "response.failed", "error":
if ev.Response.Error != nil {
res.Error = ev.Response.Error
} else if ev.Error != nil {
res.Error = ev.Error
}
}
}
}
out := drawn{Input: res.Usage.Input, Output: res.Usage.Output}
seen := map[string]bool{}
for _, it := range items {
if it.Type != "image_generation_call" || it.Result == "" || it.ID != "" && seen[it.ID] {
continue
}
seen[it.ID] = true
data, err := base64.StdEncoding.DecodeString(it.Result)
if err != nil {
return drawn{}, 502, fmt.Errorf("%s's image isn't base64: %v", p.Name, err)
}
out.Images = append(out.Images, picture{Mime: http.DetectContentType(data), Data: data})
}
if len(out.Images) == 0 {
var why string
if res.Error != nil && res.Error.Message != "" {
why = ": " + res.Error.Message
} else {
why = vendorSaid(vendorMessage(b))
}
return out, 502, fmt.Errorf("%s answered with no image%s", provider.HostOf(url), why)
}
return out, code, nil
}
+58
View File
@@ -0,0 +1,58 @@
package gateway
import (
"encoding/base64"
"io"
"net/http"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A Muse (Meta) subscription draws with Muse Image on the Responses API
// (ljlwlcz on X: "both Muse plugins don't support image generation"): the
// model muse-image-1.0, the prompt as input, the picture in the answer's
// image_generation_call, read from a JSON body and from an event stream.
func TestMusePluginDraws(t *testing.T) {
png := base64.StdEncoding.EncodeToString(pngBytes)
for name, answer := range map[string]struct{ ct, body string }{
"json": {"application/json", `{"id":"resp_1","status":"completed","output":[{"type":"reasoning","id":"rs_1","summary":[]},{"type":"message","id":"m","role":"assistant","content":[]},{"type":"image_generation_call","id":"ig_1","status":"completed","result":"` + png + `"}],"usage":{"input_tokens":7,"output_tokens":3}}`},
"stream": {"text/event-stream", "event: response.output_item.done\ndata: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"image_generation_call\",\"id\":\"ig_1\",\"result\":\"" + png + "\"}}\n\n" +
"event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"output\":[{\"type\":\"image_generation_call\",\"id\":\"ig_1\",\"result\":\"" + png + "\"}],\"usage\":{\"input_tokens\":7,\"output_tokens\":3}}}\n\n"},
} {
t.Run(name, func(t *testing.T) {
var mu sync.Mutex
var paths, bodies []string
pid := besideFake(t, "muse", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
paths, bodies = append(paths, r.URL.Path), append(bodies, string(b))
mu.Unlock()
w.Header().Set("Content-Type", answer.ct)
io.WriteString(w, answer.body)
}))
p, err := provider.Find(pid)
if err != nil {
t.Fatal(err)
}
if ds := Drawers(*p); len(ds) != 1 || ds[0].ID != "muse-image-1.0" || ds[0].Provider != pid {
t.Fatalf("drawers %v", ds)
}
code, a, raw := postImages(t, New(), "/v1/images/generations", "application/json", `{"model":"`+pid+`/muse-image-1.0","prompt":"a magpie"}`)
if code != 200 || len(a.Data) != 1 {
t.Fatalf("%d %s", code, raw)
}
// a newer Muse Image, named before magpie lists it
if code, a, raw = postImages(t, New(), "/v1/images/generations", "application/json", `{"model":"muse-image-1.1","prompt":"a magpie"}`); code != 200 || len(a.Data) != 1 {
t.Fatalf("bare name: %d %s", code, raw)
}
mu.Lock()
defer mu.Unlock()
if len(paths) != 2 || paths[0] != "/v1/responses" || !strings.Contains(bodies[0], `"model":"muse-image-1.0"`) || !strings.Contains(bodies[0], `"input":"a magpie"`) || !strings.Contains(bodies[1], `"model":"muse-image-1.1"`) {
t.Fatalf("sent %v %v", paths, bodies)
}
})
}
}