Restore what 85e6ec540 reverted: it was committed on a stale index and took out b587eb306's and earlier work (webview2, library skills, opencode endpoints, quotas); this puts the tree at b587eb306 plus the Paseo agent only

This commit is contained in:
yetone
2026-11-11 23:09:15 +08:00
parent 85e6ec5406
commit b52c711142
27 changed files with 883 additions and 49 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+72 -5
View File
@@ -1100,7 +1100,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
log.Printf("claude: a branch of a claude -p run's session goes to a new interactive Claude Code, told the whole conversation")
from, req.branch = nil, nil
}
if from != nil && from.cut != "" {
if from != nil && (from.cut != "" || len(from.cutCalls) > 0) {
// a branch is a copy of the run's session as far as the reply
// that made the calls, a session of its own: Claude Code's
// interactive mode doesn't take --resume-session-at, and resumes
@@ -1111,14 +1111,20 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
if from.cutBefore {
cutter, how = cutSessionBefore, "a side request that sends the conversation whole, without the calls its run still waits on, goes on in a branch of that run's session, cut before them"
}
sid, err := cutter(from.sessions, from.session, from.cut)
var sid string
var err error
if from.cut == "" {
sid, err = cutSessionBeforeCalls(from.sessions, from.session, from.cutCalls)
} else {
sid, err = cutter(from.sessions, from.session, from.cut)
}
if err != nil {
log.Printf("claude: a branch of a run's session couldn't be cut (%v); a new Claude Code is told the whole conversation", err)
from, req.branch = nil, nil
} else {
log.Printf("claude: %s (%d messages)", how, len(from.since))
from.mu.Lock()
from.session, from.cut, from.cutBefore, from.gone = sid, "", false, false
from.session, from.cut, from.cutCalls, from.cutBefore, from.gone = sid, "", nil, false, false
from.mu.Unlock()
}
}
@@ -2530,6 +2536,9 @@ type savedSession struct {
// cutBefore: cut before that line, not after it: the reply's words
// stay and its calls go (a side request that dropped them, #6128)
cutBefore bool
// cutCalls: the cut is before the line of these tool calls, found by
// their ids, when the line's uuid isn't known yet (#6128).
cutCalls []string
// tui: the session was made by Claude Code's interactive mode; a
// branch of it is too, where it can be (claudePrint)
tui bool
@@ -2774,10 +2783,27 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession,
}
run.mu.Lock()
at, seq, said := "", 0, ""
var unread []string // pending calls whose line isn't read yet
if pending {
for id, l := range run.lines {
switch {
case l.told != told:
case l.uuid == "":
unread = append(unread, id)
if seq == 0 || l.seq < seq {
seq, said = l.seq, l.told
}
}
}
// A reply is parked on once its calls were streamed; its
// session line may not be read yet, nor on disk (#6128): the
// calls are found in the session by their ids, and a line
// already read is a surer place.
slices.Sort(unread)
for _, l := range run.lines {
if l.uuid != "" && l.told == told && (at == "" || l.seq < seq) {
at, seq, said = l.uuid, l.seq, l.told
unread = nil
}
}
} else {
@@ -2790,7 +2816,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession,
sid, sessions, prefix := run.sessionID, slices.Clone(run.sessions), run.cachePrefix
usable := !run.closed && !run.rewound && run.lean == req.leanPrompt && !run.clientMarks && (run.tui || !wantTUI(req))
run.mu.Unlock()
if at == "" {
if at == "" && len(unread) == 0 {
continue
}
switch {
@@ -2804,7 +2830,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession,
if pending && found != nil && seq <= foundSeq {
continue
}
found, foundSeq = &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, cutBefore: pending, tui: run.tui, appended: run.appended, cachePrefix: prefix, gone: true}, seq
found, foundSeq = &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, cutCalls: unread, cutBefore: pending, tui: run.tui, appended: run.appended, cachePrefix: prefix, gone: true}, seq
}
if !pending {
break
@@ -3007,6 +3033,47 @@ func cutSessionBefore(dirs []string, sid, uuid string) (string, error) {
return cutSessionAt(dirs, sid, uuid, cutBefore)
}
// cutSessionBeforeCalls is cutSession as far as the line before the first
// assistant line that calls one of ids, the calls a run's reply made that
// its line uuid isn't known for (#6128). Claude Code writes that line late,
// after its tool ran: asked again until cutWait is over, then, with the
// line not there, the session as it stands is what came before the calls.
func cutSessionBeforeCalls(dirs []string, sid string, ids []string) (string, error) {
if len(ids) == 0 {
return "", errors.New("no session to cut")
}
return cutSessionWhere(dirs, sid, "calls "+strings.Join(ids, ","), func(b []byte, last bool) int {
if end := cutBeforeCalls(b, ids); end >= 0 {
return end
}
if last {
return len(b)
}
return -1
})
}
// cutBeforeCalls is where in a session's lines b the first whole assistant
// line calling one of ids begins, -1 when none is there; a line with no
// newline yet is not whole.
func cutBeforeCalls(b []byte, ids []string) int {
for at := 0; at < len(b); {
nl := bytes.IndexByte(b[at:], '\n')
if nl < 0 {
break
}
line := b[at : at+nl]
start := at
at += nl + 1
for _, id := range ids {
if bytes.Contains(line, []byte(`"id":"`+id+`"`)) {
return start
}
}
}
return -1
}
// cutSessionWhere copies session sid as far as the place at finds in its
// lines (> 0), asked again until cutWait is over; last is the final ask.
// what is what it looks for, as an error says.
@@ -5,6 +5,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
)
// recih on X (#6128): Claude Code's AgentSummary sends the sub-agent's
@@ -70,3 +71,60 @@ func TestClaudeBranchForSummaryWithoutThePendingCall(t *testing.T) {
t.Fatalf("closed run: %v %q", got, why)
}
}
// #6128 (recih, v0.1.3757): the run parks on a call it streamed before the
// call's session line is read or written (Claude Code writes it after the
// tool ran), so the line has no uuid. The summary is found by the history
// the call answered, and the branch is cut before the call by its id,
// whether the line is on disk by then or not.
func TestClaudeBranchForSummaryBeforeTheCallLineIsRead(t *testing.T) {
was := cutWait
cutWait = 300 * time.Millisecond
t.Cleanup(func() { cutWait = was })
dir := t.TempDir()
const sid = "lead-session"
path := filepath.Join(dir, sid+".jsonl")
head := `{"uuid":"u1","sessionId":"` + sid + `","type":"user"}` + "\n" + `{"uuid":"a-words","sessionId":"` + sid + `","type":"assistant"}` + "\n"
if err := os.WriteFile(path, []byte(head), 0o600); err != nil {
t.Fatal(err)
}
user := func(s string) Message { return Message{Role: "user", Parts: []Part{{Kind: Text, Text: s}}} }
words := Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: "I will run the tests."}}}
history := []Message{user("task")}
b := newSubscriptionBridge()
run := &subscriptionRun{sessionID: sid, sessions: []string{dir}, tui: true}
own := "claude\x00u"
run.owner.Store(&own)
run.lines = map[string]callLine{"toolu_1": {seq: 1, told: historyKey(history)}} // parked, no uuid yet
b.runs["r"] = run
req := &Request{Messages: append(append(append([]Message{}, history...), words), user("Describe your progress in 3-5 words."))}
got, why := b.branch(req, own)
if got == nil {
t.Fatalf("no branch while the call's line is unread: %s", why)
}
if !got.cutBefore || len(got.cutCalls) != 1 || got.cutCalls[0] != "toolu_1" {
t.Fatalf("branch = %+v, want cut before the call toolu_1", got)
}
// the line is written while the cut waits for it: the cut is before it
go func() {
time.Sleep(60 * time.Millisecond)
f, _ := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600)
defer f.Close()
f.WriteString(`{"uuid":"a-call","sessionId":"` + sid + `","type":"assistant","message":{"content":[{"type":"tool_use","id":"toolu_1"}]}}` + "\n")
}()
id, err := cutSessionBeforeCalls(got.sessions, got.session, got.cutCalls)
if err != nil {
t.Fatal(err)
}
if s, _ := os.ReadFile(filepath.Join(dir, id+".jsonl")); !strings.Contains(string(s), "a-words") || strings.Contains(string(s), "a-call") {
t.Fatalf("branch keeps %q, want the words and not the call", s)
}
// the line never comes: what is on disk is what came before the call
id, err = cutSessionBeforeCalls(got.sessions, got.session, []string{"toolu_9"})
if err != nil {
t.Fatal(err)
}
if s, _ := os.ReadFile(filepath.Join(dir, id+".jsonl")); !strings.Contains(string(s), "a-words") {
t.Fatalf("branch keeps %q, want the words", s)
}
}
+2 -2
View File
@@ -63,7 +63,7 @@ func openCodeGeminiServer(t *testing.T, s *Server) func() []openCodeAsk {
switch {
case r.Method != http.MethodPost:
return reply(404, "application/json", `{}`)
case gemini && (strings.HasPrefix(path, "/zen/v1/models/") || strings.HasPrefix(path, "/inference/go/v1/models/")):
case gemini && (strings.HasPrefix(path, "/zen/v1/models/") || strings.HasPrefix(path, "/inference/go/google/v1beta/models/")):
return reply(200, "text/event-stream", openCodeGeminiSSE)
case strings.Contains(path, ":") || strings.Contains(path, "/models/"):
return reply(404, "text/html", `<html>Not Found</html>`)
@@ -113,7 +113,7 @@ func TestOpenCodeGoGeminiModelOnGeminiAPI(t *testing.T) {
}
s := New()
took := openCodeGeminiServer(t, s)
const want = "opencode.ai/inference/go/v1/models/gemini-4-argon-contributor:streamGenerateContent?alt=sse"
const want = "opencode.ai/inference/go/google/v1beta/models/gemini-4-argon-contributor:streamGenerateContent?alt=sse"
check := func(what string, code int, body string) openCodeAsk {
t.Helper()
asked := took()
+6 -6
View File
@@ -36,7 +36,7 @@ func goFreeServer(t *testing.T, models, serves []string, zenStatus int, zenRefus
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "go", Name: "OpenCode Go", Preset: "opencode-go", Key: "sk-go-users-own",
Chat: "https://opencode.ai/zen/go/v1", Responses: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go",
Chat: provider.OpenCodeGoChat, Responses: provider.OpenCodeGoChat, Anthropic: provider.OpenCodeGoAnthropic,
Models: models}); err != nil {
t.Fatal(err)
}
@@ -55,7 +55,7 @@ func goFreeServer(t *testing.T, models, serves []string, zenStatus int, zenRefus
model = m
}
}
if strings.HasPrefix(r.URL.Path, "/zen/go/") {
if strings.HasPrefix(r.URL.Path, "/inference/go/") {
for _, m := range serves {
if m == model {
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/event-stream"}},
@@ -96,8 +96,8 @@ func TestOpenCodeGoFreeModelAskedAtZen(t *testing.T) {
}
a := asked()
// on the API Go was asked on, at Zen's free tier
want := map[string]string{"opencode.ai/zen/go/v1/messages": "opencode.ai/inference/anthropic/v1/messages",
"opencode.ai/zen/go/v1/chat/completions": "opencode.ai/inference/openai/v1/chat/completions"}
want := map[string]string{"opencode.ai/inference/go/anthropic/v1/messages": "opencode.ai/inference/anthropic/v1/messages",
"opencode.ai/inference/go/openai/v1/chat/completions": "opencode.ai/inference/openai/v1/chat/completions"}
if len(a) != 2 || want[a[0].url] == "" || a[1].url != want[a[0].url] {
t.Fatalf("asked %+v", a)
}
@@ -114,7 +114,7 @@ func TestOpenCodeGoOwnFreeModelStaysOnGo(t *testing.T) {
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from go") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if a := asked(); len(a) != 1 || !strings.HasPrefix(a[0].url, "opencode.ai/zen/go/") {
if a := asked(); len(a) != 1 || !strings.HasPrefix(a[0].url, "opencode.ai/inference/go/") {
t.Fatalf("asked %+v", a)
}
}
@@ -137,7 +137,7 @@ func TestOpenCodeGoUnavailableSaysWhere(t *testing.T) {
t.Fatalf("%d %s", rec.Code, body)
}
for _, a := range asked()[n:] {
if !strings.HasPrefix(a.url, "opencode.ai/zen/go/") {
if !strings.HasPrefix(a.url, "opencode.ai/inference/go/") {
t.Fatalf("a paid model asked at %s", a.url)
}
}
+2 -1
View File
@@ -422,6 +422,7 @@ func Run(version string, showMain bool, link string) error {
// a quiet start joins the Dock once started (below): Wails activates
// an app that starts in it
policy := dockPolicy(settings.Load().Dock && !quiet)
webView2Prepare()
h.app = application.New(application.Options{
// Windows and Linux start a new process for a magpie:// link (or a
// second launch); it hands its arguments to the running one and quits.
@@ -472,7 +473,7 @@ func Run(version string, showMain bool, link string) error {
updates.install(false)
},
// Wails exits on some webview errors; say why before it does.
ErrorHandler: func(err error) { log.Println("magpie:", err) },
ErrorHandler: func(err error) { webView2Failed(h.app, err) },
})
// Windows without the WebView2 runtime can make no window: Wails would
// exit on the first, with nothing on screen to say why (#1806). The
+50 -1
View File
@@ -6680,6 +6680,53 @@ magpie.plugin("library", (ctx) => {
};
}
// A skill of the user's own: a name and a description make its SKILL.md
// in the library's folder (josephBenchap on X); it opens in the reader,
// whose path opens it in their editor.
function newSkill() {
const all = skillAgents();
const d = { name: "", description: "", agents: all.map((a) => a.id) };
const ed = el("div", "editor lib-editor lib-newskill");
const head = el("div", "ehead");
head.append(glyph(GLYPH.skill), el("b", "", t("New skill")));
ed.append(head);
const err = el("div", "editor-error");
const name = field2("", t("e.g. my-skill"), (v) => { d.name = v.trim(); });
name.classList.add("mono");
ed.append(...field(t("Name"), name, t("Letters, digits, - and _ — what the agents call it")));
const desc = el("textarea", "lib-text small lib-newskilldesc");
desc.placeholder = t("e.g. Writes release notes. Use when asked for a changelog.");
desc.spellcheck = false;
desc.rows = 2;
desc.maxLength = 1024;
desc.oninput = () => { d.description = desc.value; };
desc.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (e.key === "Enter") { e.preventDefault(); modal?.save?.(); } };
ed.append(...field(t("Description"), desc, t("What it does and when to use it: the agent reads this to decide when to load it")));
const agentsBox = el("div");
ed.append(...field(t("Agents"), agentsBox));
ed.append(err);
const drawAgents = () => agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, all: true }));
drawAgents();
const bar = el("div", "bar");
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal));
const save = async () => {
err.textContent = "";
try {
take(await api("library/skills/create", { name: d.name, description: d.description, agents: d.agents }));
report(lib.result, t("{name} is in the library now", { name: d.name }));
render();
const made = lib.skills.find((x) => x.name === d.name);
if (made) viewSkill(made); else closeLibModal(true);
} catch (e) { err.textContent = e.message; }
};
bar.append(button(t("Create"), "primary", save));
ed.append(bar);
const original = JSON.stringify(d);
modal = { save, dirty: () => JSON.stringify(d) !== original };
openLib(ed);
requestAnimationFrame(() => name.focus());
}
function installCard() {
const card = el("div", "list lib-card lib-install");
const line = el("div", "lib-find");
@@ -6695,7 +6742,9 @@ magpie.plugin("library", (ctx) => {
if (probing) go.classList.add("busy");
inp.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") find(); else if (e.key === "Escape" && probe) { probe = null; render(); } };
const g = glyph(GLYPH.search, "lib-mini");
line.append(g, inp, go);
const mk = button(t("New skill"), "", () => newSkill());
mk.dataset.lib = "new-skill";
line.append(g, inp, go, mk);
card.append(line);
async function find() {
const src = inp.value.trim();
@@ -2,6 +2,10 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"New skill": "新建技能",
"e.g. my-skill": "例如 my-skill",
"e.g. Writes release notes. Use when asked for a changelog.": "例如:撰写发布说明。需要更新日志时使用。",
"What it does and when to use it: the agent reads this to decide when to load it": "它做什么、何时使用:Agent 据此决定何时加载它",
"This computer follows the server: what you change here is replaced by the next sync.": "这台电脑跟随服务器:你在这里的改动会被下一次同步替换。",
"Sync settings": "同步设置",
"Stop picking memories": "不再选择记忆",
@@ -975,6 +979,10 @@ magpie.strings({
"{name} read again from its source": "已重新从来源读取 {name}",
},
"zh-TW": {
"New skill": "新增技能",
"e.g. my-skill": "例如 my-skill",
"e.g. Writes release notes. Use when asked for a changelog.": "例如:撰寫發佈說明。需要更新日誌時使用。",
"What it does and when to use it: the agent reads this to decide when to load it": "它做什麼、何時使用:Agent 據此決定何時載入它",
"This computer follows the server: what you change here is replaced by the next sync.": "這台電腦跟隨伺服器:你在這裡的變更會被下一次同步取代。",
"Sync settings": "同步設定",
"Stop picking memories": "不再選擇記憶",
@@ -1948,6 +1956,10 @@ magpie.strings({
"{name} read again from its source": "已重新從來源讀取 {name}",
},
ja: {
"New skill": "新しいスキル",
"e.g. my-skill": "例: my-skill",
"e.g. Writes release notes. Use when asked for a changelog.": "例: リリースノートを書く。変更履歴を求められたときに使う。",
"What it does and when to use it: the agent reads this to decide when to load it": "何をするか、いつ使うか。エージェントはこれを読んで読み込むかを決めます",
"This computer follows the server: what you change here is replaced by the next sync.": "このコンピュータはサーバーに従います。ここでの変更は次の同期で置き換えられます。",
"Sync settings": "同期の設定",
"Stop picking memories": "メモリの選択を終える",
@@ -2921,6 +2933,10 @@ magpie.strings({
"{name} read again from its source": "{name} をソースから読み直しました",
},
de: {
"New skill": "Neuer Skill",
"e.g. my-skill": "z. B. my-skill",
"e.g. Writes release notes. Use when asked for a changelog.": "z. B. Schreibt Release Notes. Zu verwenden, wenn ein Changelog verlangt wird.",
"What it does and when to use it: the agent reads this to decide when to load it": "Was er tut und wann er gebraucht wird: Der Agent entscheidet danach, ob er ihn lädt",
"This computer follows the server: what you change here is replaced by the next sync.": "Dieser Computer folgt dem Server: Änderungen hier werden bei der nächsten Synchronisierung ersetzt.",
"Sync settings": "Sync-Einstellungen",
"Stop picking memories": "Keine Erinnerungen mehr auswählen",
+9 -5
View File
@@ -604,11 +604,13 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
// Agents is named as the page sends it, so that it is this
// and not the instructions' own Agents that "agents" fills
Agents []string `json:"agents"`
Source string
Paths []string
Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents
Server library.Server
Hook library.Hook // a hook saved (#1790)
// Description is a new skill's (skills/create)
Description string `json:"description"`
Source string
Paths []string
Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents
Server library.Server
Hook library.Hook // a hook saved (#1790)
// a subagent saved (#2283)
Subagent library.Subagent
Agent string // the agent whose own skill is in the library's way
@@ -715,6 +717,8 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
res, err = library.RemoveSubagents([]string{in.Name})
case "skills/install":
res, err = library.InstallSkills(in.Source, in.Paths, in.Agents)
case "skills/create":
res, err = library.CreateSkill(in.Name, in.Description, in.Agents)
case "skills/update":
res, err = library.UpdateSkill(in.Name, in.Replace)
var gone *library.GoneError
+4 -3
View File
@@ -94,9 +94,10 @@ func inlinePage(html []byte, dir string) (out []byte, hashes []string) {
if !ok {
return tag
}
body = strings.ReplaceAll(body, "</script", `<\/script`)
hash(body)
s := "<script>" + body + "\n</script>"
// the hash covers the exact text between the tags, the newline
// before </script> included
s := "<script>" + strings.ReplaceAll(body, "</script", `<\/script`) + "\n</script>"
hash(strings.TrimSuffix(strings.TrimPrefix(s, "<script>"), "</script>"))
if attrDefer.MatchString(attrs) {
deferred = append(deferred, s)
return ""
+15
View File
@@ -2,12 +2,15 @@ package gui
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
@@ -456,6 +459,18 @@ func TestPluginPageWebComesAsOneDocument(t *testing.T) {
if n := strings.Count(csp, "'sha256-"); n != 3 || !strings.Contains(csp, "data:") {
t.Errorf("hashes of the three scripts: %s", csp)
}
// each hash is the sha256 of the exact bytes between the tags, as served
inl := regexp.MustCompile(`(?s)<script>(.*?)</script>`)
got := inl.FindAllStringSubmatch(body, -1)
if len(got) != 3 {
t.Fatalf("inline scripts: %d in %s", len(got), body)
}
for _, m := range got {
sum := sha256.Sum256([]byte(m[1]))
if h := "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"; !strings.Contains(csp, h) {
t.Errorf("served script %q has hash %s, not in the policy: %s", m[1], h, csp)
}
}
// not in a browser (the desktop window): files as they are
mux = http.NewServeMux()
pluginPageRoutes(mux, false)
@@ -0,0 +1,93 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A skill made in the Library (josephBenchap on X): Skills > New skill takes
// a name and a description and the agents, posts library/skills/create, and
// opens the new skill in the reader. A refusal is said in the dialog and the
// dialog stays. No native select, no sideways scroll. English and Chinese,
// Chromium and WebKit, 1100 and 420px. The API is faked.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/emo";
const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });
const lib = (skills) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [agent("codex", "Codex"), agent("claude", "Claude Code")],
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills, servers: [],
});
function server(lang, posts, state) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/library") return route.fulfill({ json: lib(state.skills) });
if (url.pathname === "/api/library/skills/create") {
const b = req.postDataJSON();
posts.push(b);
if (b.name === "taken") return route.fulfill({ status: 400, body: "there is a skill called taken already" });
state.skills = [{ name: b.name, description: b.description, agents: b.agents }];
return route.fulfill({ json: { ...lib(state.skills), result: { changed: b.agents, problems: [] } } });
}
if (url.pathname === "/api/library/skill") return route.fulfill({ json: { text: `---\nname: ${url.searchParams.get("name")}\n---\n`, path: `${HOME}/.magpie/library/skills/${url.searchParams.get("name")}/SKILL.md` } });
if (url.pathname === "/api/library/rtk") return route.fulfill({ json: {} });
if (url.pathname === "/api/davsync") return route.fulfill({ json: { on: false } });
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": Library makes a skill of the user's own", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const errors = [];
t.after(async () => { if (errors.length) console.log(errors); await browser.close(); });
for (const lang of ["en", "zh"]) {
for (const width of [1100, 420]) {
await t.test(`${lang} ${width}`, async () => {
const ctx = await browser.newContext({ viewport: { width, height: 800 } });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
const posts = [], state = { skills: [] };
await page.route("**/*", server(lang, posts, state));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const v = page.locator("#view-library");
await v.locator("[data-lib=new-skill]").click();
const dlg = page.locator(".lib-newskill");
await dlg.waitFor();
assert.equal(await dlg.locator("select").count(), 0, "native select");
const sideways = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
assert(sideways <= 0, `page scrolls sideways by ${sideways}px`);
// a refusal stays in the dialog
await dlg.locator("input").first().fill("taken");
await dlg.locator("textarea").fill("Does a thing");
await dlg.locator("button.primary").click();
await dlg.locator(".editor-error").filter({ hasText: "taken" }).waitFor();
assert.equal(posts.length, 1);
// one agent unticked, then created
await dlg.locator("input").first().fill("my-skill");
await dlg.locator(".lib-ag[data-agent=claude]").click();
await dlg.locator("button.primary").click();
await page.locator(".lib-reader").waitFor();
assert.deepEqual(posts[1], { name: "my-skill", description: "Does a thing", agents: ["codex"] });
await page.locator(".lib-reader .lib-md").filter({ hasText: "my-skill" }).waitFor();
await ctx.close();
});
}
}
});
}
@@ -0,0 +1,47 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A plugin page served to a browser comes as one document whose inline
// scripts are allowed by hash (pageinline.go). The hash is of the exact
// bytes between the tags, the newline before </script> included; a hash of
// the body alone blocks the script and leaves the page blank (zhangly1 on X).
// pluginpage_test.go checks the hashes Go sends against the bytes it serves;
// this checks the browsers agree, with no violation, and that a hash of the
// body without the newline would have been blocked.
const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const tok = "d".repeat(32);
const sha = (s) => `'sha256-${crypto.createHash("sha256").update(s).digest("base64")}'`;
const body = "window.ran = 1;";
function serve(hash) {
return async (route) => {
const url = new URL(route.request().url());
if (url.pathname !== `/_magpie/plugin/${tok}/index.html`) return route.fulfill({ status: 404, body: "" });
const doc = `<!doctype html><meta charset="utf-8"><script>${body}\n</script><p id=p>page</p>`;
return route.fulfill({ headers: { "Content-Type": "text/html", "Content-Security-Policy": `sandbox allow-scripts; default-src 'none'; script-src ${hash}` }, body: doc });
};
}
async function open(browser, hash) {
const p = await browser.newPage();
p.setDefaultNavigationTimeout(60000);
await p.addInitScript(() => { window.violations = []; document.addEventListener("securitypolicyviolation", (e) => window.violations.push(e.violatedDirective)); });
await p.route("**/*", serve(hash));
await p.goto(`http://magpie.test/_magpie/plugin/${tok}/index.html`);
return p;
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a hash of the served bytes runs the page's script`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const ok = await open(browser, sha(body + "\n"));
assert.equal(await ok.evaluate(() => window.ran), 1);
assert.deepEqual(await ok.evaluate(() => window.violations), []);
// the old hash, of the body without the newline served after it
const bad = await open(browser, sha(body));
assert.equal(await bad.evaluate(() => window.ran), undefined);
});
}
+80
View File
@@ -2,8 +2,11 @@ package gui
import (
"fmt"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
)
// magpie's windows are WebView2 on Windows, a runtime Windows 10 doesn't
@@ -127,3 +130,80 @@ func splitArgs(s string) []string {
}
return out
}
// WebView2 that does not come up. A magpie started while the one before it
// is still going down finds the profile folder held by the old
// msedgewebview2, and Wails waits a minute for a controller that never
// arrives, then exits (@ljlwlcz on X, 0.1.3688: a restart by a script left
// no window). Two things answer it: the start waits for the folder to be
// free, and a start that still fails is tried again, a few times.
// webView2TryEnv counts the starts that ended in a WebView2 failure; each
// relaunch passes it on.
const webView2TryEnv = "MAGPIE_WV2_TRY"
// webView2Tries is how many starts are made before the failure is shown.
const webView2Tries = 3
// webView2Folder is the folder WebView2 keeps its profile in: the one magpie
// passes Wails (webViewUserDataPath), else Wails' own default,
// %AppData%\<exe name>.
func webView2Folder(userDataPath, appData, exe string) string {
if userDataPath != "" {
return userDataPath
}
if appData == "" || exe == "" {
return ""
}
return filepath.Join(appData, filepath.Base(exe))
}
// webView2Failure says whether err is the webview not coming up, the
// errors Wails' Embed reports: the controller timeout and the loader's.
func webView2Failure(err error) bool {
if err == nil {
return false
}
m := strings.ToLower(err.Error())
return strings.Contains(m, "webview2")
}
// webView2Try is the number of starts already made, from the env value.
func webView2Try(v string) int {
n, err := strconv.Atoi(v)
if err != nil || n < 0 {
return 0
}
return n
}
// webView2Backoff is how long a start waits before the n-th try (n >= 1).
func webView2Backoff(n int) time.Duration {
return time.Duration(n) * 2 * time.Second
}
// awaitWebView2Folder polls free until it says so or max passes, and says
// whether it was free. sleep is a var for tests.
func awaitWebView2Folder(free func() bool, max, step time.Duration, sleep func(time.Duration)) bool {
for waited := time.Duration(0); ; waited += step {
if free() {
return true
}
if waited >= max {
return false
}
sleep(step)
}
}
// webView2FailedNotice is the box shown when the webview would not start
// after every try: what failed and what to do, in lang (English where it
// has none of its own).
func webView2FailedNotice(lang, reason, version string) (title, body string) {
if strings.HasPrefix(lang, "zh") {
return "magpie 的窗口没能打开",
fmt.Sprintf("WebView2 在 %d 次启动里都没有就绪(运行时 %s)。\r\n\r\n%s\r\n\r\n请结束残留的 msedgewebview2.exe 后重新打开 magpie;也可以用 \"magpie web\" 在浏览器里打开。详情见 magpie 的日志。", webView2Tries, version, reason)
}
return "magpie's window didn't open",
fmt.Sprintf("WebView2 was not ready in %d starts (runtime %s).\r\n\r\n%s\r\n\r\nEnd any leftover msedgewebview2.exe and open magpie again, or use \"magpie web\" in your browser. The details are in magpie's log.", webView2Tries, version, reason)
}
@@ -0,0 +1,35 @@
//go:build windows && !nogui
package gui
import (
"os"
"path/filepath"
"testing"
"golang.org/x/sys/windows"
)
// Chromium holds EBWebView\lockfile without sharing while its browser
// process runs; the start waits on it (@ljlwlcz on X).
func TestWebView2FreeSeesTheHeldLockfile(t *testing.T) {
dir := t.TempDir()
if !webView2Free(dir) {
t.Fatal("no lockfile is free")
}
lock := filepath.Join(dir, "EBWebView", "lockfile")
if err := os.MkdirAll(filepath.Dir(lock), 0o755); err != nil {
t.Fatal(err)
}
h, err := windows.CreateFile(windows.StringToUTF16Ptr(lock), windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.CREATE_ALWAYS, windows.FILE_ATTRIBUTE_NORMAL, 0)
if err != nil {
t.Fatal(err)
}
if webView2Free(dir) {
t.Fatal("a lockfile held without sharing is free")
}
windows.CloseHandle(h)
if !webView2Free(dir) {
t.Fatal("a released lockfile is held")
}
}
+11 -1
View File
@@ -2,7 +2,17 @@
package gui
import "github.com/wailsapp/wails/v3/pkg/application"
import (
"log"
"github.com/wailsapp/wails/v3/pkg/application"
)
// webView2Check: only Windows' windows are WebView2.
func webView2Check(*application.App) bool { return true }
// webView2Prepare: only Windows' windows are WebView2.
func webView2Prepare() {}
// webView2Failed: Wails exits after this on every OS; say why.
func webView2Failed(_ *application.App, err error) { log.Println("magpie:", err) }
+45
View File
@@ -1,8 +1,10 @@
package gui
import (
"errors"
"strings"
"testing"
"time"
)
// #1806 (ufec): Wails' "WebView2" is "" when its lookup fails, the version
@@ -55,3 +57,46 @@ func TestWebView2Notice(t *testing.T) {
t.Errorf("pt: %q, want English", title)
}
}
func TestWebView2Folder(t *testing.T) {
if got := webView2Folder(`D:\p\webview2`, `C:\A`, `C:\x\magpie.exe`); got != `D:\p\webview2` {
t.Fatal(got)
}
if got := webView2Folder("", "", "magpie.exe"); got != "" {
t.Fatal(got)
}
}
func TestWebView2Failure(t *testing.T) {
for err, want := range map[error]bool{
errors.New("timed out after 1m0s waiting for the WebView2 controller; x"): true,
errors.New("error calling Webview2Loader: boom"): true,
errors.New("something else"): false,
nil: false,
} {
if got := webView2Failure(err); got != want {
t.Errorf("%v: %t", err, got)
}
}
}
func TestWebView2Try(t *testing.T) {
if webView2Try("") != 0 || webView2Try("2") != 2 || webView2Try("-1") != 0 || webView2Try("x") != 0 {
t.Fatal("try")
}
}
// the start waits for the folder to be let go, and gives up after max
func TestAwaitWebView2Folder(t *testing.T) {
n := 0
var slept time.Duration
free := func() bool { n++; return n > 3 }
sleep := func(d time.Duration) { slept += d }
if !awaitWebView2Folder(free, time.Second, 100*time.Millisecond, sleep) || slept != 300*time.Millisecond {
t.Fatal(n, slept)
}
slept = 0
if awaitWebView2Folder(func() bool { return false }, time.Second, 100*time.Millisecond, sleep) || slept != time.Second {
t.Fatal(slept)
}
}
+77
View File
@@ -3,11 +3,18 @@
package gui
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"time"
"unsafe"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
"golang.org/x/sys/windows"
)
@@ -50,3 +57,73 @@ func webView2Box(title, body string) int {
webView2BoxStyle)
return int(r)
}
// webView2Dir is the profile folder WebView2 will use.
func webView2Dir() string {
exe, _ := os.Executable()
return webView2Folder(appdir.WebView(), os.Getenv("AppData"), exe)
}
// webView2Free says whether no other process holds the profile folder.
// Chromium keeps EBWebView\lockfile open without sharing while its browser
// process runs, so opening it fails with a sharing violation until the
// previous magpie's msedgewebview2 has gone.
func webView2Free(dir string) bool {
if dir == "" {
return true
}
f, err := os.OpenFile(filepath.Join(dir, "EBWebView", "lockfile"), os.O_RDWR, 0)
if err != nil {
return !errors.Is(err, windows.ERROR_SHARING_VIOLATION) && !errors.Is(err, windows.ERROR_ACCESS_DENIED)
}
f.Close()
return true
}
// webView2Prepare runs before the first window. A start after a failed
// one backs off first; then it waits, up to 30s, for the previous
// process' WebView2 to let go of the profile folder.
func webView2Prepare() {
try := webView2Try(os.Getenv(webView2TryEnv))
if try > 0 {
log.Printf("magpie: WebView2 start %d of %d, after a failure", try+1, webView2Tries)
time.Sleep(webView2Backoff(try))
}
dir := webView2Dir()
start := time.Now()
if !awaitWebView2Folder(func() bool { return webView2Free(dir) }, 30*time.Second, 250*time.Millisecond, time.Sleep) {
log.Printf("magpie: WebView2 folder %s is still held by another process after 30s; going on", dir)
} else if d := time.Since(start); d > time.Second {
log.Printf("magpie: waited %s for WebView2 folder %s to be free", d.Round(100*time.Millisecond), dir)
}
}
// webView2Failed is Wails' ErrorHandler; Wails exits as soon as it
// returns. It logs the error with what is needed to read it, and for a
// WebView2 failure starts magpie again (up to webView2Tries starts), the
// last failure shown in a box with the log's place.
func webView2Failed(app *application.App, err error) {
dir := webView2Dir()
ver := "unknown"
if app != nil {
ver = fmt.Sprint(app.Env.Info().PlatformInfo["WebView2"])
}
log.Printf("magpie: %v (WebView2 runtime %q, profile folder %s, held by another process: %t)", err, ver, dir, !webView2Free(dir))
if !webView2Failure(err) {
return
}
try := webView2Try(os.Getenv(webView2TryEnv)) + 1
if try < webView2Tries {
log.Printf("magpie: starting again (start %d of %d)", try+1, webView2Tries)
if rerr := update.Respawn(fmt.Sprintf("%s=%d", webView2TryEnv, try)); rerr != nil {
log.Println("magpie: starting again:", rerr)
} else {
return
}
}
title, body := webView2FailedNotice(trayLang(settings.Load().Lang, systemLang), err.Error(), ver)
procMessageBoxW.Call(0,
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(body))),
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(title))),
mbIconError|mbSetForeground|mbTopmost)
}
+44
View File
@@ -0,0 +1,44 @@
package library
import (
"os"
"path/filepath"
"strings"
"testing"
)
// A skill made in the Library (josephBenchap on X): SKILL.md with valid
// front matter in the library's folder, given to the agents picked, and a
// name that clashes or isn't folder-safe is refused.
func TestCreateSkill(t *testing.T) {
h := sandbox(t)
ok(t)(CreateSkill("my-skill", "Does: a thing\nacross lines", []string{"claude", "codex"}))
b, err := os.ReadFile(filepath.Join(skillDir("my-skill"), "SKILL.md"))
if err != nil {
t.Fatal(err)
}
m := parseMeta(b)
if m.Name != "my-skill" || m.Description != "Does: a thing across lines" {
t.Errorf("front matter: %+v\\n%s", m, b)
}
for _, d := range []string{".claude/skills/my-skill", ".codex/skills/my-skill"} {
if _, err := os.Stat(filepath.Join(h, d, "SKILL.md")); err != nil {
t.Errorf("not given to %s: %v", d, err)
}
}
v, _ := Read(nil)
if len(v.Skills) != 1 || v.Skills[0].Name != "my-skill" {
t.Errorf("listed: %+v", v.Skills)
}
skill(t, filepath.Join(h, ".claude/skills/theirs"), "theirs", "An agent's own")
for _, c := range [][2]string{
{"My-Skill", "d"}, {"theirs", "d"}, {"../x", "d"}, {"a/b", "d"}, {"", "d"}, {"fine", " "}, {"fine", strings.Repeat("x", 1025)},
} {
if _, err := CreateSkill(c[0], c[1], nil); err == nil {
t.Errorf("%q / %.10q was taken", c[0], c[1])
}
}
if _, err := os.Lstat(skillDir("fine")); err == nil {
t.Error("a refused skill left a folder")
}
}
+47
View File
@@ -1731,6 +1731,53 @@ func (l *Library) offered(p *Probe, path string, shown bool) {
}
}
// CreateSkill makes a skill of the user's own in the library's folder: a
// SKILL.md with a name and description in its front matter, listed with no
// source and given to the agents like any other. The name can't be one the
// library has, one an agent has of its own, or a folder in the way.
func CreateSkill(name, description string, agents []string) (*Result, error) {
name = strings.TrimSpace(name)
if err := checkName("skill", name); err != nil {
return nil, err
}
description = strings.Join(strings.Fields(description), " ")
if description == "" {
return nil, errors.New("a skill needs a description: it is how an agent knows when to load it")
}
if len([]rune(description)) > 1024 {
return nil, errors.New("the description is over 1024 characters")
}
return change(func(l *Library) error {
same := func(n string) bool { return strings.EqualFold(n, name) }
if slices.ContainsFunc(l.Skills, func(s *Skill) bool { return same(s.Name) }) ||
slices.ContainsFunc(foundSkills(l), func(f FoundSkill) bool { return same(f.Name) }) {
return fmt.Errorf("there is a skill called %s already", name)
}
dir := skillDir(name)
if _, err := os.Lstat(dir); err == nil {
return fmt.Errorf("the library's folder already has a %s in it (%s)", name, dir)
} else if !errors.Is(err, fs.ErrNotExist) {
return err
}
head, err := yaml.Marshal(meta{Name: name, Description: description})
if err != nil {
return err
}
text := "---\n" + string(head) + "---\n\n# " + name + "\n\nWrite what the agent should do when this skill is used.\n"
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(text), 0o644); err != nil {
os.RemoveAll(dir)
return err
}
ag := slices.Clone(agents)
slices.Sort(ag)
l.Skills = append(l.Skills, &Skill{Name: name, Agents: slices.Compact(ag)})
return nil
})
}
// UpdateSkill fetches a skill from GitHub again, in place: the agents'
// links go on pointing at it. One changed here since it was fetched is
// an *EditedError unless replace is set, and then the changed version is
+78 -7
View File
@@ -3,6 +3,7 @@ package provider
import (
"cmp"
"net/url"
"slices"
"strings"
)
@@ -20,7 +21,16 @@ func openCodeRoot(base string) (root, catalogID string) {
if !openCodeHost(u.Hostname()) {
return "", ""
}
switch path := strings.TrimSuffix(strings.TrimRight(u.Path, "/"), "/v1"); path {
path := strings.TrimRight(u.Path, "/")
if r, ok := strings.CutSuffix(path, "/google/v1beta"); ok {
path = r
} else {
path = strings.TrimSuffix(path, "/v1")
for _, api := range []string{"/openai", "/anthropic", "/google"} {
path = strings.TrimSuffix(path, api)
}
}
switch path {
case "/zen/go", "/inference/go":
return u.Scheme + "://" + u.Host + path, "opencode-go"
case "/zen", "/inference":
@@ -63,15 +73,54 @@ func openCodeGateway(base string) string {
// root is: models/{model}:streamGenerateContent is asked under it. Zen's
// /zen/v1 relays it to the inference API's Google route, reading the key
// from x-goog-api-key; Go's /zen/go/v1 has no such route (404), so Go's
// Gemini models are asked at the inference API's /inference/go/v1, where
// Go's docs give their endpoint (opencode.ai/v2/docs/console/go, #2168).
// Gemini models are asked at the inference API, where Go's docs give
// their endpoint: /inference/go/google/v1beta/models/{model} (since
// November 2026; before it /inference/go/v1, #2168).
func openCodeGemini(root string) string {
if r, ok := strings.CutSuffix(root, "/zen/go"); ok {
return r + "/inference/go/v1"
return r + "/inference/go/google/v1beta"
}
if strings.HasSuffix(root, "/inference/go") {
return root + "/google/v1beta"
}
return root + "/v1"
}
// openCodeGoSplit is whether a Go URL names its API in the path, the way
// Go's docs give them since November 2026: …/inference/go/openai/v1 (chat
// and Responses), …/inference/go/anthropic (Messages) and
// …/inference/go/google/v1beta (Gemini).
func openCodeGoSplit(u string) bool {
pu, err := url.Parse(strings.TrimSpace(u))
if err != nil || openCodeGateway(u) != "go" {
return false
}
for _, seg := range strings.Split(pu.Path, "/") {
if seg == "openai" || seg == "anthropic" || seg == "google" {
return true
}
}
return false
}
// openCodeGoOld are the URLs the OpenCode Go preset gave before Go's docs
// named an endpoint per API; a provider of the preset saved with them is
// moved to where the docs have them (openCodeEndpoints).
var openCodeGoOld = map[string]bool{
"https://opencode.ai/zen/go/v1": true,
"https://opencode.ai/zen/go": true,
"https://opencode.ai/inference/go/v1": true,
"https://opencode.ai/inference/go": true,
}
// OpenCodeGo are the URLs Go's docs give each API (opencode.ai/docs/console/go,
// Endpoints).
const (
OpenCodeGoChat = "https://opencode.ai/inference/go/openai/v1"
OpenCodeGoAnthropic = "https://opencode.ai/inference/go/anthropic"
OpenCodeGoGemini = "https://opencode.ai/inference/go/google/v1beta"
)
// openCodeEndpoints fills in the APIs of OpenCode's gateway a provider at
// it was saved without. Zen and Go serve each model on one API of three,
// all under one root — chat completions and Responses at /v1, Anthropic's
@@ -96,9 +145,31 @@ func (p *Provider) openCodeEndpoints() {
if root == "" {
return
}
p.Chat = cmp.Or(p.Chat, root+"/v1")
p.Responses = cmp.Or(p.Responses, root+"/v1")
p.Anthropic = cmp.Or(p.Anthropic, root)
chat, anthropic := root+"/v1", root
if strings.HasSuffix(root, "/inference/go") && slices.ContainsFunc([]string{p.Chat, p.Responses, p.Anthropic, p.Gemini}, openCodeGoSplit) {
chat, anthropic = root+"/openai/v1", root+"/anthropic"
}
if p.Preset == "opencode-go" {
// the preset's own URLs, saved before Go's docs named one per API
for _, f := range []struct {
have *string
to string
}{{&p.Chat, OpenCodeGoChat}, {&p.Responses, OpenCodeGoChat}, {&p.Anthropic, OpenCodeGoAnthropic}} {
if openCodeGoOld[strings.ToLower(*f.have)] {
*f.have = f.to
}
}
if strings.EqualFold(p.Gemini, "https://opencode.ai/inference/go/v1") {
p.Gemini = OpenCodeGoGemini
}
root, catalogID = openCodeRoot(cmp.Or(p.Chat, p.Responses, p.Anthropic, p.Gemini))
if strings.HasSuffix(root, "/inference/go") {
chat, anthropic = root+"/openai/v1", root+"/anthropic"
}
}
p.Chat = cmp.Or(p.Chat, chat)
p.Responses = cmp.Or(p.Responses, chat)
p.Anthropic = cmp.Or(p.Anthropic, anthropic)
p.Gemini = cmp.Or(p.Gemini, openCodeGemini(root))
p.Catalog = cmp.Or(p.Catalog, catalogID)
}
+10 -3
View File
@@ -51,14 +51,21 @@ func TestOpenCodeEndpointsFilledIn(t *testing.T) {
apis map[string]Protocol // "" for none named
}{
{"go, chat alone", Provider{ID: "opencode-go", Chat: zg + "/v1"},
zg + "/v1", zg + "/v1", zg, igo + "/v1", "opencode-go",
zg + "/v1", zg + "/v1", zg, igo + "/google/v1beta", "opencode-go",
map[string]Protocol{"gpt-6-luna": Responses, "minimax-m2.7": Anthropic, "gemini-4-argon-contributor": Gemini, "glm-5.3": ""}},
{"go, anthropic alone with /v1", Provider{ID: "ocgo", Anthropic: zg + "/v1"},
zg + "/v1", zg + "/v1", zg, igo + "/v1", "opencode-go",
zg + "/v1", zg + "/v1", zg, igo + "/google/v1beta", "opencode-go",
map[string]Protocol{"gpt-6-luna": Responses}},
{"go at the inference API", Provider{ID: "ocgo", Chat: igo + "/v1"},
igo + "/v1", igo + "/v1", igo, igo + "/v1", "opencode-go",
igo + "/v1", igo + "/v1", igo, igo + "/google/v1beta", "opencode-go",
map[string]Protocol{"gemini-4-argon-contributor": Gemini, "glm-5.3": ""}},
{"go at the per-API URLs the docs give", Provider{ID: "ocgo", Chat: igo + "/openai/v1"},
igo + "/openai/v1", igo + "/openai/v1", igo + "/anthropic", igo + "/google/v1beta", "opencode-go",
map[string]Protocol{"gemini-4-argon-contributor": Gemini, "gpt-6-luna": Responses}},
{"go, gemini url alone", Provider{ID: "ocgo", Gemini: igo + "/google/v1beta"},
igo + "/openai/v1", igo + "/openai/v1", igo + "/anthropic", igo + "/google/v1beta", "opencode-go", nil},
{"the go preset saved with its old URLs", Provider{ID: "opencode-go", Preset: "opencode-go", Chat: zg + "/v1", Responses: zg + "/v1", Anthropic: zg},
igo + "/openai/v1", igo + "/openai/v1", igo + "/anthropic", igo + "/google/v1beta", "opencode-go", nil},
{"zen saved with go's catalog", Provider{ID: "opencode-go", Catalog: "opencode-go", Chat: zen + "/v1"},
zen + "/v1", zen + "/v1", zen, zen + "/v1", "opencode-go",
map[string]Protocol{"claude-opus-5": Anthropic, "gemini-3-flash": Gemini, "minimax-m2.7": ""}},
+1 -1
View File
@@ -564,7 +564,7 @@ var presets = []PresetDef{
Chat: "https://api.gmi-serving.com/v1",
Website: "https://www.gmicloud.ai", KeysURL: "https://console.gmicloud.ai"},
{ID: "opencode-go", Name: "OpenCode Go", Icon: "opencode", Kind: KindRelay, Catalog: "opencode-go",
Chat: "https://opencode.ai/zen/go/v1", Responses: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go",
Chat: OpenCodeGoChat, Responses: OpenCodeGoChat, Anthropic: OpenCodeGoAnthropic,
Note: "open coding models, $10/month",
Website: "https://opencode.ai/docs/go", KeysURL: "https://opencode.ai/auth"},
// Cline's plan for open models, at the Cline API with a Cline key: the
+32 -12
View File
@@ -15,9 +15,10 @@ import (
// the same account at different hours).
//
// - A card is shown for a Remote only when the Remote is enabled for a
// model of the provider the card is of (remoteCardWanted): the first
// part of the card's id is the first part of those models' ids
// (provider/model, as that remote lists them).
// model of the provider the card is of (remoteCardWanted): the
// card's id is the provider path of one of those models' ids, or a
// parent of it, whole parts only (provider/model, as that remote lists
// them; relay/strata enabled does not tell relay/kiro).
// - A card whose way names a magpie twice, or this one and another, is
// no card (catalog.Loops): it isn't kept (keepRemoteCards) nor told.
// - One account's copies are one card, the newest complete reading
@@ -35,18 +36,37 @@ func remoteCardWanted(p Provider) func(id string) bool {
if len(ms) == 0 {
return func(string) bool { return true }
}
heads := map[string]bool{}
for _, m := range ms {
head, _, ok := strings.Cut(m.ID, "/")
if !ok {
ids := make([]string, len(ms))
for i, m := range ms {
ids[i] = m.ID
}
return cardWantedFor(ids)
}
// cardWantedFor is remoteCardWanted for the enabled model ids as the remote
// lists them: a model's provider path is its id less the last part
// ("relay/strata/m" is of relay/strata). A card is wanted when its id is
// such a path or one of its parents, whole parts only: relay/strata
// enabled tells relay/strata and relay, never relay/kiro or relay/strat.
// A model with no provider before its name leaves it unknown, so wanted.
func cardWantedFor(ids []string) func(id string) bool {
paths := map[string]bool{}
for _, mid := range ids {
i := strings.LastIndex(mid, "/")
if i <= 0 {
return func(string) bool { return true }
}
heads[head] = true
}
return func(id string) bool {
head, _, _ := strings.Cut(id, "/")
return heads[head]
path := mid[:i]
for {
paths[path] = true
j := strings.LastIndex(path, "/")
if j < 0 {
break
}
path = path[:j]
}
}
return func(id string) bool { return paths[id] }
}
// withoutLoops is cards less those whose way comes back to this magpie.
+33
View File
@@ -668,3 +668,36 @@ func TestRemoteCardsFollowEnabledModelsAndDedupe(t *testing.T) {
}
}
}
// @748975219 on X (0.1.3771): with only relay/strata/model enabled, the
// cards of relay/kiro and relay/codex still passed, as only the first part
// of the card's id was compared.
func TestRemoteCardWantedByWholePath(t *testing.T) {
cases := []struct {
name string
ids []string
yes []string
no []string
}{
{"two levels", []string{"relay/strata/m"}, []string{"relay/strata", "relay"}, []string{"relay/kiro", "relay/codex", "kiro", "relay/strata/x"}},
{"three levels", []string{"a/b/c/m"}, []string{"a/b/c", "a/b", "a"}, []string{"a/b/d", "a/x", "a/b/c/d", "b"}},
{"not at a boundary", []string{"relay/kiro/m"}, []string{"relay/kiro"}, []string{"relay/kir", "relay/kiro2", "relay/kiroo", "rel"}},
{"prefix of the other way", []string{"relay/kir/m"}, []string{"relay/kir"}, []string{"relay/kiro"}},
{"several", []string{"relay/strata/m", "relay/kiro/n"}, []string{"relay/strata", "relay/kiro"}, []string{"relay/codex"}},
{"one level", []string{"kiro/m"}, []string{"kiro"}, []string{"codex", "kiro/x"}},
{"unknown provider", []string{"m"}, []string{"anything", "a/b"}, nil},
}
for _, c := range cases {
w := cardWantedFor(c.ids)
for _, id := range c.yes {
if !w(id) {
t.Errorf("%s: %v should tell %q", c.name, c.ids, id)
}
}
for _, id := range c.no {
if w(id) {
t.Errorf("%s: %v should not tell %q", c.name, c.ids, id)
}
}
}
}
+13
View File
@@ -216,3 +216,16 @@ func ReadBlocked(current string) *Blocked {
// ClearBlocked forgets the note: the version started after all.
func ClearBlocked() { os.Remove(blockedFile()) }
// Respawn starts this program again with the arguments it was started
// with and extra (NAME=value) added to its environment, detached. The new
// process waits for this one to exit, as a relaunch does (AwaitPredecessor).
func Respawn(extra ...string) error {
exe, err := os.Executable()
if err != nil {
return err
}
env := append(os.Environ(), "MAGPIE_REPLACES="+strconv.Itoa(os.Getpid()))
_, _, err = launch(exe, os.Args[1:], append(env, extra...))
return err
}