library: an open memory holds still while the Memory tab polls (Nietzsche_Li on X)
"资源库-记忆中,被展开的记忆的表单会定时抖动". While search by meaning
still has memories to read (read < of, which can last up to a minute
between memembed.Keep's reads) or a learn-from-conversations run goes,
the Memory tab reads its row again every 2s, and each read drew the
whole page anew. The open editor was a new .lib-detail each time and
played its content-in entrance (opacity .5, 2px slide) every 2s.
- semWatch/distWatch draw nothing when the read changed nothing, and
redraw only their own row (redrawRow) when it did; the whole tab only
when the memories changed.
- render() marks a .lib-detail open before it (same data-detail) as kept,
so it doesn't replay its entrance. This covers every render of an
open editor in the Library: memories, instruction sets and agents'
files (the siblings; no other Library tab polls into render()).
- A new memory's text no longer takes the focus back on every render.
Run (mote): library-memory-steady.test.cjs, all 5 languages, 980/420,
chromium + webkit: green 4 of 4 whole-file runs after the last change
(webkit alone 2 of 2 before it). Broken by hand: the same test against
origin/main's client.js and library.css: 22 of 22 red ("the editor
played its entrance again"). One webkit de 420 red was the test's own
first row click intercepted by the header at 420px while the page
settled; the test now opens rows with a DOM click.
Also run, both engines, every language, 980/420: library-memory, library-memory-select, library-memory-suggest, memory-icon, library-instr-busy, library-instr-sets, library-linked-set, library-follow-server: all green. No Go code changed, so no go test or vet.
Not tried: the real app on a real memory store mid-read.
This commit is contained in:
@@ -1308,12 +1308,6 @@ each one.
|
||||
- A record that points elsewhere: 2f34649a6's body is "Run: see push
|
||||
notes", and 8f82e08b4's "(see below)" has nothing below it; neither
|
||||
says whether what it ran passed. A pointer is not a record (10-14).
|
||||
- The eager-regexp guard, red twice more: 1ca2c62c4 (catalog, fixed
|
||||
in 19fd0dfb8) and d52e2feaf (agent, whose record is one -run in
|
||||
./internal/agent; fixed in 6a506e283). TestNoEagerPackageRegexps
|
||||
lives in the root package, so a run of the changed package never
|
||||
reaches it. A new package-level regexp is lazyre.New, and `go test
|
||||
.` runs beside the package's own.
|
||||
- **Done right on 10-17.** The retire stack (0f1666b38 to de671719a)
|
||||
diffed staticcheck's U1000 against its base for dead code, b98f906b1
|
||||
was red on the old code for an own-account gap, and 8 subscriptions
|
||||
|
||||
@@ -20,10 +20,6 @@
|
||||
<key>CFBundleURLName</key><string>com.yetone.magpie.import</string>
|
||||
<key>CFBundleURLSchemes</key><array><string>magpie</string></array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key><string>com.yetone.magpie.ccswitch</string>
|
||||
<key>CFBundleURLSchemes</key><array><string>ccswitch</string></array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>NSHumanReadableCopyright</key><string>yetone</string>
|
||||
</dict>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -193,7 +193,14 @@ further (`State.Since`), unless a range is picked.
|
||||
range reads at once; a bad level or range is a 400,
|
||||
`TestDistillRangeAndEffortRoutes`) and
|
||||
`POST /api/memory/distill/run`. The row polls every 2s while a run
|
||||
goes and reloads the memories when it ends.
|
||||
goes and reloads the memories when it ends. Search by meaning's row
|
||||
polls the same way while the model downloads or memories wait to be
|
||||
read. A poll that reads nothing new draws nothing; one that does
|
||||
redraws its own row only (`redrawRow`), and the whole tab only when the
|
||||
memories changed. A render keeps an editor that was open (`.lib-detail`
|
||||
with the same `data-detail`) from playing its entrance again
|
||||
(Nietzsche_Li on X: the open memory jittered every 2s;
|
||||
`library-memory-steady.test.cjs`).
|
||||
|
||||
### Dreaming
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -3,14 +3,14 @@ package agent
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"regexp"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// piMagpieExt matches a Pi package source for the pi-magpie extension:
|
||||
// npm:pi-magpie, npm:pi-magpie@0.1.6, or a path or git source ending in it.
|
||||
var piMagpieExt = lazyre.New(`(^|[:/\\])pi-magpie(@[^/\\]*)?(#.*)?$`)
|
||||
var piMagpieExt = regexp.MustCompile(`(^|[:/\\])pi-magpie(@[^/\\]*)?(#.*)?$`)
|
||||
|
||||
// piMagpieInstalled says Pi's settings.json lists the pi-magpie extension
|
||||
// in "packages". It serves provider "magpie" from magpie's live catalog,
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
const keyBalanceUsage = "magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|daily|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]"
|
||||
const keyBalanceUsage = "magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]"
|
||||
|
||||
// keyBalanceCmd shows, or sets, the balance typed by hand on a provider's
|
||||
// API keys whose vendor tells none (tenacious_eagle on Discord): what is
|
||||
|
||||
@@ -60,15 +60,6 @@ func TestKeyBalanceCmd(t *testing.T) {
|
||||
if b, _ := typed(); b.CNY == nil || *b.CNY != 700 || b.Refill == nil || *b.Refill != (provider.Refill{Every: provider.RefillWeek, Day: 5}) {
|
||||
t.Fatalf("weekly:fri: %+v", b)
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--refill", "daily"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := typed(); b.CNY == nil || *b.CNY != 700 || b.Refill == nil || *b.Refill != (provider.Refill{Every: provider.RefillDay}) {
|
||||
t.Fatalf("daily: %+v", b)
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--refill=weekly:fri"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range [][]string{{"relay", "Team", "--refill", "yearly"}, {"relay", "--refill", "monthly"}, {"relay", "Team", "off", "--refill", "monthly"}, {"relay", "Team", "--refill"}} {
|
||||
if err := providerCmd(append([]string{"provider", "key-balance"}, bad...)); err == nil {
|
||||
t.Fatalf("%v taken", bad)
|
||||
|
||||
@@ -108,7 +108,7 @@ const providerUsage = `usage:
|
||||
how much an API key may spend, in USD as the Usage page prices its calls,
|
||||
a day (the default), a month or in all from now: at it, routing takes the
|
||||
key for used up and goes on to the other keys and the fallbacks
|
||||
magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|daily|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]
|
||||
magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]
|
||||
the balance on an API key whose vendor tells none, typed from its own page
|
||||
in USD or in yuan (¥100): the Usage page shows it less what magpie prices the
|
||||
key's calls at since; with --refill it is whole again each month or week;
|
||||
|
||||
@@ -147,14 +147,12 @@ const I18N = {
|
||||
"No credit that expires": "去掉限期额度",
|
||||
"Refills each month…": "每月恢复…",
|
||||
"Refills each week…": "每周恢复…",
|
||||
"Refills each day": "每日恢复",
|
||||
"Never refills": "不恢复",
|
||||
"Refills on": "恢复于",
|
||||
"Refill day of the month": "每月恢复的日期",
|
||||
"A day of the month is a whole number from 1 to 31": "每月的日期是 1 到 31 之间的整数",
|
||||
"{who} no longer refills": "{who} 不再恢复余额",
|
||||
"{who} refills each {weekday}": "{who} 每{weekday}恢复余额",
|
||||
"{who} refills each day": "{who} 每日恢复余额",
|
||||
"{who} refills on day {day} of each month": "{who} 每月 {day} 日恢复余额",
|
||||
"A spend cap is an amount in USD above 0, up to 1,000,000": "消费上限是大于 0、不超过 1,000,000 的美元金额",
|
||||
"Spend cap": "消费上限",
|
||||
@@ -5302,14 +5300,12 @@ const I18N = {
|
||||
"No credit that expires": "去掉限期額度",
|
||||
"Refills each month…": "每月恢復…",
|
||||
"Refills each week…": "每週恢復…",
|
||||
"Refills each day": "每日恢復",
|
||||
"Never refills": "不恢復",
|
||||
"Refills on": "恢復於",
|
||||
"Refill day of the month": "每月恢復的日期",
|
||||
"A day of the month is a whole number from 1 to 31": "每月的日期是 1 到 31 之間的整數",
|
||||
"{who} no longer refills": "{who} 不再恢復餘額",
|
||||
"{who} refills each {weekday}": "{who} 每{weekday}恢復餘額",
|
||||
"{who} refills each day": "{who} 每日恢復餘額",
|
||||
"{who} refills on day {day} of each month": "{who} 每月 {day} 日恢復餘額",
|
||||
"A spend cap is an amount in USD above 0, up to 1,000,000": "消費上限是大於 0、不超過 1,000,000 的美元金額",
|
||||
"Spend cap": "消費上限",
|
||||
@@ -10442,14 +10438,12 @@ const I18N = {
|
||||
"No credit that expires": "期限付きクレジットなし",
|
||||
"Refills each month…": "毎月戻す…",
|
||||
"Refills each week…": "毎週戻す…",
|
||||
"Refills each day": "毎日戻す",
|
||||
"Never refills": "戻さない",
|
||||
"Refills on": "戻す曜日",
|
||||
"Refill day of the month": "毎月戻す日",
|
||||
"A day of the month is a whole number from 1 to 31": "日付は 1 から 31 までの整数です",
|
||||
"{who} no longer refills": "{who} の残高はもう戻りません",
|
||||
"{who} refills each {weekday}": "{who} の残高は毎週{weekday}に戻ります",
|
||||
"{who} refills each day": "{who} の残高は毎日戻ります",
|
||||
"{who} refills on day {day} of each month": "{who} の残高は毎月 {day} 日に戻ります",
|
||||
"A spend cap is an amount in USD above 0, up to 1,000,000": "支出上限は 0 より大きく 1,000,000 以下の USD 金額です",
|
||||
"Spend cap": "支出上限",
|
||||
@@ -15584,14 +15578,12 @@ const I18N = {
|
||||
"No credit that expires": "Kein ablaufendes Guthaben",
|
||||
"Refills each month…": "Monatlich auffüllen…",
|
||||
"Refills each week…": "Wöchentlich auffüllen…",
|
||||
"Refills each day": "Täglich auffüllen",
|
||||
"Never refills": "Nie auffüllen",
|
||||
"Refills on": "Auffüllen am",
|
||||
"Refill day of the month": "Tag des Monats zum Auffüllen",
|
||||
"A day of the month is a whole number from 1 to 31": "Ein Tag des Monats ist eine ganze Zahl von 1 bis 31",
|
||||
"{who} no longer refills": "{who} wird nicht mehr aufgefüllt",
|
||||
"{who} refills each {weekday}": "{who} wird jeden {weekday} aufgefüllt",
|
||||
"{who} refills each day": "{who} wird jeden Tag aufgefüllt",
|
||||
"{who} refills on day {day} of each month": "{who} wird am {day}. jedes Monats aufgefüllt",
|
||||
"A spend cap is an amount in USD above 0, up to 1,000,000": "Ein Ausgabenlimit ist ein Betrag in USD über 0, bis 1.000.000",
|
||||
"Spend cap": "Ausgabenlimit",
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
// own usage prices the calls it sends on the key (provider/
|
||||
// key_balance_own.go). Typing it again sets it anew. It may be typed in
|
||||
// yuan ("¥100", or picked beside the field, which starts at the balance's
|
||||
// own currency, else Settings' one), and may refill each month, week or
|
||||
// day (Kelen_Yc on X).
|
||||
// own currency, else Settings' one), and may refill each month or week.
|
||||
// Credit may come on top that expires on a day, in grants (promotional
|
||||
// credit twice, gone on two days: tenacious_eagle_96548), the one that
|
||||
// goes soonest spent first: the pill says how much of each is left and in
|
||||
@@ -72,7 +71,6 @@ function keyBalancePill(p, k) {
|
||||
const refill = (r) => accountAction("provider/keybalancerefill", { id: p.id, account: k.id, refill: r },
|
||||
!r ? t("{who} no longer refills", { who: name })
|
||||
: r.every === "week" ? t("{who} refills each {weekday}", { who: name, weekday: weekdayName(r.day) })
|
||||
: r.every === "day" ? t("{who} refills each day", { who: name })
|
||||
: t("{who} refills on day {day} of each month", { who: name, day: r.day }));
|
||||
const expiring = (v) => accountAction("provider/keyexpiring", { id: p.id, account: k.id, expiring: v },
|
||||
!v ? t("{who} has no credit that expires", { who: name }) : t("{who} has {amount} that counts through {last}", { who: name, amount: moneyText(v.amount, cny), last: dateText(v.until) }));
|
||||
@@ -189,11 +187,9 @@ function keyBalancePill(p, k) {
|
||||
...xs.length > 1 || b.expired ? [{ v: "noexp", name: "No credit that expires", note: "" }] : [],
|
||||
{ v: "month", name: "Refills each month…", note: "" },
|
||||
{ v: "week", name: "Refills each week…", note: "" },
|
||||
{ v: "day", name: "Refills each day", note: "" },
|
||||
{ v: "never", name: "Never refills", note: "" },
|
||||
{ v: "off", name: "No balance", note: "" },
|
||||
], b.refill?.every || "never", (v) => v === "off" ? set(null) : v === "exp" ? credit() : v === "noexp" ? expiring(null) : v === "month" ? monthly() : v === "week" ? weekly()
|
||||
: v === "day" ? refill({ every: "day", day: 0 })
|
||||
: v === "never" ? b.refill && refill(null) : v[0] === "x" ? unexpiring(xs[+v.slice(1)]) : type(), "Balance", "sess-menu");
|
||||
// a grant that goes within a week says so in amber, as on the pill
|
||||
const items = protoMenu?.box.querySelectorAll(".pm-item");
|
||||
|
||||
@@ -994,6 +994,10 @@ magpie.plugin("library", (ctx) => {
|
||||
const top = page.scrollTop;
|
||||
const focus = document.activeElement?.dataset?.lib; // keep the caret where the reader is typing
|
||||
const caret = focus ? [document.activeElement.selectionStart, document.activeElement.selectionEnd] : null;
|
||||
// an editor open before is open still, not opened again: drawn anew
|
||||
// it would fade and slide in on every render, which a poll's made a
|
||||
// jitter every 2s (Nietzsche_Li on X)
|
||||
const had = new Set([...page.querySelectorAll(".lib-detail[data-detail]")].map((d) => d.dataset.detail));
|
||||
page.replaceChildren();
|
||||
fits = [];
|
||||
// the MCP servers alone with no agent to write to; the tab the reader
|
||||
@@ -1025,6 +1029,7 @@ magpie.plugin("library", (ctx) => {
|
||||
else renderSkills(body);
|
||||
page.append(body);
|
||||
for (const n of body.querySelectorAll(".row-head .note")) n.title = n.textContent;
|
||||
for (const d of page.querySelectorAll(".lib-detail[data-detail]")) if (had.has(d.dataset.detail)) d.classList.add("kept");
|
||||
for (const f of fits.splice(0)) f();
|
||||
page.scrollTop = top;
|
||||
syncLists(); // a long list's rows where the view is, before it's painted
|
||||
@@ -1518,9 +1523,9 @@ magpie.plugin("library", (ctx) => {
|
||||
if (!s?.on || !(s.downloading || s.reading || (s.installed && s.read < s.of && !s.failed))) return;
|
||||
semPoll = setTimeout(async () => {
|
||||
if (tab !== "memory") return;
|
||||
const was = s.installed;
|
||||
const was = s.installed, before = JSON.stringify(sem);
|
||||
try { sem = await api("memory/semantic"); } catch {}
|
||||
render();
|
||||
if (JSON.stringify(sem) !== before) redrawRow(".lib-memsem", semRow);
|
||||
semWatch();
|
||||
if (!was && sem.installed) rankSoon();
|
||||
}, 2000);
|
||||
@@ -1555,14 +1560,23 @@ magpie.plugin("library", (ctx) => {
|
||||
if (!dist?.running && !dist?.dreaming) return;
|
||||
distPoll = setTimeout(async () => {
|
||||
if (tab !== "memory") return;
|
||||
const before = JSON.stringify(dist), memWas = JSON.stringify(mem);
|
||||
try {
|
||||
dist = await api("memory/distill");
|
||||
if (!dist.running && !dist.dreaming) mem = await api("memory");
|
||||
} catch {}
|
||||
render();
|
||||
if (JSON.stringify(mem) !== memWas) render();
|
||||
else if (JSON.stringify(dist) !== before) { redrawRow(".lib-memdistill", distillRow); redrawRow(".lib-memdream", dreamRow); }
|
||||
distWatch();
|
||||
}, 2000);
|
||||
}
|
||||
// a poll's news drawn in its own row of the memory card, so the
|
||||
// memories under it, and the one open to edit, stay as they are
|
||||
function redrawRow(sel, make) {
|
||||
const old = page.querySelector(".lib-memcard > " + sel);
|
||||
if (old) old.replaceWith(make());
|
||||
else render();
|
||||
}
|
||||
function memRow(m) {
|
||||
const isOpen = !memPicking && memOpen === m.id;
|
||||
const row = el("div", "row lib-row click lib-mem" + (isOpen ? " open" : ""));
|
||||
@@ -1600,6 +1614,7 @@ magpie.plugin("library", (ctx) => {
|
||||
function memDetail(m) {
|
||||
const d = memDraft;
|
||||
const det = el("div", "lib-detail lib-memdetail");
|
||||
det.dataset.detail = "mem:" + (m ? m.id : "new");
|
||||
const ta = el("textarea", "lib-text small");
|
||||
ta.dataset.lib = "mem:" + (m ? m.id : "new");
|
||||
ta.value = d.text;
|
||||
@@ -1607,7 +1622,9 @@ magpie.plugin("library", (ctx) => {
|
||||
ta.oninput = () => { d.text = ta.value; };
|
||||
ta.onkeydown = (e) => { e.stopPropagation(); if ((e.metaKey || e.ctrlKey) && (e.key === "s" || e.key === "Enter")) { e.preventDefault(); saveMemory(); } };
|
||||
autosize(ta, 52);
|
||||
if (!m) queueMicrotask(() => ta.focus());
|
||||
// a new one's text takes the focus when it opens, not on every render
|
||||
// after (the reader may be in its tags)
|
||||
if (!m) queueMicrotask(() => { if (!det.classList.contains("kept")) ta.focus(); });
|
||||
const pick = (label, value, opts, head, set) => {
|
||||
const b = menuButton(label(value), "lib-mempick", () => openProtoMenu(b, opts.map((v) => ({ v, name: label(v), literalName: true, note: "" })), value, (v) => { set(v); render(); }, head));
|
||||
return b;
|
||||
@@ -2394,6 +2411,7 @@ magpie.plugin("library", (ctx) => {
|
||||
if (!isOpen) return [row];
|
||||
|
||||
const det = el("div", "lib-detail");
|
||||
det.dataset.detail = "set:" + x.id;
|
||||
const nm = input(setName(x), t("Name"));
|
||||
nm.dataset.lib = "setname:" + x.id;
|
||||
nm.className = "lib-setname";
|
||||
@@ -2533,6 +2551,7 @@ magpie.plugin("library", (ctx) => {
|
||||
if (!isOpen) return [row];
|
||||
|
||||
const det = el("div", "lib-detail");
|
||||
det.dataset.detail = "agent:" + a.agent;
|
||||
if (a.override) {
|
||||
const w = el("div", "lib-warn");
|
||||
w.append(el("span", "", t("{agent} reads {file} instead of this file while it has anything in it.", { agent: a.name, file: tilde(a.override) }) + " "), pathLink(a.override));
|
||||
@@ -4640,7 +4659,6 @@ magpie.plugin("library", (ctx) => {
|
||||
if (subs.some((s) => s.agents?.includes("cursor"))) body.append(el("p", "lib-aside lib-subagents-cursor", t("The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents.")));
|
||||
const skip = all.filter((a) => subagentAgentOf(a.id).no);
|
||||
if (skip.length) body.append(el("p", "lib-aside lib-subagents-no", t("magpie can't give subagents to {agents} yet: their chips are greyed, and say why.", { agents: skip.map((a) => a.name).join(", ") })));
|
||||
if (!agentless() && (subs.length || lib.projects.length)) renderProjects(body, "subagents");
|
||||
}
|
||||
|
||||
function subagentRow(s, all) {
|
||||
@@ -4896,10 +4914,7 @@ magpie.plugin("library", (ctx) => {
|
||||
const who = el("div", "who");
|
||||
who.append(el("div", "name mono", p.name + (p.version ? " " + p.version : "")));
|
||||
if (p.description) who.append(el("div", "lib-subagentdesc", p.description));
|
||||
// counts, not every name: PStack has a hundred (jinpwng on X); the
|
||||
// names are in the dialog, folded
|
||||
const line = [[t("Skills"), p.skills], [t("MCP servers"), p.mcp], [t("Hooks"), p.hooks], [t("Subagents"), p.subagents]]
|
||||
.filter(([, v]) => v?.length).map(([k, v]) => k + " " + v.length).join(" · ");
|
||||
const line = pluginParts(p);
|
||||
if (line) who.append(el("div", "sub lib-plparts", line));
|
||||
row.append(glyph(GLYPH.folder), who,
|
||||
agentChips(all, p.agents, chipsChange("plugins/agents", p.name, "plugins", (x) => pluginRow(x, all)), { all: true }),
|
||||
@@ -4917,11 +4932,7 @@ magpie.plugin("library", (ctx) => {
|
||||
ed.append(head);
|
||||
if (p.description) ed.append(el("p", "lib-subagentdesc", p.description));
|
||||
const rows = [[t("Skills"), p.skills], [t("MCP servers"), p.mcp], [t("Hooks"), p.hooks], [t("Subagents"), p.subagents]].filter(([, v]) => v?.length);
|
||||
for (const [label, names] of rows) {
|
||||
const d = el("details", "lib-plgroup");
|
||||
d.append(el("summary", "", label + " " + names.length), el("div", "mono lib-plnames", names.join(", ")));
|
||||
ed.append(d);
|
||||
}
|
||||
for (const [label, names] of rows) ed.append(...field(label, el("div", "mono lib-plnames", names.join(", "))));
|
||||
if (p.missing?.length) ed.append(el("div", "hint lib-plmissing", t("Taken out by hand: {names}", { names: p.missing.join(", ") })));
|
||||
if (p.left?.length) {
|
||||
const left = el("div", "lib-plleft");
|
||||
@@ -6134,14 +6145,12 @@ magpie.plugin("library", (ctx) => {
|
||||
|
||||
function renderProjects(body, kind) {
|
||||
const rh = el("div", "row-head");
|
||||
rh.append(el("span", "label", kind === "skills" ? t("Project skills") : kind === "subagents" ? t("Project subagents") : t("Project servers")), el("span", "grow"));
|
||||
rh.append(el("span", "label", kind === "skills" ? t("Project skills") : t("Project servers")), el("span", "grow"));
|
||||
if (!addingProject) rh.append(button(t("Add a project"), "action lib-updall", () => { addingProject = { dir: "" }; render(); }));
|
||||
body.append(rh);
|
||||
if (addingProject) body.append(addProjectCard(kind));
|
||||
if (!lib.projects.length && !addingProject) {
|
||||
body.append(el("p", "lib-aside", kind === "subagents"
|
||||
? t("Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.")
|
||||
: kind === "mcp"
|
||||
body.append(el("p", "lib-aside", kind === "mcp"
|
||||
? t("Give a project's agents some of these servers as the project's own: magpie writes them into its {files}, leaving the rest of each file as it is.", { files: projectFiles() })
|
||||
: t("Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git.")));
|
||||
return;
|
||||
@@ -6188,7 +6197,7 @@ magpie.plugin("library", (ctx) => {
|
||||
addingProject = null;
|
||||
const p = lib.projects.find((x) => !was.has(x.dir));
|
||||
if (p) openProjects.add(p.dir);
|
||||
status(kind === "subagents" ? t("{name} added — pick the subagents it gets", { name: p?.name || dir }) : kind === "mcp" ? t("{name} added — pick the servers it gets", { name: p?.name || dir }) : t("{name} added — pick the skills it gets", { name: p?.name || dir }), "ok");
|
||||
status(kind === "mcp" ? t("{name} added — pick the servers it gets", { name: p?.name || dir }) : t("{name} added — pick the skills it gets", { name: p?.name || dir }), "ok");
|
||||
} catch (e) {
|
||||
a.busy = false;
|
||||
a.error = e.message;
|
||||
@@ -6199,24 +6208,24 @@ magpie.plugin("library", (ctx) => {
|
||||
}
|
||||
|
||||
function projectCard(p, kind) {
|
||||
const mcp = kind === "mcp", sub = kind === "subagents";
|
||||
const mcp = kind === "mcp";
|
||||
const card = el("div", "list lib-card lib-project" + (p.missing ? " missing" : ""));
|
||||
const isOpen = openProjects.has(p.dir);
|
||||
const head = el("div", "row lib-row click lib-projhead" + (isOpen ? " open" : ""));
|
||||
const who = el("div", "who");
|
||||
const nm = el("div", "name", p.name);
|
||||
if (p.missing) nm.append(tag(t("Folder is gone"), "warn"));
|
||||
else if (p.copy && !mcp && !sub) nm.append(tag(t("Copies"), ""));
|
||||
else if (p.copy && !mcp) nm.append(tag(t("Copies"), ""));
|
||||
who.append(nm);
|
||||
const src = el("div", "lib-src");
|
||||
src.append(pathLink(p.dir));
|
||||
who.append(src);
|
||||
const names = Object.keys((sub ? p.subagents : mcp ? p.servers : p.skills) || {}).sort();
|
||||
const names = Object.keys((mcp ? p.servers : p.skills) || {}).sort();
|
||||
const pills = el("div", "lib-tags");
|
||||
if (!isOpen) {
|
||||
for (const n of names.slice(0, 4)) pills.append(tag(n, "lib-dot"));
|
||||
if (names.length > 4) pills.append(tag("+" + (names.length - 4), ""));
|
||||
if (!names.length) pills.append(tag(sub ? t("No subagents yet") : mcp ? t("No servers yet") : t("No skills yet"), "lib-unchecked"));
|
||||
if (!names.length) pills.append(tag(mcp ? t("No servers yet") : t("No skills yet"), "lib-unchecked"));
|
||||
}
|
||||
const acts = el("div", "lib-rowacts");
|
||||
const rm = button("", "lib-icon danger", () => confirmRemoveProject(p));
|
||||
@@ -6227,12 +6236,11 @@ magpie.plugin("library", (ctx) => {
|
||||
chev.append(svg(CHEV_R, 11, 1.7));
|
||||
head.append(glyph(GLYPH.folder), who, pills, acts, chev);
|
||||
head.onclick = () => { isOpen ? openProjects.delete(p.dir) : openProjects.add(p.dir); projectShown.delete(p.dir); render(); };
|
||||
head.title = sub ? (isOpen ? t("Hide its subagents") : t("Pick the subagents it gets")) : mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets");
|
||||
head.title = mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets");
|
||||
card.append(head);
|
||||
if (p.problems?.[""]) card.append(el("div", "lib-err", p.problems[""]));
|
||||
if (!isOpen) return card;
|
||||
if (mcp) return projectServers(p, card);
|
||||
if (sub) return projectSubagents(p, card);
|
||||
|
||||
const opts = el("div", "lib-projopts");
|
||||
const copy = toggle(p.copy, t("Copy files instead of linking"), (on) =>
|
||||
@@ -6432,32 +6440,6 @@ magpie.plugin("library", (ctx) => {
|
||||
return card;
|
||||
}
|
||||
|
||||
// The project's card, open on the Subagents tab: each library subagent
|
||||
// with the chips of the agents that read a project's own subagent folder.
|
||||
function projectSubagents(p, card) {
|
||||
const all = shownAgents().filter((a) => a.projectSubagents);
|
||||
for (const s of lib.subagents || []) {
|
||||
const row = el("div", "row lib-row lib-projskill lib-projsubagent");
|
||||
const w = el("div", "who");
|
||||
const n = el("div", "name mono", s.name);
|
||||
const problem = p.problems?.["subagent:" + s.name];
|
||||
if (problem) n.append(tag(t("Not written"), "warn", problem));
|
||||
w.append(n);
|
||||
const sub = el("div", "sub", problem || s.description || "");
|
||||
sub.title = problem || s.description || "";
|
||||
w.append(sub);
|
||||
const on = (p.subagents?.[s.name] || []).filter((id) => all.some((a) => a.id === id));
|
||||
const say = (next) => next.length
|
||||
? t("{item} is in {name} for {agents}", { item: s.name, name: p.name, agents: next.map(nameOf).join(", ") })
|
||||
: t("{item} is out of {name}", { item: s.name, name: p.name });
|
||||
row.append(glyph(GLYPH.subagent), w, agentChips(all, on, projectChange("projects/subagents", p.dir, s.name, say)));
|
||||
card.append(row);
|
||||
}
|
||||
if (!(lib.subagents || []).length) card.append(el("p", "lib-aside lib-projfoot", t("No subagents in the library yet")));
|
||||
card.append(el("p", "lib-aside lib-projfoot", t("Written into the project's own agents folder, one file per subagent; a file magpie makes is kept out of git, its .gitignore untouched. A file there by the same name that isn't magpie's is left as it is.")));
|
||||
return card;
|
||||
}
|
||||
|
||||
function confirmRemoveProject(p) {
|
||||
const ed = el("div", "editor lib-editor");
|
||||
const head = el("div", "ehead");
|
||||
|
||||
@@ -717,15 +717,6 @@ magpie.strings({
|
||||
"{agents} has no skills folder.": "{agents} 没有技能文件夹。",
|
||||
"Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop 刷新窗口({keys})后才显示技能变化。它使用技能的副本,在 Desktop 中改过的副本不会被覆盖。",
|
||||
"Project servers": "项目服务器",
|
||||
"Project subagents": "项目子代理",
|
||||
"Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "把这些子代理作为项目自己的给项目里的 Agent:magpie 写进它的 .claude/agents 等文件夹,并让它们不进 git。",
|
||||
"{name} added — pick the subagents it gets": "已添加 {name},选择它要用的子代理",
|
||||
"No subagents yet": "还没有子代理",
|
||||
"Hide its subagents": "收起子代理",
|
||||
"Pick the subagents it gets": "选择它要用的子代理",
|
||||
"Written into the project's own agents folder, one file per subagent; a file magpie makes is kept out of git, its .gitignore untouched. A file there by the same name that isn't magpie's is left as it is.": "每个子代理一个文件,写进项目自己的 agents 文件夹;magpie 创建的文件不进 git,.gitignore 不动。里面同名但不是 magpie 写的文件保持原样。",
|
||||
"{item} is in {name} for {agents}": "{item} 已在 {name} 中对 {agents} 开启",
|
||||
"{item} is out of {name}": "{item} 已从 {name} 中移除",
|
||||
"Project skills": "项目技能",
|
||||
"Add a project": "添加项目",
|
||||
"Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git.": "将部分技能作为项目技能提供给项目中的 Agent:链接到项目的 .claude/skills 和 .agents/skills,并让 git 忽略。",
|
||||
@@ -1727,15 +1718,6 @@ magpie.strings({
|
||||
"{agents} has no skills folder.": "{agents} 沒有技能資料夾。",
|
||||
"Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop 重新整理視窗({keys})後才顯示技能變化。它使用技能的副本,在 Desktop 中改過的副本不會被覆蓋。",
|
||||
"Project servers": "專案伺服器",
|
||||
"Project subagents": "專案子代理",
|
||||
"Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "把這些子代理作為專案自己的給專案裡的 Agent:magpie 寫進它的 .claude/agents 等資料夾,並讓它們不進 git。",
|
||||
"{name} added — pick the subagents it gets": "已新增 {name},選擇它要用的子代理",
|
||||
"No subagents yet": "還沒有子代理",
|
||||
"Hide its subagents": "收起子代理",
|
||||
"Pick the subagents it gets": "選擇它要用的子代理",
|
||||
"Written into the project's own agents folder, one file per subagent; a file magpie makes is kept out of git, its .gitignore untouched. A file there by the same name that isn't magpie's is left as it is.": "每個子代理一個檔案,寫進專案自己的 agents 資料夾;magpie 建立的檔案不進 git,.gitignore 不動。裡面同名但不是 magpie 寫的檔案保持原樣。",
|
||||
"{item} is in {name} for {agents}": "{item} 已在 {name} 中對 {agents} 開啟",
|
||||
"{item} is out of {name}": "{item} 已從 {name} 中移除",
|
||||
"Project skills": "專案技能",
|
||||
"Add a project": "新增專案",
|
||||
"Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git.": "將部分技能作為專案技能提供給專案中的 Agent:連結到專案的 .claude/skills 和 .agents/skills,並讓 git 忽略。",
|
||||
@@ -2728,15 +2710,6 @@ magpie.strings({
|
||||
"{agents} has no skills folder.": "{agents} にはスキルフォルダがありません。",
|
||||
"Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop はウィンドウを再読み込み({keys})するとスキルの変更を表示します。各スキルのコピーを受け取り、Desktop で変更したものはそのまま残ります。",
|
||||
"Project servers": "プロジェクトのサーバー",
|
||||
"Project subagents": "プロジェクトのサブエージェント",
|
||||
"Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "これらのサブエージェントをプロジェクト専用として渡します。magpie が .claude/agents などに書き込み、git には入れません。",
|
||||
"{name} added — pick the subagents it gets": "{name} を追加しました。渡すサブエージェントを選んでください",
|
||||
"No subagents yet": "サブエージェントはまだありません",
|
||||
"Hide its subagents": "サブエージェントを隠す",
|
||||
"Pick the subagents it gets": "渡すサブエージェントを選ぶ",
|
||||
"Written into the project's own agents folder, one file per subagent; a file magpie makes is kept out of git, its .gitignore untouched. A file there by the same name that isn't magpie's is left as it is.": "サブエージェントごとに1ファイルをプロジェクトの agents フォルダに書きます。magpie が作ったファイルは git に入れず、.gitignore は触りません。同名で magpie のものではないファイルはそのままです。",
|
||||
"{item} is in {name} for {agents}": "{item} は {name} で {agents} に対してオンです",
|
||||
"{item} is out of {name}": "{item} は {name} から外れました",
|
||||
"Project skills": "プロジェクトのスキル",
|
||||
"Add a project": "プロジェクトを追加",
|
||||
"Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git.": "プロジェクトのエージェントに、これらのスキルの一部をプロジェクト固有のものとして渡します:magpie はそれらを .claude/skills と .agents/skills にリンクし、git の対象外にします。",
|
||||
@@ -3734,15 +3707,6 @@ magpie.strings({
|
||||
"{agents} has no skills folder.": "{agents} hat keinen Skills-Ordner.",
|
||||
"Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop zeigt Skill-Änderungen erst nach dem Neuladen des Fensters ({keys}). Es erhält von jedem Skill eine Kopie, und eine in Desktop geänderte bleibt unverändert.",
|
||||
"Project servers": "Projektserver",
|
||||
"Project subagents": "Projekt-Subagenten",
|
||||
"Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "Gib den Agenten eines Projekts einige dieser Subagenten als eigene: magpie schreibt sie in dessen .claude/agents und Ähnliches und hält sie aus git heraus.",
|
||||
"{name} added — pick the subagents it gets": "{name} hinzugefügt – wähle die Subagenten dafür",
|
||||
"No subagents yet": "Noch keine Subagenten",
|
||||
"Hide its subagents": "Subagenten ausblenden",
|
||||
"Pick the subagents it gets": "Subagenten wählen",
|
||||
"Written into the project's own agents folder, one file per subagent; a file magpie makes is kept out of git, its .gitignore untouched. A file there by the same name that isn't magpie's is left as it is.": "Eine Datei pro Subagent im agents-Ordner des Projekts; was magpie anlegt, bleibt aus git heraus, die .gitignore bleibt unberührt. Eine gleichnamige Datei, die nicht von magpie stammt, bleibt wie sie ist.",
|
||||
"{item} is in {name} for {agents}": "{item} ist in {name} für {agents} an",
|
||||
"{item} is out of {name}": "{item} ist aus {name} entfernt",
|
||||
"Project skills": "Projekt-Skills",
|
||||
"Add a project": "Projekt hinzufügen",
|
||||
"Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git.": "Geben Sie den Agenten eines Projekts einige dieser Skills als projekteigene: magpie verlinkt sie in dessen .claude/skills und .agents/skills und hält sie aus git heraus.",
|
||||
|
||||
@@ -282,6 +282,8 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col
|
||||
|
||||
/* an agent's instructions, opened */
|
||||
.lib-detail { padding: 4px 14px 14px 50px; background: var(--card-2); display: flex; flex-direction: column; gap: 8px; border-top: 0 !important; animation: content-in .2s var(--ease); }
|
||||
/* open before the render that drew it again: no second entrance */
|
||||
.lib-detail.kept { animation: none; }
|
||||
.lib-lab { font-size: 11.5px; color: var(--muted); }
|
||||
.lib-detail .lib-aside { margin: 0; }
|
||||
.lib-acts { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
@@ -796,10 +798,6 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col
|
||||
.lib-plugin > .who { flex-basis: 240px; }
|
||||
.lib-plugin.off .name, .lib-plugin.off .lib-subagentdesc { opacity: .55; }
|
||||
.lib-plugin .lib-plparts, .lib-plpick .lib-plparts { white-space: normal; overflow-wrap: anywhere; }
|
||||
.lib-pldetail > :is(p, details, .hint), .lib-pldetail .ebody > :is(p, details, .hint) { grid-column: 1 / -1; margin: 0; }
|
||||
.lib-pldetail p { font-size: 12.5px; line-height: 1.5; }
|
||||
.lib-pldetail .lib-plgroup > summary { cursor: pointer; font-size: 12.5px; color: var(--fg-2); }
|
||||
.lib-pldetail .lib-plgroup .lib-plnames { margin-top: 4px; font-size: 12px; }
|
||||
.lib-pldetail .lib-plnames, .lib-pldetail .lib-plsource { white-space: normal; overflow-wrap: anywhere; }
|
||||
.lib-subagentedit .lib-menu { max-width: 100%; height: 28px; color: var(--fg); }
|
||||
.lib-subagentedit .lib-menu > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@@ -11,8 +11,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// An import link (magpie://import?… or ccswitch://v1/import?…, see
|
||||
// provider.ParseImport) is parsed
|
||||
// An import link (magpie://import?…, see provider.ParseImport) is parsed
|
||||
// here, parked under a random id, and the window opens on the Providers tab
|
||||
// with that id; the page fetches it once and asks the user before saving
|
||||
// anything.
|
||||
@@ -45,11 +44,10 @@ func stashImport(link string) string {
|
||||
return id
|
||||
}
|
||||
|
||||
// ImportLink is the link among a launch's arguments, if any: a magpie:// one,
|
||||
// or a ccswitch:// one, which relays put on their pages for CC Switch.
|
||||
// ImportLink is the link among a launch's arguments, if any.
|
||||
func ImportLink(args []string) string {
|
||||
for _, a := range args {
|
||||
if l := strings.ToLower(a); strings.HasPrefix(l, provider.Scheme+":") || strings.HasPrefix(l, provider.CCSwitchScheme+":") {
|
||||
if strings.HasPrefix(strings.ToLower(a), provider.Scheme+":") {
|
||||
return a
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,11 +31,6 @@ func TestImportIsReadOnce(t *testing.T) {
|
||||
if rec, _ := get(id); rec.Code != 404 {
|
||||
t.Fatalf("second read: %d", rec.Code)
|
||||
}
|
||||
// a relay's CC Switch link opens the same confirmation
|
||||
id = stashImport("ccswitch://v1/import?resource=provider&app=claude&name=My%20Relay&endpoint=https%3A%2F%2Frelay.example&apiKey=sk-r")
|
||||
if rec, in := get(id); rec.Code != 200 || in.Error != "" || in.Provider.ID != "my-relay" || in.Provider.Anthropic != "https://relay.example" || in.Provider.Key != "sk-r" {
|
||||
t.Fatalf("%d %+v", rec.Code, in)
|
||||
}
|
||||
if _, in := get(stashImport("magpie://import?name=x")); in.Error == "" {
|
||||
t.Fatal("a bad link reported no error")
|
||||
}
|
||||
@@ -73,7 +68,4 @@ func TestImportLink(t *testing.T) {
|
||||
if ImportLink([]string{"MAGPIE://import?preset=x"}) == "" {
|
||||
t.Fatal("missed an upper-case link")
|
||||
}
|
||||
if ImportLink([]string{"ccswitch://v1/import?resource=provider&app=claude&name=x"}) == "" {
|
||||
t.Fatal("missed a CC Switch link")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -852,8 +852,6 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
|
||||
res, err = library.ProjectSkill(in.Dir, in.Name, in.Agents)
|
||||
case "projects/skills":
|
||||
res, err = library.ProjectSkills(in.Dir, in.Names, in.Agents)
|
||||
case "projects/subagents":
|
||||
res, err = library.ProjectSubagents(in.Dir, oneOrMore(in.Name, in.Names), in.Agents)
|
||||
case "projects/server":
|
||||
res, err = library.ProjectServer(in.Dir, in.Name, in.Agents)
|
||||
case "projects/server-off":
|
||||
|
||||
@@ -61,7 +61,7 @@ Terminal=false
|
||||
`
|
||||
if old, err := os.ReadFile(path); err == nil && strings.Contains(string(old), "Exec="+exe+" %u") && strings.Contains(string(old), "x-scheme-handler/magpie") &&
|
||||
strings.Contains(string(old), "\nStartupWMClass="+programName+"\n") {
|
||||
return errors.Join(iconErr, registerCCSwitch(dir, exe))
|
||||
return iconErr
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
@@ -70,44 +70,7 @@ Terminal=false
|
||||
return err
|
||||
}
|
||||
_ = proc.Command("update-desktop-database", dir).Run()
|
||||
return errors.Join(iconErr, proc.Command("xdg-mime", "default", "magpie.desktop", "x-scheme-handler/magpie").Run(), registerCCSwitch(dir, exe))
|
||||
}
|
||||
|
||||
// ccSwitchEntry is the desktop entry that claims ccswitch:// links, apart
|
||||
// from magpie's own so that it can be left out.
|
||||
const ccSwitchEntry = "magpie-ccswitch.desktop"
|
||||
|
||||
// registerCCSwitch lets magpie open ccswitch:// links, the one-click import
|
||||
// links relays make for CC Switch, but only when no other app has them: CC
|
||||
// Switch installed here keeps its links. The desktop's default for the
|
||||
// scheme is asked first; it is set to this entry only when empty or already
|
||||
// this entry. No icon or window class of its own: it is never shown.
|
||||
func registerCCSwitch(dir, exe string) error {
|
||||
const mime = "x-scheme-handler/ccswitch"
|
||||
out, _ := proc.Command("xdg-mime", "query", "default", mime).Output()
|
||||
if def := strings.TrimSpace(string(out)); def != "" && def != ccSwitchEntry {
|
||||
return nil
|
||||
}
|
||||
path := filepath.Join(dir, ccSwitchEntry)
|
||||
entry := `[Desktop Entry]
|
||||
Type=Application
|
||||
Name=magpie (ccswitch:// links)
|
||||
Exec=` + exe + ` %u
|
||||
NoDisplay=true
|
||||
MimeType=` + mime + `;
|
||||
Terminal=false
|
||||
`
|
||||
if old, err := os.ReadFile(path); err == nil && string(old) == entry && strings.TrimSpace(string(out)) == ccSwitchEntry {
|
||||
return nil
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(entry), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = proc.Command("update-desktop-database", dir).Run()
|
||||
return proc.Command("xdg-mime", "default", ccSwitchEntry, mime).Run()
|
||||
return errors.Join(iconErr, proc.Command("xdg-mime", "default", "magpie.desktop", "x-scheme-handler/magpie").Run())
|
||||
}
|
||||
|
||||
// installIcon puts magpie's icon where the entry's Icon=magpie is looked
|
||||
|
||||
@@ -11,28 +11,6 @@ import (
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// fakeDesktopTools puts update-desktop-database and an xdg-mime that
|
||||
// remembers the defaults it is given and answers `query default` with them,
|
||||
// each call logged to calls (names only, or with arguments).
|
||||
func fakeDesktopTools(t *testing.T, bin, calls string, args bool) {
|
||||
t.Helper()
|
||||
t.Setenv("MAGPIE_SCHEME_TEST_CALLS", calls)
|
||||
t.Setenv("PATH", bin)
|
||||
for _, name := range []string{"update-desktop-database", "xdg-mime"} {
|
||||
log := `printf '%s\n' '` + name + `'`
|
||||
if args {
|
||||
log = `printf '%s\n' '` + name + `' "$@"`
|
||||
}
|
||||
script := "#!/bin/sh\n" + log + ` >> "$MAGPIE_SCHEME_TEST_CALLS"` + "\n"
|
||||
if name == "xdg-mime" {
|
||||
script += `f="$MAGPIE_SCHEME_TEST_CALLS.${3##*/}"` + "\n" + // PATH holds only these two, so shell builtins
|
||||
`[ "$1" = query ] && { [ -f "$f" ] && read -r v < "$f" && echo "$v"; exit 0; }` + "\n" +
|
||||
`[ "$1" = default ] && echo "$2" > "$f"` + "\n"
|
||||
}
|
||||
testenv.Program(t, filepath.Join(bin, name), script)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterScheme(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
@@ -57,7 +35,12 @@ func TestRegisterScheme(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := filepath.Join(root, "calls")
|
||||
fakeDesktopTools(t, bin, calls, true)
|
||||
t.Setenv("MAGPIE_SCHEME_TEST_CALLS", calls)
|
||||
t.Setenv("PATH", bin)
|
||||
for _, name := range []string{"update-desktop-database", "xdg-mime"} {
|
||||
script := "#!/bin/sh\nprintf '%s\\n' '" + name + "' \"$@\" >> \"$MAGPIE_SCHEME_TEST_CALLS\"\n"
|
||||
testenv.Program(t, filepath.Join(bin, name), script)
|
||||
}
|
||||
dir := filepath.Join(data, "applications")
|
||||
path := filepath.Join(dir, "magpie.desktop")
|
||||
const old = "[Desktop Entry]\nExec=/usr/bin/magpie %u\nMimeType=x-scheme-handler/magpie;\n"
|
||||
@@ -101,13 +84,7 @@ func TestRegisterScheme(t *testing.T) {
|
||||
if err := registerScheme(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// ccswitch:// links are claimed too, asked first, and on the second
|
||||
// run only asked
|
||||
udd := "update-desktop-database\n" + dir + "\n"
|
||||
want := udd + "xdg-mime\ndefault\nmagpie.desktop\nx-scheme-handler/magpie\n" +
|
||||
"xdg-mime\nquery\ndefault\nx-scheme-handler/ccswitch\n" +
|
||||
udd + "xdg-mime\ndefault\nmagpie-ccswitch.desktop\nx-scheme-handler/ccswitch\n" +
|
||||
"xdg-mime\nquery\ndefault\nx-scheme-handler/ccswitch\n"
|
||||
want := "update-desktop-database\n" + dir + "\nxdg-mime\ndefault\nmagpie.desktop\nx-scheme-handler/magpie\n"
|
||||
if got, err := os.ReadFile(calls); err != nil || string(got) != want {
|
||||
t.Fatalf("registration calls: %q, want %q (%v)", got, want, err)
|
||||
}
|
||||
@@ -143,7 +120,11 @@ func TestRegisterSchemeBindsAnOlderEntry(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := filepath.Join(root, "calls")
|
||||
fakeDesktopTools(t, bin, calls, false)
|
||||
t.Setenv("MAGPIE_SCHEME_TEST_CALLS", calls)
|
||||
t.Setenv("PATH", bin)
|
||||
for _, name := range []string{"update-desktop-database", "xdg-mime"} {
|
||||
testenv.Program(t, filepath.Join(bin, name), "#!/bin/sh\nprintf '%s\\n' '"+name+"' >> \"$MAGPIE_SCHEME_TEST_CALLS\"\n")
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -168,7 +149,7 @@ func TestRegisterSchemeBindsAnOlderEntry(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checkDesktopBinding(t, data, string(got))
|
||||
if c, err := os.ReadFile(calls); err != nil || string(c) != "update-desktop-database\nxdg-mime\nxdg-mime\nupdate-desktop-database\nxdg-mime\nxdg-mime\n" {
|
||||
if c, err := os.ReadFile(calls); err != nil || string(c) != "update-desktop-database\nxdg-mime\n" {
|
||||
t.Fatalf("registered %q, want once (%v)", c, err)
|
||||
}
|
||||
}
|
||||
@@ -221,34 +202,3 @@ func TestKeepWebData(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// CC Switch installed here keeps ccswitch:// links: magpie leaves the
|
||||
// desktop's default for the scheme alone, and writes no entry for it.
|
||||
func TestRegisterSchemeLeavesCCSwitchItsLinks(t *testing.T) {
|
||||
t.Setenv("FLATPAK_ID", "")
|
||||
root := t.TempDir()
|
||||
data := filepath.Join(root, "data")
|
||||
t.Setenv("XDG_DATA_HOME", data)
|
||||
bin := filepath.Join(root, "bin")
|
||||
if err := os.Mkdir(bin, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := filepath.Join(root, "calls")
|
||||
fakeDesktopTools(t, bin, calls, true)
|
||||
if err := os.WriteFile(calls+".ccswitch", []byte("cc-switch.desktop\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := registerScheme(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(data, "applications", ccSwitchEntry)); !os.IsNotExist(err) {
|
||||
t.Fatalf("an entry for ccswitch:// was written: %v", err)
|
||||
}
|
||||
if c, _ := os.ReadFile(calls); strings.Contains(string(c), "default\nmagpie-ccswitch.desktop") {
|
||||
t.Fatalf("took the default from CC Switch: %q", c)
|
||||
}
|
||||
// magpie's own scheme is still registered
|
||||
if _, err := os.Stat(filepath.Join(data, "applications", "magpie.desktop")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
package gui
|
||||
|
||||
// registerScheme: the Mac reads the schemes (magpie, ccswitch) from the bundle's Info.plist.
|
||||
// registerScheme: the Mac reads the scheme from the bundle's Info.plist.
|
||||
func registerScheme() error { return nil }
|
||||
|
||||
// keepWebData: the Mac's webview keeps its data by the bundle id.
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
@@ -16,43 +13,12 @@ func registerScheme() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.Join(setScheme("magpie", exe), registerCCSwitch(exe))
|
||||
}
|
||||
|
||||
// registerCCSwitch lets magpie open ccswitch:// links, the one-click import
|
||||
// links relays make for CC Switch, but only while no other program has
|
||||
// them: CC Switch installed here, per user or for the machine, keeps its
|
||||
// links. The merged view (HKEY_CLASSES_ROOT) is asked, so both count; a
|
||||
// handler whose program is gone is replaced.
|
||||
func registerCCSwitch(exe string) error {
|
||||
if run := schemeCommand(registry.CLASSES_ROOT, "ccswitch"); run != "" && !strings.EqualFold(filepath.Clean(run), filepath.Clean(exe)) {
|
||||
if _, err := os.Stat(run); err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return setScheme("ccswitch", exe)
|
||||
}
|
||||
|
||||
// schemeCommand is the program a scheme's open command runs, "" when none.
|
||||
func schemeCommand(root registry.Key, scheme string) string {
|
||||
k, err := registry.OpenKey(root, scheme+`\shell\open\command`, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer k.Close()
|
||||
v, _, _ := k.GetStringValue("")
|
||||
run, _, _ := strings.Cut(strings.TrimPrefix(v, `"`), `"`)
|
||||
return run
|
||||
}
|
||||
|
||||
// setScheme points the per-user handler of scheme at exe.
|
||||
func setScheme(scheme, exe string) error {
|
||||
k, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Classes\`+scheme, registry.SET_VALUE)
|
||||
k, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Classes\magpie`, registry.SET_VALUE)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer k.Close()
|
||||
_ = k.SetStringValue("", "URL:"+scheme)
|
||||
_ = k.SetStringValue("", "URL:magpie")
|
||||
_ = k.SetStringValue("URL Protocol", "")
|
||||
icon, _, err := registry.CreateKey(k, `DefaultIcon`, registry.SET_VALUE)
|
||||
if err == nil {
|
||||
|
||||
@@ -67,11 +67,11 @@ function serve(lang, posts) {
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { currency: "Currency", yuan40: "≈¥40.00 left", usd100: "≈$100.00 left", k1: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", yuan: "≈¥100.00 left", bad: "A balance is an amount from -1,000,000 to 1,000,000, in USD or in yuan (¥)", month: "Refills each month…", week: "Refills each week…", day: "Refills each day", never: "Never refills", on: "Refills on", refills: "Refills to $40.00 on" },
|
||||
zh: { currency: "货币", yuan40: "≈¥40.00 剩余", usd100: "≈$100.00 剩余", k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 -1,000,000 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", day: "每日恢复", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" },
|
||||
"zh-TW": { currency: "貨幣", yuan40: "≈¥40.00 剩餘", usd100: "≈$100.00 剩餘", k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 -1,000,000 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", day: "每日恢復", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" },
|
||||
ja: { currency: "通貨", yuan40: "残り ≈¥40.00", usd100: "残り ≈$100.00", k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は -1,000,000 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", day: "毎日戻す", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" },
|
||||
de: { currency: "Währung", yuan40: "≈¥40.00 übrig", usd100: "≈$100.00 übrig", k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", yuan: "≈¥100.00 übrig", bad: "Ein Guthaben ist ein Betrag von -1.000.000 bis 1.000.000, in USD oder in Yuan (¥)", month: "Monatlich auffüllen…", week: "Wöchentlich auffüllen…", day: "Täglich auffüllen", never: "Nie auffüllen", on: "Auffüllen am", refills: "wieder auf $40.00 aufgefüllt" },
|
||||
en: { currency: "Currency", yuan40: "≈¥40.00 left", usd100: "≈$100.00 left", k1: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", yuan: "≈¥100.00 left", bad: "A balance is an amount from -1,000,000 to 1,000,000, in USD or in yuan (¥)", month: "Refills each month…", week: "Refills each week…", never: "Never refills", on: "Refills on", refills: "Refills to $40.00 on" },
|
||||
zh: { currency: "货币", yuan40: "≈¥40.00 剩余", usd100: "≈$100.00 剩余", k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 -1,000,000 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" },
|
||||
"zh-TW": { currency: "貨幣", yuan40: "≈¥40.00 剩餘", usd100: "≈$100.00 剩餘", k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 -1,000,000 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" },
|
||||
ja: { currency: "通貨", yuan40: "残り ≈¥40.00", usd100: "残り ≈$100.00", k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は -1,000,000 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" },
|
||||
de: { currency: "Währung", yuan40: "≈¥40.00 übrig", usd100: "≈$100.00 übrig", k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", yuan: "≈¥100.00 übrig", bad: "Ein Guthaben ist ein Betrag von -1.000.000 bis 1.000.000, in USD oder in Yuan (¥)", month: "Monatlich auffüllen…", week: "Wöchentlich auffüllen…", never: "Nie auffüllen", on: "Auffüllen am", refills: "wieder auf $40.00 aufgefüllt" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
@@ -196,7 +196,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.deepEqual(p.body, { id: "relay", account: "k1", balance: 40 });
|
||||
await page.waitForTimeout(250);
|
||||
|
||||
// k1 refills on a day of each month, then each Friday, then each day, then never
|
||||
// k1 refills on a day of each month, then each Friday, then never
|
||||
await still("k1");
|
||||
await menu.waitFor();
|
||||
await item(w.month).click();
|
||||
@@ -233,21 +233,6 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
p = await posted(n);
|
||||
assert.deepEqual(p.body, { id: "relay", account: "k1", refill: { every: "week", day: 5 } });
|
||||
await page.waitForTimeout(250);
|
||||
// each day (Kelen_Yc on X): picked at once, no day to choose, and
|
||||
// the menu shows it picked
|
||||
await still("k1");
|
||||
await menu.waitFor();
|
||||
n = posts.length;
|
||||
await item(w.day).click();
|
||||
p = await posted(n);
|
||||
assert.deepEqual(p.body, { id: "relay", account: "k1", refill: { every: "day", day: 0 } });
|
||||
await page.waitForTimeout(250);
|
||||
assert.equal(await page.locator(".proto-menu").count(), 0, "a daily refill asked for more");
|
||||
await still("k1");
|
||||
await menu.waitFor();
|
||||
assert.equal(await item(w.day).getAttribute("aria-checked"), "true");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.waitForTimeout(200);
|
||||
await still("k1");
|
||||
await menu.waitFor();
|
||||
n = posts.length;
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// An open memory's editor holds still while the Memory tab's polls run
|
||||
// (Nietzsche_Li on X: "资源库-记忆中,被展开的记忆的表单会定时抖动"). Search by
|
||||
// meaning still reading the memories, or a run learning from conversations,
|
||||
// is read again every 2s; each read drew the whole page again, and the
|
||||
// editor faded and slid in anew every time. Now a read that changes nothing
|
||||
// draws nothing, one that does redraws its own row only, and a render of an
|
||||
// editor that was open already doesn't replay its entrance. The editor's
|
||||
// element, its text and caret, and the focus stay. Every language, wide and
|
||||
// narrow, Chromium and WebKit; no backend, the API is faked here.
|
||||
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(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets"));
|
||||
const HOME = "/Users/mem";
|
||||
const library = {
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [{ id: "codex", name: "Codex", icon: "", instructions: `${HOME}/.codex/AGENTS.md` }],
|
||||
instructions: { shared: "", sets: [{ id: "default", name: "", active: true, text: "" }], agents: [] },
|
||||
foundServers: [], projects: [], foundSkills: [], skills: [], servers: [],
|
||||
};
|
||||
const at = (d) => `2026-11-0${d}T10:00:00Z`;
|
||||
const memories = () => ({
|
||||
memories: [
|
||||
{ id: "a1", text: "Use pnpm, never npm, in this repo", why: "", kind: "rule", scope: "global", origin: "user", status: "active", created: at(1), updated: at(2) },
|
||||
{ id: "a2", text: "Never push to main", kind: "rule", scope: "global", origin: "user", status: "active", created: at(1), updated: at(1) },
|
||||
],
|
||||
projects: {}, digest: true, agents: [],
|
||||
});
|
||||
|
||||
function server(lang, st) {
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().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: library });
|
||||
if (url.pathname === "/api/memory/semantic") { st.semReads++; return route.fulfill({ json: st.sem }); }
|
||||
if (url.pathname === "/api/memory/distill") { st.distReads++; return route.fulfill({ json: st.dist }); }
|
||||
if (url.pathname.startsWith("/api/memory")) return route.fulfill({ json: st.mem });
|
||||
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 });
|
||||
};
|
||||
}
|
||||
|
||||
const view = "#view-library";
|
||||
const langs = ["en", "zh", "zh-TW", "ja", "de"];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": an open memory holds still while the Memory tab polls", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
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 langs) for (const width of [980, 420]) {
|
||||
await t.test(`${lang} ${width}`, async () => {
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 860 } });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "memory"); } catch {} });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(8000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
// search by meaning on, one memory of two read, nothing reading it
|
||||
// now (magpie reads new ones once a minute), and a run learning
|
||||
// from conversations under way: both polled every 2s
|
||||
const st = {
|
||||
mem: memories(),
|
||||
sem: { on: true, installed: true, size: 1, done: 1, downloading: false, read: 1, of: 2, reading: false },
|
||||
dist: { on: true, model: "", auto: "", running: true, models: [] },
|
||||
semReads: 0, distReads: 0,
|
||||
};
|
||||
await page.route("**/*", server(lang, st));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
const row = page.locator(`${view} .lib-mems .lib-mem[data-id="a1"]`);
|
||||
await row.waitFor();
|
||||
await row.evaluate((e) => e.click()); // at 420px the header can sit over it while the page settles
|
||||
const ta = page.locator(`${view} .lib-memdetail textarea`);
|
||||
await ta.waitFor();
|
||||
// typed into, the caret in the middle
|
||||
await ta.focus();
|
||||
await ta.evaluate((e) => e.setSelectionRange(e.value.length, e.value.length));
|
||||
await page.keyboard.type(" here");
|
||||
await ta.evaluate((e) => e.setSelectionRange(4, 4));
|
||||
await page.evaluate(async () => {
|
||||
const det = document.querySelector("#view-library .lib-memdetail");
|
||||
// its own entrance played out first
|
||||
await Promise.all(det.getAnimations().map((a) => a.finished));
|
||||
det.__first = true;
|
||||
window.__entrances = 0;
|
||||
window.__shifts = [];
|
||||
document.addEventListener("animationstart", (e) => { if (e.target.closest?.(".lib-detail")) window.__entrances++; }, true);
|
||||
// where the editor sits, each frame
|
||||
let top0 = det.getBoundingClientRect().top;
|
||||
// what is new above it moves it, once: measured from there
|
||||
window.__rebase = () => { top0 = document.querySelector("#view-library .lib-memdetail").getBoundingClientRect().top; window.__shifts = []; };
|
||||
const look = () => {
|
||||
const d = document.querySelector("#view-library .lib-memdetail");
|
||||
if (!d) return;
|
||||
const r = d.getBoundingClientRect(), o = parseFloat(getComputedStyle(d).opacity);
|
||||
if (Math.abs(r.top - top0) > 0.5 || o < 1) window.__shifts.push([r.top - top0, o]);
|
||||
requestAnimationFrame(look);
|
||||
};
|
||||
requestAnimationFrame(look);
|
||||
});
|
||||
const steady = async (what, moved) => {
|
||||
const s = await page.evaluate(() => {
|
||||
const det = document.querySelector("#view-library .lib-memdetail");
|
||||
const ta = det?.querySelector("textarea");
|
||||
return { same: !!det?.__first, entrances: window.__entrances, shifts: window.__shifts.length, first: window.__shifts[0], focused: document.activeElement === ta, text: ta?.value, caret: ta?.selectionStart };
|
||||
});
|
||||
assert.equal(s.entrances, 0, `${what}: the editor played its entrance again`);
|
||||
if (!moved) assert.equal(s.shifts, 0, `${what}: the editor moved or faded (${JSON.stringify(s.first)})`);
|
||||
assert.equal(s.focused, true, `${what}: the editor lost the focus`);
|
||||
assert.equal(s.text, "Use pnpm, never npm, in this repo here", `${what}: the text typed`);
|
||||
assert.equal(s.caret, 4, `${what}: the caret`);
|
||||
return s;
|
||||
};
|
||||
|
||||
// two rounds of both polls with nothing new
|
||||
const reads = async (n) => {
|
||||
const s = st.semReads + n, d = st.distReads + n;
|
||||
while (st.semReads < s || st.distReads < d) await page.waitForTimeout(100);
|
||||
await page.waitForTimeout(150); // what a read draws, drawn
|
||||
};
|
||||
await reads(2);
|
||||
let s = await steady("polls with nothing new");
|
||||
assert.equal(s.same, true, "polls with nothing new: the editor was drawn anew");
|
||||
|
||||
// what is new is said in its own row, the editor left alone
|
||||
st.sem = { ...st.sem, read: 2, reading: false };
|
||||
const was = await page.locator(`${view} .lib-memsem .sub`).textContent();
|
||||
await reads(1);
|
||||
await page.waitForFunction((was) => document.querySelector("#view-library .lib-memsem .sub")?.textContent !== was, was);
|
||||
// the row's new line may wrap, and move what is under it once
|
||||
s = await steady("search by meaning read them all", true);
|
||||
assert.equal(s.same, true, "a new reading: the editor was drawn anew");
|
||||
await page.evaluate(() => window.__rebase());
|
||||
|
||||
// the run ends: the memories are read again, and the page is
|
||||
// drawn again with them, the editor open as it was
|
||||
st.dist = { ...st.dist, running: false };
|
||||
st.mem = memories();
|
||||
st.mem.memories.push({ id: "a3", text: "Answers in Chinese", kind: "preference", scope: "global", origin: "inferred", status: "active", created: at(3), updated: at(3) });
|
||||
await page.locator(`${view} .lib-mems .lib-mem[data-id="a3"]`).waitFor();
|
||||
await page.waitForTimeout(300);
|
||||
// a3 is newer, listed above it
|
||||
await steady("the run ended with a new memory", true);
|
||||
assert.equal(await page.locator(`${view} .lib-memdetail`).count(), 1);
|
||||
// a closed and reopened editor still comes in as before
|
||||
await row.evaluate((e) => e.click()); // at 420px the header can sit over it while the page settles
|
||||
await page.locator(`${view} .lib-memdetail`).waitFor({ state: "detached" });
|
||||
await row.evaluate((e) => e.click()); // at 420px the header can sit over it while the page settles
|
||||
await page.locator(`${view} .lib-memdetail`).waitFor();
|
||||
await page.waitForFunction(() => window.__entrances > 0);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -139,19 +139,6 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.locator("#modal .lib-pldetail").waitFor();
|
||||
await settled(page);
|
||||
assert.deepEqual(await sideways(page), [], "sideways scroll in the dialog at 1100");
|
||||
// the description keeps the dialog's width, and the parts are folded (jinpwng on X)
|
||||
const m = await page.evaluate(() => {
|
||||
const d = document.querySelector("#modal .lib-pldetail");
|
||||
const p = d.querySelector("p").getBoundingClientRect();
|
||||
const w = (x) => x.getBoundingClientRect().width;
|
||||
return { p: p.width, d: d.getBoundingClientRect().width, open: [...d.querySelectorAll("details")].filter((x) => x.open).length, n: d.querySelectorAll("details").length,
|
||||
parts: [...d.querySelectorAll("details")].map(w), src: w(d.querySelector(".lib-plsource")) };
|
||||
});
|
||||
assert(m.p > m.d * 0.8, "the description is squeezed: " + JSON.stringify(m));
|
||||
// #6309: Plannotator's Hooks heading sat far right and the GitHub line in the middle
|
||||
for (const x of [...m.parts, m.src]) assert(x > m.d * 0.8, "a part or the source is squeezed: " + JSON.stringify(m));
|
||||
assert.equal(m.open, 0, "parts open by default");
|
||||
assert.equal(m.n, 4);
|
||||
await ctx.close();
|
||||
}
|
||||
|
||||
@@ -162,7 +149,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
|
||||
assert(tabs.includes(w("Claude plugins") + " · 1"), tabs.join("|"));
|
||||
assert.equal((await row("code-kit").locator(".lib-plparts").textContent()).trim(),
|
||||
[w("Skills") + " 1", w("MCP servers") + " 1", w("Hooks") + " 1", w("Subagents") + " 1"].join(" · "));
|
||||
[w("Skills: {names}", { names: "code-kit-tdd" }), w("MCP servers: {names}", { names: "code-kit-docs" }), w("Hooks: {names}", { names: "code-kit-lint" }), w("Subagents: {names}", { names: "code-kit-reviewer" })].join(" · "));
|
||||
assert.deepEqual(await sideways(page), [], "sideways scroll at 420");
|
||||
assert.equal(await page.locator("select").count(), 0, "a native <select>");
|
||||
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// (jinpwng on X) The Subagents tab lists the projects: a card opens to each
|
||||
// library subagent with chips for the agents that read a project's own
|
||||
// subagent folder, and a chip posts that project's agents for the subagent to
|
||||
// projects/subagents. An agent with no project folder has no chip. The click
|
||||
// scrolls nothing; in English and Chinese. No backend: the API is faked here.
|
||||
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 DIR = HOME + "/code/app";
|
||||
const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more });
|
||||
const sv = (name, transport) => ({ name, transport, command: transport === "stdio" ? name : "", url: transport === "stdio" ? "" : "http://localhost:9/" + name, agents: [] });
|
||||
const lib = (servers) => ({
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [
|
||||
agent("claude", "Claude Code", { projectSubagents: ".claude/agents" }),
|
||||
agent("codex", "Codex", { projectSubagents: ".codex/agents" }),
|
||||
agent("goose", "Goose"),
|
||||
],
|
||||
instructions: { agents: [] }, servers: [], subagents: [{ name: "reviewer", description: "Reviews", agents: [] }, { name: "tester", description: "Tests", agents: [] }], skills: [], foundServers: [], foundSkills: [],
|
||||
projects: [{ dir: DIR, name: "app", copy: false, skills: {}, placed: [], servers: {}, subagents: servers, wrote: {} }],
|
||||
});
|
||||
|
||||
function server(lang, posts) {
|
||||
let servers = {};
|
||||
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/library") return route.fulfill({ json: lib(servers) });
|
||||
if (url.pathname === "/api/library/projects/subagents") {
|
||||
const b = req.postDataJSON();
|
||||
posts.push(b);
|
||||
if (posts.hold) await posts.hold;
|
||||
servers = { ...servers, [b.name]: b.agents };
|
||||
if (!b.agents.length) delete servers[b.name];
|
||||
return route.fulfill({ json: { ...lib(servers), result: { changed: [], problems: [] } } });
|
||||
}
|
||||
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
|
||||
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 });
|
||||
};
|
||||
}
|
||||
|
||||
const scrolled = (page) => page.evaluate(() => [window.scrollX, window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop || e.scrollLeft).map((e) => `${e.className}:${e.scrollTop},${e.scrollLeft}`)].join(" "));
|
||||
// a click where the element is, as the reader's: Playwright's own click
|
||||
// first scrolls it into view
|
||||
const press = async (page, loc) => {
|
||||
const b = await loc.boundingBox();
|
||||
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
|
||||
};
|
||||
// a chip: the chips fan out under the pointer first, as a reader's hand
|
||||
// does, and the chip is pressed where it is then
|
||||
const chip = async (page, loc) => {
|
||||
const a = await loc.boundingBox();
|
||||
await page.mouse.move(a.x + a.width / 2, a.y + a.height / 2);
|
||||
await page.waitForTimeout(350);
|
||||
await press(page, loc);
|
||||
};
|
||||
|
||||
const words = {
|
||||
en: { head: "Project subagents", none: "No subagents yet", one: "reviewer is in app for Claude Code", on: "reviewer is in app for Claude Code, Codex" },
|
||||
zh: { head: "项目子代理", none: "还没有子代理", one: "reviewer 已在 app 中对 Claude Code 开启", on: "reviewer 已在 app 中对 Claude Code, Codex 开启" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": a project's subagents, agent by agent", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
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"]) {
|
||||
await t.test(lang, async () => {
|
||||
const w = words[lang], posts = [];
|
||||
const ctx = await browser.newContext({ viewport: { width: 860, height: 700 } });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "subagents"); } catch {} });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, posts));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
const card = page.locator("#view-library .lib-project");
|
||||
await card.waitFor();
|
||||
assert.equal((await card.locator(".lib-tags").textContent()).trim(), w.none);
|
||||
assert.ok((await page.locator("#view-library .row-head .label").allTextContents()).includes(w.head));
|
||||
|
||||
await card.locator(".lib-projhead").scrollIntoViewIfNeeded();
|
||||
const before = await scrolled(page);
|
||||
await press(page, card.locator(".lib-projhead"));
|
||||
const rows = card.locator(".lib-projsubagent");
|
||||
await rows.first().waitFor();
|
||||
assert.equal(await rows.count(), 2);
|
||||
const row = rows.filter({ hasText: "reviewer" }).first();
|
||||
assert.deepEqual(await row.locator(".lib-ag").evaluateAll((cs) => cs.map((c) => c.dataset.agent)), ["claude", "codex"], "Goose reads no project folder");
|
||||
|
||||
await chip(page, row.locator('.lib-ag[data-agent="claude"]'));
|
||||
await page.waitForFunction(() => document.querySelectorAll('#view-library .lib-projsubagent .lib-ag.on[data-agent="claude"]').length === 1);
|
||||
await page.waitForFunction((s) => document.querySelector("#status").textContent.trim() === s, w.one);
|
||||
await chip(page, card.locator(".lib-projsubagent").first().locator('.lib-ag[data-agent="codex"]'));
|
||||
await page.waitForFunction(() => document.querySelectorAll('#view-library .lib-projsubagent .lib-ag.on').length === 2);
|
||||
await page.waitForFunction((s) => document.querySelector("#status").textContent.trim() === s, w.on);
|
||||
assert.deepEqual(posts, [{ dir: DIR, name: "reviewer", agents: ["claude"] }, { dir: DIR, name: "reviewer", agents: ["claude", "codex"] }]);
|
||||
assert.equal(await scrolled(page), before, "the clicks scroll nothing");
|
||||
assert.deepEqual(errors, []);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -448,7 +448,7 @@ func (l *Library) syncTrees(p *Project, res *Result, hubs map[string]*Server) {
|
||||
if t == nil {
|
||||
t = &Project{Dir: d}
|
||||
}
|
||||
t.Copy, t.Skills, t.Servers, t.ServersOff, t.SkillsOff, t.Subagents = p.Copy, p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents
|
||||
t.Copy, t.Skills, t.Servers, t.ServersOff, t.SkillsOff = p.Copy, p.Skills, p.Servers, p.ServersOff, p.SkillsOff
|
||||
l.syncFolder(t, res, hubs)
|
||||
trees = append(trees, t)
|
||||
}
|
||||
@@ -461,7 +461,7 @@ func (l *Library) syncTrees(p *Project, res *Result, hubs map[string]*Server) {
|
||||
}
|
||||
// no longer one of the repository's worktrees, or no longer the
|
||||
// project's: what magpie put there comes out
|
||||
t.Skills, t.Servers, t.ServersOff, t.SkillsOff, t.Subagents = nil, nil, nil, nil, nil
|
||||
t.Skills, t.Servers, t.ServersOff, t.SkillsOff = nil, nil, nil, nil
|
||||
l.syncFolder(t, res, nil)
|
||||
if t.holds() {
|
||||
trees = append(trees, t)
|
||||
@@ -484,17 +484,7 @@ func (p *Project) tree(dir string) *Project {
|
||||
|
||||
// holds says whether magpie has anything of its own in the folder still.
|
||||
func (p *Project) holds() bool {
|
||||
return len(p.Placed) > 0 || len(p.Wrote) > 0 || len(p.CodexOff) > 0 || len(p.Overrides) > 0 || len(p.MadeFiles) > 0 || len(p.AgentFiles) > 0
|
||||
}
|
||||
|
||||
// ignored are the files and folders of the project magpie put there, which
|
||||
// are kept out of git.
|
||||
func (p *Project) ignored() []string {
|
||||
out := slices.Concat(p.Placed, p.MadeFiles)
|
||||
for _, f := range p.AgentFiles {
|
||||
out = append(out, f.Path)
|
||||
}
|
||||
return out
|
||||
return len(p.Placed) > 0 || len(p.Wrote) > 0 || len(p.CodexOff) > 0 || len(p.Overrides) > 0 || len(p.MadeFiles) > 0
|
||||
}
|
||||
|
||||
// treesChanged says whether a project's repository has a worktree its
|
||||
@@ -504,7 +494,7 @@ func (l *Library) treesChanged() bool {
|
||||
for _, p := range l.Projects {
|
||||
// a folder made a repository since (git init): its entries go
|
||||
// into the new info/exclude
|
||||
if len(p.ignored()) > 0 {
|
||||
if len(p.Placed)+len(p.MadeFiles) > 0 {
|
||||
if g, ok := gitOf(p.Dir); ok {
|
||||
b, _ := os.ReadFile(filepath.Join(g.Common, "info", "exclude"))
|
||||
if !strings.Contains(string(b), excludeBegin(p.Dir)) {
|
||||
@@ -512,7 +502,7 @@ func (l *Library) treesChanged() bool {
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(p.Skills)+len(p.Servers)+len(p.ServersOff)+len(p.SkillsOff)+len(p.Subagents) == 0 && len(p.Trees) == 0 {
|
||||
if len(p.Skills)+len(p.Servers)+len(p.ServersOff)+len(p.SkillsOff) == 0 && len(p.Trees) == 0 {
|
||||
continue
|
||||
}
|
||||
dirs := p.treeDirs()
|
||||
|
||||
@@ -1,213 +0,0 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
)
|
||||
|
||||
// A project can be given library subagents (jinpwng on X), each for some
|
||||
// agents, as files of the project's own: the folder each agent reads a
|
||||
// project's subagents from, in the shape its user-wide ones have
|
||||
// (subagents.go). Only an agent whose docs name a project folder is
|
||||
// listed:
|
||||
//
|
||||
// Claude Code .claude/agents/<name>.md code.claude.com/docs/en/sub-agents
|
||||
// Codex .codex/agents/<name>.toml "standalone TOML files under .codex/agents/ for project-scoped agents" (Codex docs, subagents)
|
||||
// OpenCode .opencode/agents/<name>.md opencode.ai/docs/agents
|
||||
// Gemini CLI .gemini/agents/<name>.md "Project-level: .gemini/agents/*.md" (Gemini CLI docs, subagents)
|
||||
// Qwen Code .qwen/agents/<name>.md Qwen Code docs, sub-agents
|
||||
// Factory Droid .factory/droids/<name>.md docs.factory.com/cli/configuration/custom-droids
|
||||
// Cursor .cursor/agents/<name>.md cursor.com/docs/subagents
|
||||
// Copilot CLI .github/agents/<name>.agent.md "Repository-level custom agents are stored in the .github/agents directory"
|
||||
//
|
||||
// A file is recorded by its hash (Project.AgentFiles), as the user-wide
|
||||
// ones are: magpie writes over or takes away only one still exactly as it
|
||||
// wrote it, and a file of the user's by the same name is never touched.
|
||||
// Nothing is written outside the project's folder, so the agents' own
|
||||
// (global) subagents stay as they are.
|
||||
var projectSubagentDirs = map[string]string{
|
||||
"claude": ".claude/agents",
|
||||
"codex": ".codex/agents",
|
||||
"opencode": ".opencode/agents",
|
||||
"gemini": ".gemini/agents",
|
||||
"qwen": ".qwen/agents",
|
||||
"droid": ".factory/droids",
|
||||
"cursor": ".cursor/agents",
|
||||
"copilot": ".github/agents",
|
||||
}
|
||||
|
||||
// ProjectSubagentsDir is the folder, in a project, an agent reads its
|
||||
// subagents from: "" for one magpie can't give a project's subagents to.
|
||||
func ProjectSubagentsDir(agentID string) string { return projectSubagentDirs[agentID] }
|
||||
|
||||
// projectSubagentSpec is the shape of agent id's subagent files, kept in
|
||||
// the project's folder in place of the agent's own.
|
||||
func projectSubagentSpec(p *Project, id string) *subagentSpec {
|
||||
sp, _ := subagentSpecOf(&Target{Agent: &agent.Agent{ID: id}})
|
||||
if sp == nil {
|
||||
return nil
|
||||
}
|
||||
cp := *sp
|
||||
cp.dir = filepath.Join(p.Dir, filepath.FromSlash(projectSubagentDirs[id]))
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (p *Project) rel(abs string) string {
|
||||
r, _ := filepath.Rel(p.Dir, abs)
|
||||
return filepath.ToSlash(r)
|
||||
}
|
||||
|
||||
// syncProjectSubagents writes the library's subagents the project has
|
||||
// into each agent's folder there, and takes away those it wrote that it
|
||||
// no longer has.
|
||||
func (l *Library) syncProjectSubagents(p *Project, fail func(what string, err error)) {
|
||||
type want struct {
|
||||
s *Subagent
|
||||
sp *subagentSpec
|
||||
}
|
||||
wanted := map[string]want{} // file (project-relative) → what goes there
|
||||
for _, name := range slices.Sorted(func(yield func(string) bool) {
|
||||
for n := range p.Subagents {
|
||||
if !yield(n) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}) {
|
||||
s := l.subagent(name)
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
for _, id := range p.Subagents[name] {
|
||||
if sp := projectSubagentSpec(p, id); sp != nil {
|
||||
wanted[p.rel(sp.path(s.Name))] = want{s, sp}
|
||||
}
|
||||
}
|
||||
}
|
||||
var kept []SubagentFile
|
||||
done := map[string]bool{}
|
||||
for _, f := range p.AgentFiles {
|
||||
abs := filepath.Join(p.Dir, filepath.FromSlash(f.Path))
|
||||
cur, err := os.ReadFile(abs)
|
||||
switch {
|
||||
case os.IsNotExist(err):
|
||||
continue // gone: written again below if it is still wanted
|
||||
case err != nil:
|
||||
fail("subagent:"+f.Name, err)
|
||||
kept = append(kept, f)
|
||||
done[f.Path] = true
|
||||
continue
|
||||
case subagentHash(cur) != f.Hash:
|
||||
continue // the user's from now on
|
||||
}
|
||||
w, ok := wanted[f.Path]
|
||||
if !ok {
|
||||
if err := os.Remove(abs); err != nil && !os.IsNotExist(err) {
|
||||
fail("subagent:"+f.Name, err)
|
||||
kept = append(kept, f)
|
||||
}
|
||||
continue
|
||||
}
|
||||
done[f.Path] = true
|
||||
body := l.renderSubagent(w.sp, w.s)
|
||||
if !bytes.Equal(cur, body) {
|
||||
if err := edit.WriteAtomic(abs, body); err != nil {
|
||||
fail("subagent:"+f.Name, err)
|
||||
kept = append(kept, f)
|
||||
continue
|
||||
}
|
||||
}
|
||||
kept = append(kept, SubagentFile{Name: w.s.Name, Path: f.Path, Hash: subagentHash(body)})
|
||||
}
|
||||
for _, rel := range slices.Sorted(func(yield func(string) bool) {
|
||||
for r := range wanted {
|
||||
if !yield(r) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}) {
|
||||
if done[rel] {
|
||||
continue
|
||||
}
|
||||
w := wanted[rel]
|
||||
abs := filepath.Join(p.Dir, filepath.FromSlash(rel))
|
||||
body := l.renderSubagent(w.sp, w.s)
|
||||
cur, err := os.ReadFile(abs)
|
||||
switch {
|
||||
case err == nil && bytes.Equal(cur, body):
|
||||
// the same as magpie would write: taken as magpie's
|
||||
case err == nil:
|
||||
fail("subagent:"+w.s.Name, fmt.Errorf("%s is in the project already and isn't magpie's: it's left as it is", rel))
|
||||
continue
|
||||
case !os.IsNotExist(err):
|
||||
fail("subagent:"+w.s.Name, err)
|
||||
continue
|
||||
default:
|
||||
if err := p.mkdirs(filepath.Dir(abs)); err != nil {
|
||||
fail("subagent:"+w.s.Name, err)
|
||||
continue
|
||||
}
|
||||
if err := edit.WriteAtomic(abs, body); err != nil {
|
||||
fail("subagent:"+w.s.Name, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
kept = append(kept, SubagentFile{Name: w.s.Name, Path: rel, Hash: subagentHash(body)})
|
||||
}
|
||||
slices.SortFunc(kept, func(x, y SubagentFile) int { return strings.Compare(x.Path, y.Path) })
|
||||
p.AgentFiles = kept
|
||||
}
|
||||
|
||||
// ProjectSubagents sets which agents get each of some library subagents
|
||||
// in a project; none takes them out of it.
|
||||
func ProjectSubagents(dir string, names, agents []string) (*Result, error) {
|
||||
return change(func(l *Library) error {
|
||||
p := l.project(dir)
|
||||
if p == nil {
|
||||
return fmt.Errorf("no project %s", dir)
|
||||
}
|
||||
if len(names) == 0 {
|
||||
return errors.New("no subagents given")
|
||||
}
|
||||
for _, n := range names {
|
||||
if l.subagent(n) == nil {
|
||||
return fmt.Errorf("no subagent called %s", n)
|
||||
}
|
||||
}
|
||||
var ids []string
|
||||
for _, id := range agents {
|
||||
if ProjectSubagentsDir(id) == "" {
|
||||
return fmt.Errorf("magpie knows of no folder %s reads a project's subagents from", id)
|
||||
}
|
||||
ids = set(ids, id, true)
|
||||
}
|
||||
for _, n := range names {
|
||||
if len(ids) == 0 {
|
||||
delete(p.Subagents, n)
|
||||
continue
|
||||
}
|
||||
if p.Subagents == nil {
|
||||
p.Subagents = map[string][]string{}
|
||||
}
|
||||
p.Subagents[n] = slices.Clone(ids)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// renameProjectSubagents has the projects give a subagent its new name.
|
||||
func (l *Library) renameProjectSubagents(old, name string) {
|
||||
for _, p := range l.Projects {
|
||||
if a, ok := p.Subagents[old]; ok {
|
||||
delete(p.Subagents, old)
|
||||
p.Subagents[name] = a
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var projectAgentFiles = map[string]string{
|
||||
"claude": ".claude/agents/reviewer.md",
|
||||
"codex": ".codex/agents/reviewer.toml",
|
||||
"opencode": ".opencode/agents/reviewer.md",
|
||||
"gemini": ".gemini/agents/reviewer.md",
|
||||
"qwen": ".qwen/agents/reviewer.md",
|
||||
"droid": ".factory/droids/reviewer.md",
|
||||
"cursor": ".cursor/agents/reviewer.md",
|
||||
"copilot": ".github/agents/reviewer.agent.md",
|
||||
}
|
||||
|
||||
func subagentProjects(t *testing.T) (h, a, b string) {
|
||||
h = sandbox(t)
|
||||
a, b = filepath.Join(t.TempDir(), "a"), filepath.Join(t.TempDir(), "b")
|
||||
for _, d := range []string{a, b} {
|
||||
gitInit(t, d)
|
||||
ok(t)(AddProject(d))
|
||||
}
|
||||
s := reviewer
|
||||
s.Agents = []string{}
|
||||
ok(t)(SaveSubagent("", s))
|
||||
return
|
||||
}
|
||||
|
||||
// A project's subagents go into the folder each agent reads a project's
|
||||
// from, in the shape of its user-wide ones (jinpwng on X), and into
|
||||
// nothing else: not the agent's own folder, not another project, not
|
||||
// the project's git.
|
||||
func TestProjectSubagentsEachAgentsFolder(t *testing.T) {
|
||||
h, a, b := subagentProjects(t)
|
||||
var ids []string
|
||||
for id := range projectAgentFiles {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
res := ok(t)(ProjectSubagents(a, []string{"reviewer"}, ids))
|
||||
if len(res.Problems) > 0 {
|
||||
t.Fatalf("problems: %+v", res.Problems)
|
||||
}
|
||||
for id, rel := range projectAgentFiles {
|
||||
got := read(t, filepath.Join(a, rel))
|
||||
if !strings.Contains(got, "You review code.") {
|
||||
t.Errorf("%s: %s = %q", id, rel, got)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(read(t, filepath.Join(a, ".codex/agents/reviewer.toml")), "developer_instructions") {
|
||||
t.Error("Codex's role file isn't a role file")
|
||||
}
|
||||
// global and other projects untouched
|
||||
for _, rel := range projectAgentFiles {
|
||||
if _, err := os.Stat(filepath.Join(b, rel)); err == nil {
|
||||
t.Errorf("another project got %s", rel)
|
||||
}
|
||||
}
|
||||
for _, d := range []string{".claude/agents", ".codex/agents", ".gemini/agents", ".cursor/agents", ".copilot/agents", ".factory/droids", ".config/opencode/agents", ".qwen/agents"} {
|
||||
if _, err := os.Stat(filepath.Join(h, d)); err == nil {
|
||||
t.Errorf("the user-wide %s was made", d)
|
||||
}
|
||||
}
|
||||
// kept out of git, the project's own files untouched
|
||||
g, _ := gitOf(a)
|
||||
ex := read(t, filepath.Join(g.Common, "info", "exclude"))
|
||||
for _, rel := range projectAgentFiles {
|
||||
if !strings.Contains(ex, "/"+rel+"\n") {
|
||||
t.Errorf("%s isn't in info/exclude:\n%s", rel, ex)
|
||||
}
|
||||
}
|
||||
// a library edit reaches the project
|
||||
s := reviewer
|
||||
s.Prompt = "You review harder."
|
||||
s.Agents = []string{}
|
||||
ok(t)(SaveSubagent("reviewer", s))
|
||||
if !strings.Contains(read(t, filepath.Join(a, ".claude/agents/reviewer.md")), "harder") {
|
||||
t.Error("an edit of the subagent didn't reach the project")
|
||||
}
|
||||
// taking it out of one agent takes only that file
|
||||
ok(t)(ProjectSubagents(a, []string{"reviewer"}, []string{"claude"}))
|
||||
for id, rel := range projectAgentFiles {
|
||||
_, err := os.Stat(filepath.Join(a, rel))
|
||||
if (id == "claude") != (err == nil) {
|
||||
t.Errorf("%s: %s present=%v", id, rel, err == nil)
|
||||
}
|
||||
}
|
||||
// none: everything magpie made goes, folders and exclude lines too
|
||||
ok(t)(ProjectSubagents(a, []string{"reviewer"}, nil))
|
||||
for _, d := range []string{".claude", ".github", ".codex"} {
|
||||
if _, err := os.Stat(filepath.Join(a, d)); err == nil {
|
||||
t.Errorf("%s was left", d)
|
||||
}
|
||||
}
|
||||
if ex := read(t, filepath.Join(g.Common, "info", "exclude")); strings.Contains(ex, "reviewer") {
|
||||
t.Errorf("exclude keeps lines:\n%s", ex)
|
||||
}
|
||||
}
|
||||
|
||||
// A subagent file of the user's by the same name is never written over,
|
||||
// and one the user edited is theirs from then on.
|
||||
func TestProjectSubagentsLeaveTheUsersFiles(t *testing.T) {
|
||||
_, a, _ := subagentProjects(t)
|
||||
own := filepath.Join(a, ".claude/agents/reviewer.md")
|
||||
write(t, own, "mine\n")
|
||||
res, err := ProjectSubagents(a, []string{"reviewer"}, []string{"claude", "gemini"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if read(t, own) != "mine\n" {
|
||||
t.Fatal("the user's file was written over")
|
||||
}
|
||||
found := false
|
||||
for _, p := range res.Problems {
|
||||
found = found || p.What == "project:subagent:reviewer"
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("no problem for the user's file: %+v", res.Problems)
|
||||
}
|
||||
gem := filepath.Join(a, ".gemini/agents/reviewer.md")
|
||||
write(t, gem, read(t, gem)+"\nmy edit\n")
|
||||
ok(t)(ProjectSubagents(a, []string{"reviewer"}, nil))
|
||||
if !strings.Contains(read(t, gem), "my edit") {
|
||||
t.Error("an edited file was taken away")
|
||||
}
|
||||
if read(t, own) != "mine\n" {
|
||||
t.Error("the user's file was taken away")
|
||||
}
|
||||
}
|
||||
|
||||
// Taking the library's subagent out, or renaming it, follows in projects;
|
||||
// removing the project takes its files; an agent magpie knows no folder
|
||||
// of is refused.
|
||||
func TestProjectSubagentsFollowTheLibrary(t *testing.T) {
|
||||
_, a, _ := subagentProjects(t)
|
||||
if _, err := ProjectSubagents(a, []string{"reviewer"}, []string{"grok"}); err == nil {
|
||||
t.Error("an agent with no known project folder was taken")
|
||||
}
|
||||
ok(t)(ProjectSubagents(a, []string{"reviewer"}, []string{"claude"}))
|
||||
s := reviewer
|
||||
s.Name, s.Agents = "checker", []string{}
|
||||
ok(t)(SaveSubagent("reviewer", s))
|
||||
if _, err := os.Stat(filepath.Join(a, ".claude/agents/reviewer.md")); err == nil {
|
||||
t.Error("the old name stayed")
|
||||
}
|
||||
if !strings.Contains(read(t, filepath.Join(a, ".claude/agents/checker.md")), `name: "checker"`) {
|
||||
t.Error("the renamed subagent didn't follow")
|
||||
}
|
||||
ok(t)(RemoveSubagents([]string{"checker"}))
|
||||
if _, err := os.Stat(filepath.Join(a, ".claude")); err == nil {
|
||||
t.Error("removing the subagent left its file or folder")
|
||||
}
|
||||
s.Name = "again"
|
||||
ok(t)(SaveSubagent("", s))
|
||||
ok(t)(ProjectSubagents(a, []string{"again"}, []string{"claude"}))
|
||||
ok(t)(RemoveProject(a, false))
|
||||
if _, err := os.Stat(filepath.Join(a, ".claude")); err == nil {
|
||||
t.Error("removing the project left its files")
|
||||
}
|
||||
}
|
||||
|
||||
// A project's subagents follow it into the repository's other git
|
||||
// worktrees, as its skills and servers do, and come out with it.
|
||||
func TestProjectSubagentsFollowWorktrees(t *testing.T) {
|
||||
_, a, _ := subagentProjects(t)
|
||||
ok(t)(ProjectSubagents(a, []string{"reviewer"}, []string{"claude"}))
|
||||
|
||||
// git worktree add ../a-wt
|
||||
wt := filepath.Join(filepath.Dir(a), "a-wt")
|
||||
own := filepath.Join(a, ".git", "worktrees", "a-wt")
|
||||
write(t, filepath.Join(wt, ".git"), "gitdir: "+own+"\n")
|
||||
write(t, filepath.Join(own, "gitdir"), filepath.Join(wt, ".git")+"\n")
|
||||
write(t, filepath.Join(own, "commondir"), "../..\n")
|
||||
keepProjectTrees()
|
||||
f := filepath.Join(wt, ".claude", "agents", "reviewer.md")
|
||||
if !strings.Contains(read(t, f), "You review code.") {
|
||||
t.Fatal("the worktree hasn't the project's subagent")
|
||||
}
|
||||
|
||||
ok(t)(ProjectSubagents(a, []string{"reviewer"}, nil))
|
||||
if _, err := os.Stat(f); err == nil {
|
||||
t.Error("the worktree keeps a subagent the project no longer has")
|
||||
}
|
||||
}
|
||||
@@ -60,11 +60,6 @@ type Project struct {
|
||||
// Trees are the project's folder in each other worktree of its git
|
||||
// repository, given the project's set, with what magpie put in each
|
||||
Trees []*Project `json:"trees,omitempty"`
|
||||
// Subagents are the library's subagents the project has, and for which
|
||||
// agents; AgentFiles the files magpie wrote for them, by their hash
|
||||
// (project_subagents.go)
|
||||
Subagents map[string][]string `json:"subagents,omitempty"`
|
||||
AgentFiles []SubagentFile `json:"agentFiles,omitempty"`
|
||||
}
|
||||
|
||||
// projectSkillsDirs is where, in a project, each agent reads skills of its
|
||||
@@ -138,7 +133,7 @@ func (l *Library) syncProjects(res *Result) {
|
||||
|
||||
func (l *Library) syncProject(p *Project, res *Result) {
|
||||
if fi, err := os.Stat(p.Dir); err != nil || !fi.IsDir() {
|
||||
if len(p.Skills) > 0 || len(p.Servers) > 0 || len(p.Subagents) > 0 || len(p.ServersOff) > 0 || len(p.SkillsOff) > 0 || p.holds() {
|
||||
if len(p.Skills) > 0 || len(p.Servers) > 0 || len(p.ServersOff) > 0 || len(p.SkillsOff) > 0 || p.holds() {
|
||||
res.Problems = append(res.Problems, Problem{Agent: p.Dir, What: "project:", Error: "the folder is gone"})
|
||||
}
|
||||
return
|
||||
@@ -213,7 +208,6 @@ func (l *Library) syncFolder(p *Project, res *Result, hubs map[string]*Server) {
|
||||
res.Problems = append(res.Problems, Problem{Agent: p.Dir, What: "project:" + what, Error: err.Error()})
|
||||
})
|
||||
l.syncSkillsOff(p, fail)
|
||||
l.syncProjectSubagents(p, func(what string, err error) { fail(what, err) })
|
||||
p.tidy()
|
||||
}
|
||||
|
||||
@@ -230,9 +224,10 @@ func (p *Project) keepOutOfGit() error {
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
entries := p.ignored()
|
||||
entries := slices.Concat(p.Placed, p.MadeFiles)
|
||||
for _, t := range p.Trees {
|
||||
entries = append(entries, t.ignored()...)
|
||||
entries = append(entries, t.Placed...)
|
||||
entries = append(entries, t.MadeFiles...)
|
||||
}
|
||||
return p.writeExclude(g, entries)
|
||||
}
|
||||
@@ -470,7 +465,7 @@ func RemoveProject(dir string, keep bool) (*Result, error) {
|
||||
l.Projects = slices.DeleteFunc(l.Projects, func(x *Project) bool { return x == p })
|
||||
return nil
|
||||
}
|
||||
p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents = nil, nil, nil, nil, nil
|
||||
p.Skills, p.Servers, p.ServersOff, p.SkillsOff = nil, nil, nil, nil
|
||||
l.syncProject(p, &Result{})
|
||||
if !p.holds() && p.Claude == nil && !slices.ContainsFunc(p.Trees, (*Project).holds) {
|
||||
l.Projects = slices.DeleteFunc(l.Projects, func(x *Project) bool { return x == p })
|
||||
@@ -553,13 +548,8 @@ type ProjectView struct {
|
||||
SkillsOff map[string][]string `json:"skillsOff"`
|
||||
// Trees are the project's folder in the repository's other git
|
||||
// worktrees, which follow it
|
||||
Trees []string `json:"trees,omitempty"`
|
||||
// Subagents are the library's subagents the project has, for the
|
||||
// agents named
|
||||
Subagents map[string][]string `json:"subagents"`
|
||||
// AgentFiles are the project's files magpie wrote for them
|
||||
AgentFiles []string `json:"agentFiles"`
|
||||
Missing bool `json:"missing,omitempty"` // the folder is gone
|
||||
Trees []string `json:"trees,omitempty"`
|
||||
Missing bool `json:"missing,omitempty"` // the folder is gone
|
||||
// Problems are, by skill ("" for the project's own), what couldn't be done
|
||||
Problems map[string]string `json:"problems,omitempty"`
|
||||
}
|
||||
@@ -585,14 +575,6 @@ func projectViews(l *Library, problems []Problem) []ProjectView {
|
||||
for k, a := range p.SkillsOff {
|
||||
v.SkillsOff[k] = append([]string{}, a...)
|
||||
}
|
||||
v.AgentFiles = []string{}
|
||||
for _, f := range p.AgentFiles {
|
||||
v.AgentFiles = append(v.AgentFiles, f.Path)
|
||||
}
|
||||
v.Subagents = map[string][]string{}
|
||||
for k, a := range p.Subagents {
|
||||
v.Subagents[k] = append([]string{}, a...)
|
||||
}
|
||||
for _, t := range p.Trees {
|
||||
v.Trees = append(v.Trees, t.Dir)
|
||||
}
|
||||
|
||||
@@ -413,9 +413,6 @@ func SaveSubagent(old string, s Subagent) (*Result, error) {
|
||||
return fmt.Errorf("no subagent called %s", old)
|
||||
}
|
||||
l.Subagents = slices.Delete(l.Subagents, i, i+1)
|
||||
if old != s.Name {
|
||||
l.renameProjectSubagents(old, s.Name)
|
||||
}
|
||||
}
|
||||
s.Skills = slices.Compact(slices.Sorted(slices.Values(s.Skills)))
|
||||
s.MCP = slices.Compact(slices.Sorted(slices.Values(s.MCP)))
|
||||
|
||||
@@ -401,8 +401,6 @@ type AgentView struct {
|
||||
ProjectSkills string `json:"projectSkills,omitempty"`
|
||||
// ProjectMCP is the file, in a project, it reads MCP servers from
|
||||
ProjectMCP string `json:"projectMCP,omitempty"`
|
||||
// ProjectSubagents is the folder in a project it reads subagents from
|
||||
ProjectSubagents string `json:"projectSubagents,omitempty"`
|
||||
// ProjectNoSSE: its project file can't take a server over SSE
|
||||
ProjectNoSSE bool `json:"projectNoSSE,omitempty"`
|
||||
// ProjectOff and ProjectSkillOff: a server, or a skill, it has from
|
||||
@@ -626,7 +624,7 @@ func readView(problems []Problem, glance bool) (*View, error) {
|
||||
v := &View{Agents: []AgentView{}, Servers: []ServerView{}, Skills: []SkillView{}, FoundSkills: []FoundSkill{}, Instructions: l.instructionsView(targets, asleep), Dir: Dir(), Backups: BackupDir(), CopySkills: l.CopySkills, SharedSkills: l.SharedSkills, SharedDir: sharedSkillsDir(), MCPHub: l.MCPHub, SkillRouter: l.SkillRouter, HubPath: gateway.HubMCPPath, HubNote: settings.Shared().RouterNote, HubName: gateway.HostName(), HubAllTools: settings.Shared().RouterAllTools, Partial: glance}
|
||||
for _, t := range targets {
|
||||
av := AgentView{ID: t.Agent.ID, Name: t.Agent.Name, Icon: t.Agent.Icon, Instructions: t.Instructions, Skills: t.Skills,
|
||||
SkillsAlso: t.SkillsAlso, Note: t.Note, MCPVia: t.MCPVia, ProjectSkills: ProjectSkillsDir(t.Agent.ID), ProjectMCP: ProjectMCPFile(t.Agent.ID), ProjectSubagents: ProjectSubagentsDir(t.Agent.ID),
|
||||
SkillsAlso: t.SkillsAlso, Note: t.Note, MCPVia: t.MCPVia, ProjectSkills: ProjectSkillsDir(t.Agent.ID), ProjectMCP: ProjectMCPFile(t.Agent.ID),
|
||||
ProjectOff: slices.Contains(projectOffAgents, t.Agent.ID), ProjectSkillOff: slices.Contains(projectSkillOffAgents, t.Agent.ID),
|
||||
ProjectNoSSE: ProjectNoSSE(t.Agent.ID)}
|
||||
if t.Skills != "" {
|
||||
|
||||
@@ -1,312 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
// CCSwitchScheme is the URL scheme CC Switch (github.com/farion1231/cc-switch)
|
||||
// registers. Relays put its one-click import links on their pages, so magpie
|
||||
// reads them too:
|
||||
//
|
||||
// ccswitch://v1/import?resource=provider&app=claude&name=My%20Relay&endpoint=https://relay.example&apiKey=sk-…
|
||||
// ccswitch://v1/import?resource=provider&app=claude&name=…&configFormat=json&config=<base64 of {"env":{…}}>
|
||||
//
|
||||
// The format is read from CC Switch's own parser
|
||||
// (src-tauri/src/deeplink/parser.rs, provider.rs). Only resource=provider
|
||||
// is something magpie has (prompts, MCP servers and skills are other
|
||||
// resources). Parameters:
|
||||
//
|
||||
// app claude, claude-desktop, codex, gemini, agy, copilot,
|
||||
// grokbuild, opencode, openclaw, hermes, pi, mcode, kimi, dsh
|
||||
// or omp; it picks which endpoint the address is (below)
|
||||
// name required
|
||||
// endpoint the base URL; with several, comma separated, the first
|
||||
// apiKey the API key
|
||||
// apiFormat anthropic, openai_chat, openai_responses or gemini_native:
|
||||
// which API the endpoint speaks. Without it, the app's own:
|
||||
// Anthropic for claude, Responses for codex and grokbuild,
|
||||
// Gemini for gemini and agy, Chat Completions for the rest
|
||||
// model, haikuModel, sonnetModel, opusModel the model ids to show
|
||||
// homepage the vendor's site
|
||||
// iconUrl a picture, fetched only after the user confirms
|
||||
// configFormat json (the default) or toml, with config: the base64 of the
|
||||
// app's own settings. Its address, key and models fill what
|
||||
// the other parameters leave out, as CC Switch does (claude:
|
||||
// env.ANTHROPIC_*; codex: auth.OPENAI_API_KEY and
|
||||
// config.toml's model provider; gemini: GEMINI_API_KEY and
|
||||
// GOOGLE_GEMINI_BASE_URL). The rest of that config is not
|
||||
// taken: it is the app's settings, not a provider's
|
||||
//
|
||||
// Everything else (enabled, notes, usage*, the CC Switch icon names) is
|
||||
// dropped. The link goes through the same checks and the same confirmation
|
||||
// as a magpie:// one: it becomes a magpie://import's parameters (see
|
||||
// ParseImport), so nothing is saved until the user says yes.
|
||||
const CCSwitchScheme = "ccswitch"
|
||||
|
||||
// ccSwitchLinkApps are the app= values CC Switch's parser accepts.
|
||||
var ccSwitchLinkApps = []string{"agy", "copilot", "claude", "claude-desktop", "codex", "gemini", "grokbuild", "opencode", "openclaw", "hermes", "pi", "mcode", "kimi", "dsh", "omp"}
|
||||
|
||||
// ccSwitchConfigMax bounds the base64 config: a provider's settings are a
|
||||
// few hundred bytes, and a URL much past this is not one.
|
||||
const ccSwitchConfigMax = 256 << 10
|
||||
|
||||
// ccSwitchQuery translates a ccswitch://v1/import link into the parameters
|
||||
// of a magpie import.
|
||||
func ccSwitchQuery(u *url.URL) (url.Values, error) {
|
||||
if !strings.EqualFold(u.Host, "v1") {
|
||||
return nil, errorf("ccswitch://%s: magpie reads ccswitch://v1/import links only", u.Host)
|
||||
}
|
||||
if u.Path != "/import" {
|
||||
return nil, errorf("ccswitch link path %q is not /import", u.Path)
|
||||
}
|
||||
in := u.Query()
|
||||
get := func(k string) string { return strings.TrimSpace(in.Get(k)) }
|
||||
|
||||
if r := get("resource"); r != "provider" {
|
||||
if r == "" {
|
||||
return nil, errorf("the ccswitch link has no resource=")
|
||||
}
|
||||
return nil, errorf("magpie takes providers from a ccswitch link; this one is a %q", r)
|
||||
}
|
||||
app := get("app")
|
||||
if !slices.Contains(ccSwitchLinkApps, app) {
|
||||
return nil, errorf("the ccswitch link's app= is not an app CC Switch knows: %q", app)
|
||||
}
|
||||
name := get("name")
|
||||
if name == "" {
|
||||
return nil, errorf("the ccswitch link has no name=")
|
||||
}
|
||||
if in.Has("configUrl") {
|
||||
return nil, errorf("the ccswitch link's configUrl= is not supported: the config is inline, or not at all")
|
||||
}
|
||||
|
||||
endpoint, key := get("endpoint"), get("apiKey")
|
||||
format := strings.TrimSpace(in.Get("apiFormat"))
|
||||
models := []string{get("model"), get("haikuModel"), get("sonnetModel"), get("opusModel")}
|
||||
|
||||
if raw := get("config"); raw != "" {
|
||||
cfg, err := ccSwitchConfig(raw, get("configFormat"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, err := cfg.read(app)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if key == "" {
|
||||
key = c.key
|
||||
}
|
||||
if endpoint == "" {
|
||||
endpoint = c.endpoint
|
||||
}
|
||||
if format == "" {
|
||||
format = c.format
|
||||
}
|
||||
for i, m := range c.models {
|
||||
if models[i] == "" {
|
||||
models[i] = m
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if i := strings.IndexByte(endpoint, ','); i >= 0 {
|
||||
endpoint = endpoint[:i] // the first is the one requests go to
|
||||
}
|
||||
endpoint = strings.TrimSpace(endpoint)
|
||||
|
||||
kind, err := ccSwitchKind(app, format)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := url.Values{}
|
||||
out.Set("name", name)
|
||||
if endpoint != "" {
|
||||
out.Set(kind, endpoint)
|
||||
}
|
||||
if key != "" {
|
||||
out.Set("key", key)
|
||||
}
|
||||
var ids []string
|
||||
for _, m := range models {
|
||||
if m = strings.TrimSpace(m); m != "" && !slices.Contains(ids, m) {
|
||||
ids = append(ids, m)
|
||||
}
|
||||
}
|
||||
out.Set("models", strings.Join(ids, ","))
|
||||
// a picture or a site that isn't an https URL is dropped, not a reason
|
||||
// to turn the whole link away: CC Switch does the same
|
||||
if h := get("homepage"); h != "" && page(h) != "" {
|
||||
out.Set("website", h)
|
||||
}
|
||||
if ic := get("iconUrl"); ic != "" {
|
||||
if _, err := iconURL(ic); err == nil {
|
||||
out.Set("icon", ic)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ccSwitchKind is which of magpie's endpoints the link's address is.
|
||||
func ccSwitchKind(app, format string) (string, error) {
|
||||
switch format {
|
||||
case "":
|
||||
switch app {
|
||||
case "claude", "claude-desktop":
|
||||
return "anthropic", nil
|
||||
case "codex", "grokbuild":
|
||||
return "responses", nil
|
||||
case "gemini", "agy":
|
||||
return "gemini", nil
|
||||
}
|
||||
return "chat", nil
|
||||
case "anthropic":
|
||||
return "anthropic", nil
|
||||
case "openai_chat":
|
||||
return "chat", nil
|
||||
case "openai_responses":
|
||||
return "responses", nil
|
||||
case "gemini_native":
|
||||
return "gemini", nil
|
||||
}
|
||||
return "", errorf("the ccswitch link's apiFormat= is anthropic, openai_chat, openai_responses or gemini_native, not %q", format)
|
||||
}
|
||||
|
||||
// ccSwitchSettings is what a link's config yields.
|
||||
type ccSwitchSettings struct {
|
||||
endpoint, key, format string
|
||||
models [4]string // model, haiku, sonnet, opus
|
||||
}
|
||||
|
||||
type ccSwitchCfg map[string]any
|
||||
|
||||
// ccSwitchConfig decodes the config parameter as CC Switch does: base64
|
||||
// with the quirks of a URL ("+" arriving as a space, padding left off, the
|
||||
// URL-safe alphabet), then JSON or TOML.
|
||||
func ccSwitchConfig(raw, format string) (ccSwitchCfg, error) {
|
||||
if len(raw) > ccSwitchConfigMax {
|
||||
return nil, errorf("the ccswitch link's config= is too large")
|
||||
}
|
||||
raw = strings.ReplaceAll(strings.Trim(raw, "\r\n"), " ", "+")
|
||||
raw = strings.TrimRight(raw, "=")
|
||||
b, err := base64.RawStdEncoding.DecodeString(raw)
|
||||
if err != nil {
|
||||
if b, err = base64.RawURLEncoding.DecodeString(raw); err != nil {
|
||||
return nil, errorf("the ccswitch link's config= is not base64")
|
||||
}
|
||||
}
|
||||
var m map[string]any
|
||||
switch format {
|
||||
case "", "json":
|
||||
err = json.Unmarshal(b, &m)
|
||||
case "toml":
|
||||
err = toml.Unmarshal(b, &m)
|
||||
default:
|
||||
return nil, errorf("the ccswitch link's configFormat= is json or toml, not %q", format)
|
||||
}
|
||||
if err != nil || m == nil {
|
||||
return nil, errorf("the ccswitch link's config= is not a %s object", orElse(format, "json"))
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func orElse(s, def string) string {
|
||||
if s == "" {
|
||||
return def
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (c ccSwitchCfg) str(path ...string) string {
|
||||
var v any = map[string]any(c)
|
||||
for _, k := range path {
|
||||
m, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
v = m[k]
|
||||
}
|
||||
s, _ := v.(string)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func (c ccSwitchCfg) obj(k string) ccSwitchCfg {
|
||||
m, _ := c[k].(map[string]any)
|
||||
return m
|
||||
}
|
||||
|
||||
// read takes the address, key and models an app's own settings hold.
|
||||
func (c ccSwitchCfg) read(app string) (ccSwitchSettings, error) {
|
||||
var s ccSwitchSettings
|
||||
switch app {
|
||||
case "claude", "claude-desktop":
|
||||
env := c.obj("env")
|
||||
if env == nil {
|
||||
return s, errorf("the ccswitch link's claude config needs an env object")
|
||||
}
|
||||
s.key = orElse(env.str("ANTHROPIC_AUTH_TOKEN"), env.str("ANTHROPIC_API_KEY"))
|
||||
s.endpoint = env.str("ANTHROPIC_BASE_URL")
|
||||
s.models = [4]string{env.str("ANTHROPIC_MODEL"), env.str("ANTHROPIC_DEFAULT_HAIKU_MODEL"), env.str("ANTHROPIC_DEFAULT_SONNET_MODEL"), env.str("ANTHROPIC_DEFAULT_OPUS_MODEL")}
|
||||
case "gemini", "agy":
|
||||
env := c
|
||||
if e := c.obj("env"); e != nil {
|
||||
env = e
|
||||
}
|
||||
s.key = env.str("GEMINI_API_KEY")
|
||||
s.endpoint = orElse(env.str("GOOGLE_GEMINI_BASE_URL"), env.str("GEMINI_BASE_URL"))
|
||||
s.models[0] = env.str("GEMINI_MODEL")
|
||||
case "codex":
|
||||
return c.readCodex()
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// readCodex reads {"auth":{"OPENAI_API_KEY":…},"config":"<config.toml>"},
|
||||
// or a config.toml itself. The key a provider table reads from an
|
||||
// environment variable (env_key) is the computer's own, not the link's, and
|
||||
// is never taken.
|
||||
func (c ccSwitchCfg) readCodex() (ccSwitchSettings, error) {
|
||||
var s ccSwitchSettings
|
||||
doc := map[string]any(c)
|
||||
if text := c.str("config"); text != "" {
|
||||
doc = nil
|
||||
if err := toml.Unmarshal([]byte(text), &doc); err != nil {
|
||||
return s, errorf("the ccswitch link's codex config is not TOML")
|
||||
}
|
||||
} else if c.obj("auth") != nil {
|
||||
doc = nil
|
||||
}
|
||||
root := ccSwitchCfg(doc)
|
||||
s.key = c.obj("auth").str("OPENAI_API_KEY")
|
||||
s.models[0] = root.str("model")
|
||||
id := root.str("model_provider")
|
||||
var tbl ccSwitchCfg
|
||||
if provs := root.obj("model_providers"); provs != nil {
|
||||
if tbl = provs.obj(id); tbl == nil && len(provs) == 1 {
|
||||
for _, v := range provs {
|
||||
tbl, _ = v.(map[string]any)
|
||||
}
|
||||
}
|
||||
}
|
||||
if tbl != nil {
|
||||
s.endpoint = tbl.str("base_url")
|
||||
if s.key == "" {
|
||||
s.key = tbl.str("experimental_bearer_token")
|
||||
}
|
||||
switch tbl.str("wire_api") {
|
||||
case "chat":
|
||||
s.format = "openai_chat"
|
||||
case "responses":
|
||||
s.format = "openai_responses"
|
||||
}
|
||||
if s.key == "" && tbl.str("env_key") != "" {
|
||||
return s, errorf("the ccswitch link gives its key through the environment variable %s, which a link can't read: add the key yourself", tbl.str("env_key"))
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// testdata/ccswitch_links.txt holds CC Switch's own example links, copied
|
||||
// as written from its repository (deplink.html and the site integration
|
||||
// guide at 3c76d3b), one per line.
|
||||
func ccSwitchLinks(t *testing.T) []string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile("testdata/ccswitch_links.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out []string
|
||||
for _, l := range strings.Split(string(b), "\n") {
|
||||
if strings.TrimSpace(l) != "" {
|
||||
out = append(out, l)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestCCSwitchOwnExamples(t *testing.T) {
|
||||
type want struct {
|
||||
Name, Chat, Responses, Anthropic, Gemini, Key string
|
||||
Models []string
|
||||
}
|
||||
got := map[string]want{}
|
||||
n := 0
|
||||
for _, l := range ccSwitchLinks(t) {
|
||||
p, err := ParseImport(l)
|
||||
if !strings.Contains(l, "resource=provider") {
|
||||
// prompts, MCP servers and skills are not providers
|
||||
if err == nil || !strings.Contains(err.Error(), "providers") {
|
||||
t.Errorf("%.60s: %v", l, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("%.90s: %v", l, err)
|
||||
continue
|
||||
}
|
||||
n++
|
||||
if p.ID != "example-ai" && p.ID != "example-gemini" {
|
||||
t.Errorf("%.90s: id %q", l, p.ID)
|
||||
}
|
||||
app := l[strings.Index(l, "app=")+4:]
|
||||
app = app[:strings.IndexByte(app, '&')]
|
||||
got[app+"/"+map[bool]string{true: "config", false: "params"}[strings.Contains(l, "config=")]+"/"+p.Name+p.Key+strings.Join(p.Models, ",")] = want{p.Name, p.Chat, p.Responses, p.Anthropic, p.Gemini, p.Key, p.Models}
|
||||
}
|
||||
if n != 11 {
|
||||
t.Fatalf("%d provider links in the examples", n)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
key string
|
||||
w want
|
||||
}{
|
||||
// endpoint, apiKey: claude's address is Anthropic's
|
||||
{"claude/params/Example AIsk-test-key123", want{Name: "Example AI", Anthropic: "https://api.example.com", Key: "sk-test-key123"}},
|
||||
// the config's env, with its three tiers
|
||||
{"claude/config/Example AIsk-test-key123example-chat,example-fast,example-pro", want{Name: "Example AI", Anthropic: "https://api.example.com", Key: "sk-test-key123", Models: []string{"example-chat", "example-fast", "example-pro"}}},
|
||||
// the key in the URL, the address in the config
|
||||
{"claude/config/Example AIsk-test-key123", want{Name: "Example AI", Anthropic: "https://api.example.com", Key: "sk-test-key123"}},
|
||||
// codex: config.toml's provider table, wire_api responses
|
||||
{"codex/config/Example AIsk-test-key123example-coder", want{Name: "Example AI", Responses: "https://api.example.com/v1", Key: "sk-test-key123", Models: []string{"example-coder"}}},
|
||||
{"codex/params/Example AIsk-test-key123", want{Name: "Example AI", Responses: "https://api.example.com/v1", Key: "sk-test-key123"}},
|
||||
{"gemini/config/Example GeminiAIzaSy-test-key123", want{Name: "Example Gemini", Gemini: "https://api.example.com", Key: "AIzaSy-test-key123"}},
|
||||
// apiFormat names the API an app of any kind speaks
|
||||
{"opencode/params/Example AIsk-test-key123example-chat", want{Name: "Example AI", Anthropic: "https://api.example.com/v1", Key: "sk-test-key123", Models: []string{"example-chat"}}},
|
||||
{"pi/params/Example AIsk-test-key123example-chat", want{Name: "Example AI", Chat: "https://api.example.com/v1", Key: "sk-test-key123", Models: []string{"example-chat"}}},
|
||||
} {
|
||||
if g, ok := got[c.key]; !ok {
|
||||
t.Errorf("no example gave %q; have %v", c.key, got)
|
||||
} else if !reflect.DeepEqual(g, c.w) {
|
||||
t.Errorf("%s:\n got %+v\nwant %+v", c.key, g, c.w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCCSwitchIconAndUsageDropped(t *testing.T) {
|
||||
for _, l := range ccSwitchLinks(t) {
|
||||
if !strings.Contains(l, "iconUrl=") {
|
||||
continue
|
||||
}
|
||||
p, err := ParseImport(l)
|
||||
if err != nil || p.IconURL == "" {
|
||||
t.Fatalf("iconUrl: %q, %v", p.IconURL, err)
|
||||
}
|
||||
}
|
||||
// a usage script (CC Switch's balance query) is code: never taken
|
||||
p, err := ParseImport("ccswitch://v1/import?resource=provider&app=claude&name=x&endpoint=https%3A%2F%2Fa.example&usageScript=KHsKfSk%3D&usageEnabled=true&usageBaseUrl=https%3A%2F%2Fevil.example")
|
||||
if err != nil || p.BalanceURL != "" {
|
||||
t.Fatalf("%+v %v", p, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCCSwitchRefused(t *testing.T) {
|
||||
const base = "ccswitch://v1/import?resource=provider&app=claude&name=x&endpoint=https%3A%2F%2Fa.example"
|
||||
for name, c := range map[string]struct{ link, why string }{
|
||||
"other version": {strings.Replace(base, "//v1/", "//v2/", 1), "v1"},
|
||||
"other path": {strings.Replace(base, "/import?", "/export?", 1), "/import"},
|
||||
"no resource": {strings.Replace(base, "resource=provider&", "", 1), "resource"},
|
||||
"unknown app": {strings.Replace(base, "app=claude", "app=nope", 1), "app"},
|
||||
"no name": {strings.Replace(base, "name=x&", "", 1), "name"},
|
||||
"plain http": {strings.Replace(base, "https", "http", 1), "https"},
|
||||
"javascript": {strings.Replace(base, "https%3A%2F%2Fa.example", "javascript%3Aalert(1)", 1), "base URL"},
|
||||
"file": {strings.Replace(base, "https%3A%2F%2Fa.example", "file%3A%2F%2F%2Fetc%2Fpasswd", 1), "base URL"},
|
||||
"bad format": {base + "&apiFormat=grpc", "apiFormat"},
|
||||
"remote config": {base + "&configUrl=https%3A%2F%2Fa.example%2Fc.json", "configUrl"},
|
||||
"config not base64": {base + "&config=%25%25%25", "base64"},
|
||||
"config not json": {base + "&config=bm90IGpzb24", "json"},
|
||||
"config huge": {base + "&config=" + strings.Repeat("A", 300<<10), "large"},
|
||||
"claude no env": {base + "&config=e30", "env"},
|
||||
"key with newline": {base + "&apiKey=sk%0Aevil", "key"},
|
||||
"no address": {"ccswitch://v1/import?resource=provider&app=claude&name=x", "base URL"},
|
||||
"codex env_key": {"ccswitch://v1/import?resource=provider&app=codex&name=x&config=" +
|
||||
b64(`{"config":"model_provider=\"p\"\n[model_providers.p]\nbase_url=\"https://a.example/v1\"\nenv_key=\"HOME_SECRET\""}`), "HOME_SECRET"},
|
||||
"name only a symbol": {"ccswitch://v1/import?resource=provider&app=claude&name=%2A%2A&endpoint=https%3A%2F%2Fa.example", "id"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
p, err := ParseImport(c.link)
|
||||
if err == nil {
|
||||
t.Fatalf("accepted: %+v", p)
|
||||
}
|
||||
if !strings.Contains(err.Error(), c.why) {
|
||||
t.Fatalf("%q does not say %q", err, c.why)
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, err := ParseImport("ccswitch://v1/import?resource=provider&app=claude&name=x&endpoint=https%3A%2F%2Fa.example&homepage=javascript%3Aalert(1)"); err != nil {
|
||||
t.Fatalf("a bad homepage turned the link away: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// a ccswitch link is as safe as a magpie one: the balance host rule and
|
||||
// the id rules are the shared ones
|
||||
func TestCCSwitchNamedAsSubscription(t *testing.T) {
|
||||
p, err := ParseImport("CCSWITCH://V1/import?resource=provider&app=claude&name=claude&endpoint=https%3A%2F%2Fa.example")
|
||||
if err != nil || p.ID == "claude" {
|
||||
t.Fatalf("%+v %v", p, err)
|
||||
}
|
||||
}
|
||||
|
||||
func b64(s string) string {
|
||||
const a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
||||
var out []byte
|
||||
for i := 0; i < len(s); i += 3 {
|
||||
var v uint
|
||||
n := 0
|
||||
for j := 0; j < 3; j++ {
|
||||
v <<= 8
|
||||
if i+j < len(s) {
|
||||
v |= uint(s[i+j])
|
||||
n++
|
||||
}
|
||||
}
|
||||
for j := 0; j <= n; j++ {
|
||||
out = append(out, a[(v>>(18-6*uint(j)))&63])
|
||||
}
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
@@ -53,13 +53,6 @@ const Scheme = "magpie"
|
||||
// ParseImport reads an import link into the provider it describes.
|
||||
func ParseImport(link string) (Provider, error) {
|
||||
u, err := url.Parse(strings.TrimSpace(link))
|
||||
if err == nil && strings.EqualFold(u.Scheme, CCSwitchScheme) {
|
||||
q, err := ccSwitchQuery(u)
|
||||
if err != nil {
|
||||
return Provider{}, err
|
||||
}
|
||||
return importFromQuery(q)
|
||||
}
|
||||
if err != nil || !strings.EqualFold(u.Scheme, Scheme) {
|
||||
return Provider{}, errors.New("not a magpie:// link")
|
||||
}
|
||||
@@ -70,14 +63,7 @@ func ParseImport(link string) (Provider, error) {
|
||||
if action != "import" {
|
||||
return Provider{}, errorf("magpie://%s is not something magpie knows; links start magpie://import?", action)
|
||||
}
|
||||
return importFromQuery(u.Query())
|
||||
}
|
||||
|
||||
// importFromQuery is ParseImport after the link's shape is known: q holds
|
||||
// the parameters in the list above, from a magpie:// link or translated from
|
||||
// a ccswitch:// one (ccSwitchQuery).
|
||||
func importFromQuery(q url.Values) (Provider, error) {
|
||||
var err error
|
||||
q := u.Query()
|
||||
get := func(k string) string { return strings.TrimSpace(q.Get(k)) }
|
||||
|
||||
var p Provider
|
||||
|
||||
@@ -16,9 +16,8 @@ package provider
|
||||
// learned (internal/fx, fetched behind the page and cached), and while it
|
||||
// has never learned one what is left is unknown, never counted at a guess.
|
||||
// It may refill (the same user: $10 a month from the 1st): at each refill,
|
||||
// at midnight local time on a day of the month or of the week, or every
|
||||
// midnight (Kelen_Yc on X: a relay key with a daily allowance), the
|
||||
// amount typed is whole again and the spend counted from then.
|
||||
// at midnight local time on a day of the month or of the week, the amount
|
||||
// typed is whole again and the spend counted from then.
|
||||
|
||||
// It may have credit that expires on top of it (the same user: some
|
||||
// vendors split a balance into money that stays and credit good until a
|
||||
@@ -119,7 +118,7 @@ func (b OwnBalance) Amount() (float64, string) {
|
||||
|
||||
// Refill is when a balance typed is whole again: at midnight, local time,
|
||||
// on Day of each month (1–31, a month without that day on its last) or of
|
||||
// each week (1 Monday to 7 Sunday), or each day (Day 0).
|
||||
// each week (1 Monday to 7 Sunday).
|
||||
type Refill struct {
|
||||
Every string `json:"every"`
|
||||
Day int `json:"day"`
|
||||
@@ -129,16 +128,12 @@ type Refill struct {
|
||||
const (
|
||||
RefillMonth = "month"
|
||||
RefillWeek = "week"
|
||||
RefillDay = "day"
|
||||
)
|
||||
|
||||
// Last is the last refill at or before now, in now's location.
|
||||
func (r Refill) Last(now time.Time) time.Time {
|
||||
y, m, d := now.Date()
|
||||
loc := now.Location()
|
||||
if r.Every == RefillDay {
|
||||
return time.Date(y, m, d, 0, 0, 0, 0, loc)
|
||||
}
|
||||
if r.Every == RefillWeek {
|
||||
iso := (int(now.Weekday())+6)%7 + 1
|
||||
return time.Date(y, m, d-(iso-r.Day+7)%7, 0, 0, 0, 0, loc)
|
||||
@@ -154,9 +149,6 @@ func (r Refill) Last(now time.Time) time.Time {
|
||||
func (r Refill) Next(now time.Time) time.Time {
|
||||
l := r.Last(now)
|
||||
y, m, d := l.Date()
|
||||
if r.Every == RefillDay {
|
||||
return time.Date(y, m, d+1, 0, 0, 0, 0, l.Location())
|
||||
}
|
||||
if r.Every == RefillWeek {
|
||||
return time.Date(y, m, d+7, 0, 0, 0, 0, l.Location())
|
||||
}
|
||||
@@ -175,18 +167,14 @@ func (r Refill) check() error {
|
||||
switch {
|
||||
case r.Every == RefillMonth && r.Day >= 1 && r.Day <= 31:
|
||||
case r.Every == RefillWeek && r.Day >= 1 && r.Day <= 7:
|
||||
case r.Every == RefillDay && r.Day == 0:
|
||||
default:
|
||||
return fmt.Errorf("a balance refills each month on a day from 1 to 31, each week on a day from 1 (Monday) to 7 (Sunday), or each day (day 0), not %s %d", r.Every, r.Day)
|
||||
return fmt.Errorf("a balance refills each month on a day from 1 to 31, or each week on a day from 1 (Monday) to 7 (Sunday), not %s %d", r.Every, r.Day)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// String is r as the CLI takes and shows it: monthly:1, weekly:mon, daily.
|
||||
// String is r as the CLI takes and shows it: monthly:1, weekly:mon.
|
||||
func (r Refill) String() string {
|
||||
if r.Every == RefillDay {
|
||||
return "daily"
|
||||
}
|
||||
if r.Every == RefillWeek {
|
||||
return "weekly:" + strings.ToLower(time.Weekday(r.Day % 7).String()[:3])
|
||||
}
|
||||
@@ -758,8 +746,8 @@ func ParseOwnBalance(amount string) (*OwnBalance, error) {
|
||||
}
|
||||
|
||||
// ParseRefill reads a refill as the CLI takes it: monthly (on the 1st),
|
||||
// monthly:15, weekly (on Monday), weekly:fri or weekly:5, daily (each
|
||||
// midnight); off or never for none (nil).
|
||||
// monthly:15, weekly (on Monday), weekly:fri or weekly:5; off or never
|
||||
// for none (nil).
|
||||
func ParseRefill(s string) (*Refill, error) {
|
||||
a := strings.ToLower(strings.TrimSpace(s))
|
||||
switch a {
|
||||
@@ -767,7 +755,7 @@ func ParseRefill(s string) (*Refill, error) {
|
||||
return nil, nil
|
||||
}
|
||||
every, day, _ := strings.Cut(a, ":")
|
||||
bad := fmt.Errorf("a refill is monthly[:day 1-31], weekly[:mon…sun], daily or off, not %q", s)
|
||||
bad := fmt.Errorf("a refill is monthly[:day 1-31], weekly[:mon…sun] or off, not %q", s)
|
||||
var r Refill
|
||||
switch every {
|
||||
case "monthly", "month", "m":
|
||||
@@ -779,11 +767,6 @@ func ParseRefill(s string) (*Refill, error) {
|
||||
}
|
||||
r.Day = n
|
||||
}
|
||||
case "daily", "day", "d":
|
||||
if day != "" {
|
||||
return nil, bad
|
||||
}
|
||||
r = Refill{Every: RefillDay}
|
||||
case "weekly", "week", "w":
|
||||
r = Refill{Every: RefillWeek, Day: 1}
|
||||
if day != "" {
|
||||
|
||||
@@ -344,7 +344,7 @@ func TestTypedBalanceRefills(t *testing.T) {
|
||||
t.Fatalf("no refill: %+v", e)
|
||||
}
|
||||
// refused: a refill that isn't one; one for a key with no balance
|
||||
for _, bad := range []Refill{{RefillMonth, 0}, {RefillMonth, 32}, {RefillWeek, 8}, {"year", 1}, {RefillDay, 1}} {
|
||||
for _, bad := range []Refill{{RefillMonth, 0}, {RefillMonth, 32}, {RefillWeek, 8}, {"year", 1}} {
|
||||
if err := SetKeyBalanceRefill("monthly", keyID("sk-r"), &bad); err == nil {
|
||||
t.Errorf("%+v taken", bad)
|
||||
}
|
||||
@@ -357,47 +357,6 @@ func TestTypedBalanceRefills(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A balance that refills each day (Kelen_Yc on X: a relay key with a
|
||||
// daily allowance) is whole again at local midnight, not UTC's: held in
|
||||
// UTC+14 and UTC-11, where the local day and UTC's differ, the spend is
|
||||
// counted from the midnight just past and the next is the one after.
|
||||
func TestTypedBalanceRefillsDaily(t *testing.T) {
|
||||
probeSandbox(t)
|
||||
probeLocal = false
|
||||
asked := spentStub(t, map[string]float64{keyID("sk-d"): 2})
|
||||
if err := Save(Provider{ID: "daily", Name: "Daily", Chat: "http://127.0.0.1:1/v1", Key: "sk-d"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, zone := range []string{"Pacific/Kiritimati", "Pacific/Pago_Pago", "UTC"} {
|
||||
loc, err := time.LoadLocation(zone)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
typed := time.Date(2026, 11, 12, 9, 0, 0, 0, loc)
|
||||
clockStub(t, typed)
|
||||
if err := SetKeyOwnBalance("daily", keyID("sk-d"), &OwnBalance{USD: 5, Refill: &Refill{Every: RefillDay}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the same local day, a minute before midnight: from when typed
|
||||
clockStub(t, time.Date(2026, 11, 12, 23, 59, 0, 0, loc))
|
||||
p, _ := Find("daily")
|
||||
e, _ := p.OwnBalanceEstimate(keyID("sk-d"))
|
||||
if !e.From.Equal(typed) || *e.Left != 3 || !e.Next.Equal(time.Date(2026, 11, 13, 0, 0, 0, 0, loc)) {
|
||||
t.Fatalf("%s before midnight: from %v next %v left %v", zone, e.From, e.Next, *e.Left)
|
||||
}
|
||||
// a minute past local midnight: whole again, counted from then
|
||||
clockStub(t, time.Date(2026, 11, 13, 0, 1, 0, 0, loc))
|
||||
q := ownCards(t)["daily|"]
|
||||
mid := time.Date(2026, 11, 13, 0, 0, 0, 0, loc)
|
||||
if !q.Estimate.From.Equal(mid) || !asked[keyID("sk-d")].Equal(mid) || q.Balance != "≈$3.00" {
|
||||
t.Fatalf("%s after midnight: %+v from %v, asked from %v", zone, q, q.Estimate.From, asked[keyID("sk-d")])
|
||||
}
|
||||
if !q.Estimate.Next.Equal(time.Date(2026, 11, 14, 0, 0, 0, 0, loc)) {
|
||||
t.Errorf("%s next refill %v", zone, q.Estimate.Next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// When each refill falls: on the day, at local midnight; a month without
|
||||
// the day refills on its last; a week from Monday (1) to Sunday (7).
|
||||
func TestRefillDays(t *testing.T) {
|
||||
@@ -422,12 +381,6 @@ func TestRefillDays(t *testing.T) {
|
||||
{Refill{RefillWeek, 1}, at(2026, 11, 8, 10), at(2026, 11, 2, 0), at(2026, 11, 9, 0)},
|
||||
{Refill{RefillWeek, 7}, at(2026, 11, 8, 10), at(2026, 11, 8, 0), at(2026, 11, 15, 0)},
|
||||
{Refill{RefillWeek, 5}, at(2026, 11, 8, 10), at(2026, 11, 6, 0), at(2026, 11, 13, 0)},
|
||||
// each day (Kelen_Yc on X): the midnight before, the one after,
|
||||
// across a month's and a year's end
|
||||
{Refill{RefillDay, 0}, at(2026, 11, 8, 10), at(2026, 11, 8, 0), at(2026, 11, 9, 0)},
|
||||
{Refill{RefillDay, 0}, at(2026, 11, 8, 0), at(2026, 11, 8, 0), at(2026, 11, 9, 0)},
|
||||
{Refill{RefillDay, 0}, at(2026, 11, 30, 23), at(2026, 11, 30, 0), at(2026, 12, 1, 0)},
|
||||
{Refill{RefillDay, 0}, at(2026, 12, 31, 23), at(2026, 12, 31, 0), at(2027, 1, 1, 0)},
|
||||
} {
|
||||
if l, n := c.r.Last(c.now), c.r.Next(c.now); !l.Equal(c.last) || !n.Equal(c.next) {
|
||||
t.Errorf("%+v at %v: last %v next %v, want %v and %v", c.r, c.now, l, n, c.last, c.next)
|
||||
@@ -463,7 +416,7 @@ func TestOwnBalanceParsedInYuanAndRefill(t *testing.T) {
|
||||
}
|
||||
}
|
||||
for in, want := range map[string]Refill{"monthly": {RefillMonth, 1}, "monthly:15": {RefillMonth, 15}, "weekly": {RefillWeek, 1},
|
||||
"weekly:fri": {RefillWeek, 5}, "weekly:Sunday": {RefillWeek, 7}, "weekly:3": {RefillWeek, 3}, "daily": {RefillDay, 0}, "Day": {RefillDay, 0}} {
|
||||
"weekly:fri": {RefillWeek, 5}, "weekly:Sunday": {RefillWeek, 7}, "weekly:3": {RefillWeek, 3}} {
|
||||
if r, err := ParseRefill(in); err != nil || r == nil || *r != want {
|
||||
t.Errorf("%q: %+v %v, want %+v", in, r, err, want)
|
||||
}
|
||||
@@ -474,18 +427,15 @@ func TestOwnBalanceParsedInYuanAndRefill(t *testing.T) {
|
||||
if r, err := ParseRefill("off"); err != nil || r != nil {
|
||||
t.Errorf("off: %+v %v", r, err)
|
||||
}
|
||||
for _, in := range []string{"monthly:0", "monthly:32", "monthly:x", "weekly:x", "yearly", "--help", "daily:1"} {
|
||||
for _, in := range []string{"monthly:0", "monthly:32", "monthly:x", "weekly:x", "yearly", "--help"} {
|
||||
if _, err := ParseRefill(in); err == nil {
|
||||
t.Errorf("%q taken", in)
|
||||
}
|
||||
}
|
||||
n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Refill: &Refill{"year", 1}}, "b": {USD: 5, Refill: &Refill{RefillDay, 0}}})
|
||||
n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Refill: &Refill{"year", 1}}})
|
||||
if n["a"].USD != 5 || n["a"].Refill != nil {
|
||||
t.Errorf("a refill that isn't one, written by hand: %+v", n)
|
||||
}
|
||||
if n["b"].Refill == nil || *n["b"].Refill != (Refill{RefillDay, 0}) {
|
||||
t.Errorf("a daily refill was dropped as read back: %+v", n["b"])
|
||||
}
|
||||
}
|
||||
|
||||
// spendAt stubs usage.KeySpent with calls at given times: what the key
|
||||
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
ccswitch://v1/import?resource=mcp&apps=claude%2Ccodex&config=eyJtY3BTZXJ2ZXJzIjp7ImNvbnRleHQ3Ijp7ImNvbW1hbmQiOiJucHgiLCJhcmdzIjpbIi15IiwiQHVwc3Rhc2gvY29udGV4dDctbWNwIl0sImVudiI6e319LCJzZXF1ZW50aWFsLXRoaW5raW5nIjp7ImNvbW1hbmQiOiJucHgiLCJhcmdzIjpbIi15IiwiQG1vZGVsY29udGV4dHByb3RvY29sL3NlcnZlci1zZXF1ZW50aWFsLXRoaW5raW5nIl0sImVudiI6e319fX0%3D
|
||||
ccswitch://v1/import?resource=prompt&app=claude&name=%E4%BB%A3%E7%A0%81%E5%AE%A1%E6%9F%A5%E4%B8%93%E5%AE%B6&content=IyDku6PnoIHlrqHmn6XkuJPlrrYKCuS9oOaYr%2BS4gOS9jeaciee7j%2BmqjOeahOS7o%2BeggeWuoeafpeWRmOOAguWuoeafpeS7o%2BeggeaXtu%2B8jOWFiOaMh%2BWHuuS8muWvvOiHtOmUmeivr%2BeahOmXrumimO%2B8jOWGjee7meWHuuS%2FruaUueW7uuiuruOAgg%3D%3D&description=%E4%B8%93%E6%B3%A8%E4%BB%A3%E7%A0%81%E8%B4%A8%E9%87%8F
|
||||
ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&apiKey=sk-test-key123&configFormat=json&config=eyJlbnYiOnsiQU5USFJPUElDX0JBU0VfVVJMIjoiaHR0cHM6Ly9hcGkuZXhhbXBsZS5jb20iLCJBUElfVElNRU9VVF9NUyI6IjYwMDAwMCJ9fQ%3D%3D
|
||||
ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&configFormat=json&config=eyJlbnYiOnsiQU5USFJPUElDX0FVVEhfVE9LRU4iOiJzay10ZXN0LWtleTEyMyIsIkFOVEhST1BJQ19CQVNFX1VSTCI6Imh0dHBzOi8vYXBpLmV4YW1wbGUuY29tIiwiQU5USFJPUElDX01PREVMIjoiZXhhbXBsZS1jaGF0IiwiQU5USFJPUElDX0RFRkFVTFRfSEFJS1VfTU9ERUwiOiJleGFtcGxlLWZhc3QiLCJBTlRIUk9QSUNfREVGQVVMVF9TT05ORVRfTU9ERUwiOiJleGFtcGxlLWNoYXQiLCJBTlRIUk9QSUNfREVGQVVMVF9PUFVTX01PREVMIjoiZXhhbXBsZS1wcm8ifX0%3D
|
||||
ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-test-key123&iconUrl=https%3A%2F%2Fraw.githubusercontent.com%2Ffarion1231%2Fcc-switch%2Fmain%2Fsrc-tauri%2Ficons%2F128x128.png
|
||||
ccswitch://v1/import?resource=provider&app=claude&name=Example+AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-test-key123&usageScript=KHsKICByZXF1ZXN0OiB7CiAgICB1cmw6ICJ7e2Jhc2VVcmx9fS91c2VyL2JhbGFuY2UiLAogICAgbWV0aG9kOiAiR0VUIiwKICAgIGhlYWRlcnM6IHsKICAgICAgIkF1dGhvcml6YXRpb24iOiAiQmVhcmVyIHt7YXBpS2V5fX0iCiAgICB9CiAgfSwKICBleHRyYWN0b3I6IGZ1bmN0aW9uIChyZXNwb25zZSkgewogICAgaWYgKHJlc3BvbnNlLmVycm9yKSB7CiAgICAgIHJldHVybiB7IGlzVmFsaWQ6IGZhbHNlLCBpbnZhbGlkTWVzc2FnZTogU3RyaW5nKHJlc3BvbnNlLmVycm9yLm1lc3NhZ2UgfHwgcmVzcG9uc2UuZXJyb3IpIH07CiAgICB9CiAgICByZXR1cm4gewogICAgICByZW1haW5pbmc6IE51bWJlcihyZXNwb25zZS5iYWxhbmNlKSwKICAgICAgdW5pdDogIlVTRCIKICAgIH07CiAgfQp9KQ
|
||||
ccswitch://v1/import?resource=provider&app=claude&name=Example+AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-test-key123&usageScript=KHsKICByZXF1ZXN0OiB7CiAgICB1cmw6ICJ7e2Jhc2VVcmx9fSIucmVwbGFjZSgvXC8rJC8sICIiKS5yZXBsYWNlKC9cL3YxJC8sICIiKSArICIvdjEvdXNhZ2UiLAogICAgbWV0aG9kOiAiR0VUIiwKICAgIGhlYWRlcnM6IHsKICAgICAgIkF1dGhvcml6YXRpb24iOiAiQmVhcmVyIHt7YXBpS2V5fX0iLAogICAgICAiVXNlci1BZ2VudCI6ICJjYy1zd2l0Y2gvMS4wIgogICAgfQogIH0sCiAgZXh0cmFjdG9yOiBmdW5jdGlvbiAocmVzcG9uc2UpIHsKICAgIHZhciBxdW90YSA9IHJlc3BvbnNlLnF1b3RhIHx8IHt9OwogICAgdmFyIHJlc3VsdCA9IHsKICAgICAgaXNWYWxpZDogcmVzcG9uc2UuaXNWYWxpZCAhPT0gZmFsc2UsCiAgICAgIHVuaXQ6IHJlc3BvbnNlLnVuaXQgfHwgcXVvdGEudW5pdCB8fCAiVVNEIgogICAgfTsKICAgIGlmICh0eXBlb2YgcmVzcG9uc2UucGxhbk5hbWUgPT09ICJzdHJpbmciKSByZXN1bHQucGxhbk5hbWUgPSByZXNwb25zZS5wbGFuTmFtZTsKICAgIGlmICh0eXBlb2YgcmVzcG9uc2UucmVtYWluaW5nID09PSAibnVtYmVyIiAmJiByZXNwb25zZS5yZW1haW5pbmcgPj0gMCkgewogICAgICByZXN1bHQucmVtYWluaW5nID0gcmVzcG9uc2UucmVtYWluaW5nOwogICAgfQogICAgaWYgKHF1b3RhLmxpbWl0ID4gMCkgewogICAgICByZXN1bHQudXNlZCA9IHF1b3RhLnVzZWQ7CiAgICAgIHJlc3VsdC50b3RhbCA9IHF1b3RhLmxpbWl0OwogICAgfQogICAgaWYgKCFyZXN1bHQuaXNWYWxpZCkgewogICAgICByZXN1bHQuaW52YWxpZE1lc3NhZ2UgPSByZXNwb25zZS5zdGF0dXMKICAgICAgICA%2FIFN0cmluZyhyZXNwb25zZS5zdGF0dXMpCiAgICAgICAgOiAi5p%2Bl6K%2Bi5aSx6LSlIjsKICAgIH0KICAgIHJldHVybiByZXN1bHQ7CiAgfSwKfSk%3D&usageAutoInterval=30
|
||||
ccswitch://v1/import?resource=provider&app=codex&name=Example%20AI&configFormat=json&config=eyJhdXRoIjp7Ik9QRU5BSV9BUElfS0VZIjoic2stdGVzdC1rZXkxMjMifSwiY29uZmlnIjoibW9kZWxfcHJvdmlkZXIgPSBcImV4YW1wbGVcIlxubW9kZWwgPSBcImV4YW1wbGUtY29kZXJcIlxuXG5bbW9kZWxfcHJvdmlkZXJzLmV4YW1wbGVdXG5uYW1lID0gXCJFeGFtcGxlIEFJXCJcbmJhc2VfdXJsID0gXCJodHRwczovL2FwaS5leGFtcGxlLmNvbS92MVwiXG53aXJlX2FwaSA9IFwicmVzcG9uc2VzXCIifQ%3D%3D
|
||||
ccswitch://v1/import?resource=provider&app=codex&name=Example+AI&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-key123&usageScript=KHsKICByZXF1ZXN0OiB7CiAgICB1cmw6ICJ7e2Jhc2VVcmx9fS9hcGkvdXNlci9zZWxmIiwKICAgIG1ldGhvZDogIkdFVCIsCiAgICBoZWFkZXJzOiB7CiAgICAgICJBdXRob3JpemF0aW9uIjogIkJlYXJlciB7e2FjY2Vzc1Rva2VufX0iLAogICAgICAiTmV3LUFwaS1Vc2VyIjogInt7dXNlcklkfX0iCiAgICB9CiAgfSwKICBleHRyYWN0b3I6IGZ1bmN0aW9uIChyZXNwb25zZSkgewogICAgaWYgKHJlc3BvbnNlLnN1Y2Nlc3MgJiYgcmVzcG9uc2UuZGF0YSkgewogICAgICByZXR1cm4gewogICAgICAgIHBsYW5OYW1lOiByZXNwb25zZS5kYXRhLmdyb3VwLAogICAgICAgIHJlbWFpbmluZzogcmVzcG9uc2UuZGF0YS5xdW90YSAvIDUwMDAwMCwKICAgICAgICB1c2VkOiByZXNwb25zZS5kYXRhLnVzZWRfcXVvdGEgLyA1MDAwMDAsCiAgICAgICAgdW5pdDogIlVTRCIKICAgICAgfTsKICAgIH0KICAgIHJldHVybiB7IGlzVmFsaWQ6IGZhbHNlLCBpbnZhbGlkTWVzc2FnZTogU3RyaW5nKHJlc3BvbnNlLm1lc3NhZ2UgfHwgIuafpeivouWksei0pSIpIH07CiAgfQp9KQ&usageBaseUrl=https%3A%2F%2Fapi.example.com&usageAccessToken=test-access-token&usageUserId=1&usageAutoInterval=30
|
||||
ccswitch://v1/import?resource=provider&app=gemini&name=Example%20Gemini&configFormat=json&config=eyJHRU1JTklfQVBJX0tFWSI6IkFJemFTeS10ZXN0LWtleTEyMyIsIkdPT0dMRV9HRU1JTklfQkFTRV9VUkwiOiJodHRwczovL2FwaS5leGFtcGxlLmNvbSJ9
|
||||
ccswitch://v1/import?resource=provider&app=opencode&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-key123&apiFormat=anthropic&model=example-chat
|
||||
ccswitch://v1/import?resource=provider&app=pi&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-key123&apiFormat=openai_chat&model=example-chat
|
||||
ccswitch://v1/import?resource=skill&repo=example%2Fclaude-skills&branch=main
|
||||
ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-xxxx
|
||||
@@ -1,7 +1,6 @@
|
||||
package uninstall
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -22,33 +21,26 @@ func dataHome() string {
|
||||
// unregisterScheme takes out the desktop entry the app made for magpie://
|
||||
// links while it runs exe, or an exe that is gone, and its icon with it.
|
||||
func unregisterScheme(exe string) error {
|
||||
_, err := removeEntry("magpie-ccswitch.desktop", exe)
|
||||
gone, err2 := removeEntry("magpie.desktop", exe)
|
||||
if gone {
|
||||
_ = os.Remove(filepath.Join(dataHome(), "icons", "hicolor", "256x256", "apps", "magpie.png"))
|
||||
}
|
||||
return errors.Join(err, err2)
|
||||
}
|
||||
|
||||
// removeEntry takes out one of the app's desktop entries while it runs exe,
|
||||
// or an exe that is gone.
|
||||
func removeEntry(name, exe string) (bool, error) {
|
||||
entry := filepath.Join(dataHome(), "applications", name)
|
||||
entry := filepath.Join(dataHome(), "applications", "magpie.desktop")
|
||||
b, err := os.ReadFile(entry)
|
||||
if err != nil {
|
||||
return false, nil
|
||||
return nil
|
||||
}
|
||||
for _, l := range strings.Split(string(b), "\n") {
|
||||
if run, ok := strings.CutPrefix(l, "Exec="); ok {
|
||||
run = strings.TrimSuffix(run, " %u")
|
||||
if run != exe {
|
||||
if _, err := os.Stat(run); err == nil {
|
||||
return false, nil // another magpie's
|
||||
return nil // another magpie's
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true, os.Remove(entry)
|
||||
if err := os.Remove(entry); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = os.Remove(filepath.Join(dataHome(), "icons", "hicolor", "256x256", "apps", "magpie.png"))
|
||||
return nil
|
||||
}
|
||||
|
||||
// webData is WebKitGTK's folder for the app's pages (named after the
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package uninstall
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -13,14 +12,10 @@ import (
|
||||
|
||||
const schemeKey = `Software\Classes\magpie`
|
||||
|
||||
// unregisterScheme takes out the magpie:// and ccswitch:// handlers the app
|
||||
// registered while they open exe, or an exe that is gone.
|
||||
// unregisterScheme takes out the magpie:// handler the app registered
|
||||
// while it opens exe, or an exe that is gone.
|
||||
func unregisterScheme(exe string) error {
|
||||
return errors.Join(removeSchemeKey(schemeKey, exe), removeSchemeKey(`Software\Classes\ccswitch`, exe))
|
||||
}
|
||||
|
||||
func removeSchemeKey(key, exe string) error {
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, key+`\shell\open\command`, registry.QUERY_VALUE)
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, schemeKey+`\shell\open\command`, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -32,7 +27,7 @@ func removeSchemeKey(key, exe string) error {
|
||||
}
|
||||
}
|
||||
for _, sub := range []string{`\shell\open\command`, `\shell\open`, `\shell`, `\DefaultIcon`, ``} {
|
||||
if err := registry.DeleteKey(registry.CURRENT_USER, key+sub); err != nil && err != registry.ErrNotExist {
|
||||
if err := registry.DeleteKey(registry.CURRENT_USER, schemeKey+sub); err != nil && err != registry.ErrNotExist {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
|
||||
// A session file's chunk is named in the heatmap's key by a digest of its
|
||||
// rows (sourceDigest), and each start hashed every chunk's rows again to
|
||||
// make them: ~0.15 s of CPU on a real history, and every chunk unpacked
|
||||
// for it (#2278). A chunk's serial names its file as read under one root
|
||||
// and meta (sourceSerial), the same in every run, so the digests are kept
|
||||
// on disk by serial, under the code that makes the rows
|
||||
// (requestDiskBinary): another build's rows are hashed again.
|
||||
|
||||
// sourceDigestsDisk is what was read of heat-digests.bin. Under
|
||||
// sourceDigests' lock.
|
||||
var sourceDigestsDisk struct {
|
||||
path string // where kept was read from
|
||||
kept digestList // as read: no map of 17k entries beside sourceDigests'
|
||||
dirty bool // a digest was made that isn't on disk
|
||||
}
|
||||
|
||||
// sourceDigestsHashed counts the chunks sourceDigest hashed, for tests.
|
||||
var sourceDigestsHashed int
|
||||
|
||||
func sourceDigestsPath() string {
|
||||
return filepath.Join(filepath.Dir(sessions.CachePath()), "heat-digests.bin")
|
||||
}
|
||||
|
||||
const sourceDigestsMagic = "magpie-heat-digests-2\n"
|
||||
|
||||
// digestList is serials and their digests, each 8+32 bytes, in the
|
||||
// serials' order.
|
||||
type digestList []byte
|
||||
|
||||
const digestLen = 8 + sha256.Size
|
||||
|
||||
func (l digestList) len() int { return len(l) / digestLen }
|
||||
|
||||
func (l digestList) at(i int) (uint64, []byte) {
|
||||
e := l[i*digestLen : (i+1)*digestLen]
|
||||
return binary.LittleEndian.Uint64(e), e[8:]
|
||||
}
|
||||
|
||||
func (l digestList) get(serial uint64) (sum [sha256.Size]byte, ok bool) {
|
||||
i := sort.Search(l.len(), func(i int) bool { s, _ := l.at(i); return s >= serial })
|
||||
if i == l.len() {
|
||||
return sum, false
|
||||
}
|
||||
s, b := l.at(i)
|
||||
if s != serial {
|
||||
return sum, false
|
||||
}
|
||||
copy(sum[:], b)
|
||||
return sum, true
|
||||
}
|
||||
|
||||
// sourceDigestsLoad reads the kept digests, once for each place they are
|
||||
// kept in. A file that can't be read, or was written by other row code,
|
||||
// is nothing kept. Under sourceDigests' lock.
|
||||
func sourceDigestsLoad() {
|
||||
p := sourceDigestsPath()
|
||||
if sourceDigestsDisk.path == p {
|
||||
return
|
||||
}
|
||||
sourceDigestsDisk.path, sourceDigestsDisk.kept, sourceDigestsDisk.dirty = p, nil, false
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
sourceDigestsDisk.kept = decodeSourceDigests(b, requestDiskBinary())
|
||||
}
|
||||
|
||||
// decodeSourceDigests is b's digests when b was written for code, nil
|
||||
// when not, when b is cut short or out of order.
|
||||
func decodeSourceDigests(b []byte, code string) digestList {
|
||||
if !bytes.HasPrefix(b, []byte(sourceDigestsMagic)) {
|
||||
return nil
|
||||
}
|
||||
b = b[len(sourceDigestsMagic):]
|
||||
n, k := binary.Uvarint(b)
|
||||
if k <= 0 || uint64(len(b)-k) < n || string(b[k:k+int(n)]) != code {
|
||||
return nil
|
||||
}
|
||||
l := digestList(b[k+int(n):])
|
||||
if len(l)%digestLen != 0 {
|
||||
return nil
|
||||
}
|
||||
for i := 1; i < l.len(); i++ {
|
||||
if a, _ := l.at(i - 1); a >= binary.LittleEndian.Uint64(l[i*digestLen:]) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// encodeSourceDigests writes the sets' digests and kept's for code, the
|
||||
// first set's first, at most limit of them.
|
||||
func encodeSourceDigests(code string, limit int, kept digestList, sets ...map[uint64][sha256.Size]byte) []byte {
|
||||
type one struct {
|
||||
serial uint64
|
||||
sum []byte
|
||||
}
|
||||
var all []one
|
||||
seen := map[uint64]bool{}
|
||||
for _, s := range sets {
|
||||
for serial, sum := range s {
|
||||
if !seen[serial] && len(all) < limit {
|
||||
seen[serial] = true
|
||||
all = append(all, one{serial, append([]byte(nil), sum[:]...)})
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := 0; i < kept.len() && len(all) < limit; i++ {
|
||||
if serial, sum := kept.at(i); !seen[serial] {
|
||||
all = append(all, one{serial, sum})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(all, func(a, b one) int { return cmp.Compare(a.serial, b.serial) })
|
||||
b := make([]byte, 0, len(sourceDigestsMagic)+binary.MaxVarintLen64+len(code)+len(all)*digestLen)
|
||||
b = append(b, sourceDigestsMagic...)
|
||||
b = binary.AppendUvarint(b, uint64(len(code)))
|
||||
b = append(b, code...)
|
||||
for _, e := range all {
|
||||
b = binary.LittleEndian.AppendUint64(b, e.serial)
|
||||
b = append(b, e.sum...)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// sourceDigestWrites puts the writes in order: one encoded before the
|
||||
// last written is not written over it.
|
||||
var sourceDigestWrites struct {
|
||||
sync.Mutex
|
||||
made, wrote int // generations: under sourceDigests' lock, and under the Mutex
|
||||
}
|
||||
|
||||
// sourceDigestsSave writes the digests of this run, when one was made that
|
||||
// isn't on disk: those of the chunks hashed or used since the last turn
|
||||
// and before it. Encoded under sourceDigests' lock, written behind it, as
|
||||
// heat-v1.json is: once a start, and again when a file changed.
|
||||
func sourceDigestsSave() {
|
||||
d := &sourceDigests
|
||||
d.Lock()
|
||||
if !sourceDigestsDisk.dirty || sourceDigestsDisk.path == "" {
|
||||
d.Unlock()
|
||||
return
|
||||
}
|
||||
sourceDigestsDisk.dirty = false
|
||||
// this run's first, then those kept from before it it hasn't met (a
|
||||
// query of a few files keeps the rest): a file gone falls out once
|
||||
// two turns' worth are made
|
||||
b := encodeSourceDigests(requestDiskBinary(), 2*sourceDigestsKept, sourceDigestsDisk.kept, d.by, d.last)
|
||||
p := sourceDigestsDisk.path
|
||||
w := &sourceDigestWrites
|
||||
w.made++
|
||||
gen := w.made
|
||||
d.Unlock()
|
||||
w.Lock()
|
||||
defer w.Unlock()
|
||||
if gen < w.wrote {
|
||||
return
|
||||
}
|
||||
w.wrote = gen
|
||||
writeFileRenamed(p, b)
|
||||
}
|
||||
|
||||
// writeFileRenamed writes b to p through a temp file renamed over it.
|
||||
func writeFileRenamed(p string, b []byte) {
|
||||
dir := filepath.Dir(p)
|
||||
if os.MkdirAll(dir, 0o700) != nil {
|
||||
return
|
||||
}
|
||||
tmp, err := os.CreateTemp(dir, ".heat-digests-*")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = tmp.Write(b)
|
||||
if cerr := tmp.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err != nil || os.Rename(tmp.Name(), p) != nil {
|
||||
os.Remove(tmp.Name())
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A start takes a session file's chunk's digest from the last run's, kept
|
||||
// by its serial, and hashes its rows only when the file or the row code
|
||||
// changed (#2278).
|
||||
func TestSourceDigestsKeptAcrossStarts(t *testing.T) {
|
||||
pageHome(t)
|
||||
cut := time.Date(2026, 9, 28, 0, 0, 0, 0, time.UTC)
|
||||
d := heatDiskRef{root: "r", meta: "m"}
|
||||
chunk := func(serial uint64, input int) *rowChunk {
|
||||
c := &rowChunk{serial: serial}
|
||||
c.Source.Agent, c.Source.Key, c.Source.Path = "codex", "k", fmt.Sprint("/s/", serial)
|
||||
for i := 1; i <= 3; i++ {
|
||||
c.add(Row{Record: Record{Time: cut.Add(-time.Duration(i) * time.Hour), Agent: "codex", Model: "m", Input: i * input}}, fmt.Sprint("msg", i), int64(i), false)
|
||||
}
|
||||
return c
|
||||
}
|
||||
restart := func() {
|
||||
sourceDigests.Lock()
|
||||
sourceDigests.by, sourceDigests.last = nil, nil
|
||||
sourceDigestsDisk.path, sourceDigestsDisk.kept = "", nil
|
||||
sourceDigests.Unlock()
|
||||
}
|
||||
key := func(cs ...*rowChunk) (string, int) {
|
||||
sourceDigests.Lock()
|
||||
was := sourceDigestsHashed
|
||||
sourceDigests.Unlock()
|
||||
k, ok := heatSettledKey(d, cut, time.Time{}, Filter{}, nil, [3][]*rowChunk{cs}, heatSum{})
|
||||
if !ok {
|
||||
t.Fatal("not named")
|
||||
}
|
||||
sourceDigests.Lock()
|
||||
defer sourceDigests.Unlock()
|
||||
return k, sourceDigestsHashed - was
|
||||
}
|
||||
restart()
|
||||
first, n := key(chunk(1<<63|1, 10), chunk(1<<63|2, 20))
|
||||
if n != 2 {
|
||||
t.Fatalf("a first start hashed %d chunks, want 2", n)
|
||||
}
|
||||
restart()
|
||||
if again, n := key(chunk(1<<63|1, 10), chunk(1<<63|2, 20)); n != 0 || again != first {
|
||||
t.Fatalf("started again, hashed %d chunks, key %s, was %s", n, again, first)
|
||||
}
|
||||
// a start that met one file keeps the other's for the next
|
||||
restart()
|
||||
if _, n := key(chunk(1<<63|1, 10)); n != 0 {
|
||||
t.Fatalf("hashed %d", n)
|
||||
}
|
||||
restart()
|
||||
if _, n := key(chunk(1<<63|3, 30)); n != 1 {
|
||||
t.Fatalf("a new file hashed %d, want 1", n)
|
||||
}
|
||||
restart()
|
||||
if again, n := key(chunk(1<<63|1, 10), chunk(1<<63|2, 20)); n != 0 || again != first {
|
||||
t.Fatalf("after a start of other files, hashed %d chunks, key %s, was %s", n, again, first)
|
||||
}
|
||||
|
||||
// another build's row code: hashed again
|
||||
b, err := os.ReadFile(sourceDigestsPath())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other := encodeSourceDigests(requestDiskBinary()+"x", 10, decodeSourceDigests(b, requestDiskBinary()))
|
||||
if decodeSourceDigests(b, requestDiskBinary()).len() != 3 {
|
||||
t.Fatalf("kept %d, want 3", decodeSourceDigests(b, requestDiskBinary()).len())
|
||||
}
|
||||
if err := os.WriteFile(sourceDigestsPath(), other, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restart()
|
||||
if _, n := key(chunk(1<<63|1, 10), chunk(1<<63|2, 20)); n != 2 {
|
||||
t.Fatalf("other row code: hashed %d chunks, want 2", n)
|
||||
}
|
||||
// a file cut short is nothing kept
|
||||
b, _ = os.ReadFile(sourceDigestsPath())
|
||||
os.WriteFile(sourceDigestsPath(), b[:len(b)-1], 0o600)
|
||||
restart()
|
||||
if _, n := key(chunk(1<<63|1, 10)); n != 1 {
|
||||
t.Fatalf("a cut file: hashed %d, want 1", n)
|
||||
}
|
||||
if got := decodeSourceDigests([]byte(sourceDigestsMagic), requestDiskBinary()); got != nil {
|
||||
t.Fatalf("no code: %v", got)
|
||||
}
|
||||
var sum [sha256.Size]byte
|
||||
if got := decodeSourceDigests(encodeSourceDigests("c", 1, nil, map[uint64][sha256.Size]byte{1: sum, 2: sum}), "c"); got.len() != 1 {
|
||||
t.Fatalf("limit 1 kept %d", len(got))
|
||||
}
|
||||
}
|
||||
@@ -143,7 +143,6 @@ func heatSettledKey(d heatDiskRef, cut, since time.Time, f Filter, identities ma
|
||||
hashRows(h, rows.of(c))
|
||||
}
|
||||
}
|
||||
sourceDigestsSave()
|
||||
return fmt.Sprintf("%x", h.Sum(nil)), true
|
||||
}
|
||||
|
||||
@@ -173,23 +172,14 @@ func sourceDigest(c *rowChunk, rows *chunkRows) [sha256.Size]byte {
|
||||
if !ok {
|
||||
sum, ok = d.last[c.serial]
|
||||
}
|
||||
if !ok {
|
||||
sourceDigestsLoad()
|
||||
sum, ok = sourceDigestsDisk.kept.get(c.serial)
|
||||
}
|
||||
d.Unlock()
|
||||
made := !ok
|
||||
if made {
|
||||
if !ok {
|
||||
h := sha256.New()
|
||||
io.WriteString(h, c.Source.Agent+"\x00"+c.Source.Key+"\x00")
|
||||
hashRows(h, rows.of(c))
|
||||
copy(sum[:], h.Sum(nil))
|
||||
}
|
||||
d.Lock()
|
||||
if made {
|
||||
sourceDigestsHashed++
|
||||
sourceDigestsDisk.dirty = true
|
||||
}
|
||||
if d.by == nil || len(d.by) >= sourceDigestsKept {
|
||||
d.last, d.by = d.by, map[uint64][sha256.Size]byte{}
|
||||
}
|
||||
|
||||
+5
-37
@@ -148,20 +148,7 @@ export async function mirror(env, rels, open, now = Date.now, attest = null) {
|
||||
else done.failed.push(`${tag}/${BUNDLES}`);
|
||||
}
|
||||
}
|
||||
const kept = await prune(env, tags);
|
||||
// a release the feeds named for one run only (the next tag came minutes
|
||||
// later) can leave that run with its files copied and its budget spent;
|
||||
// its bundles are filled in from the files R2 holds of it, while kept
|
||||
for (const tag of kept) {
|
||||
if (!attest || byVersion(tag, "v" + ATTESTED) < 0 || now() > until) continue;
|
||||
const have = await held(env, tag);
|
||||
if (!have || BUNDLES in have) continue;
|
||||
const assets = {};
|
||||
for (const [name, sha256] of Object.entries(have)) if (sha256) assets[name] = { sha256 };
|
||||
if (!Object.keys(assets).length) continue;
|
||||
if (await keepBundles(env, tag, { assets }, attest)) done.copied.push(`${tag}/${BUNDLES}`);
|
||||
else done.failed.push(`${tag}/${BUNDLES}`);
|
||||
}
|
||||
await prune(env, tags);
|
||||
return done;
|
||||
}
|
||||
|
||||
@@ -170,12 +157,8 @@ export async function mirror(env, rels, open, now = Date.now, attest = null) {
|
||||
// the next run asks again rather than keep a list with holes in it.
|
||||
async function keepBundles(env, tag, rel, attest) {
|
||||
const lines = new Set();
|
||||
// release CI signs every file in one statement, so the first answer
|
||||
// covers the rest: GitHub's API is asked once a release, not once a file
|
||||
// (unsigned, it allows 60 an hour to an IP the worker shares)
|
||||
const covered = new Set();
|
||||
for (const [name, a] of Object.entries(rel.assets)) {
|
||||
if (!a.sha256 || covered.has(a.sha256)) continue;
|
||||
if (!a.sha256) continue;
|
||||
let got = null;
|
||||
try {
|
||||
got = await attest(a.sha256);
|
||||
@@ -186,10 +169,7 @@ async function keepBundles(env, tag, rel, attest) {
|
||||
console.log("r2 attest: none for", tag, name);
|
||||
return false;
|
||||
}
|
||||
for (const b of got) {
|
||||
lines.add(JSON.stringify(b));
|
||||
for (const h of subjects(b)) covered.add(h);
|
||||
}
|
||||
for (const b of got) lines.add(JSON.stringify(b));
|
||||
}
|
||||
if (!lines.size) return false;
|
||||
try {
|
||||
@@ -203,16 +183,6 @@ async function keepBundles(env, tag, rel, attest) {
|
||||
}
|
||||
}
|
||||
|
||||
// subjects is the sha256 of each file a Sigstore bundle's statement names.
|
||||
export function subjects(b) {
|
||||
try {
|
||||
const st = JSON.parse(atob(b.dsseEnvelope.payload));
|
||||
return (st.subject || []).map((x) => x.digest && x.digest.sha256).filter(Boolean);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function copy(env, tag, name, a, open) {
|
||||
let res = null;
|
||||
try {
|
||||
@@ -246,8 +216,7 @@ async function copy(env, tag, name, a, open) {
|
||||
}
|
||||
}
|
||||
|
||||
// prune deletes every tag but keep and the KEEP newest besides, and
|
||||
// returns those KEEP newest.
|
||||
// prune deletes every tag but keep and the KEEP newest besides.
|
||||
async function prune(env, keep) {
|
||||
let tags = [], cursor;
|
||||
try {
|
||||
@@ -258,7 +227,7 @@ async function prune(env, keep) {
|
||||
} while (cursor);
|
||||
} catch (e) {
|
||||
console.log("r2 prune: list", String(e));
|
||||
return [];
|
||||
return;
|
||||
}
|
||||
const rest = tags.filter((t) => !keep.includes(t)).sort((a, b) => byVersion(b, a));
|
||||
for (const tag of rest.slice(KEEP)) {
|
||||
@@ -271,7 +240,6 @@ async function prune(env, keep) {
|
||||
console.log("r2 prune: delete", tag, String(e));
|
||||
}
|
||||
}
|
||||
return rest.slice(0, KEEP);
|
||||
}
|
||||
|
||||
function byVersion(a, b) {
|
||||
|
||||
@@ -179,45 +179,6 @@ test("mirror: a release's attestation bundles land in R2 as attestations.jsonl,
|
||||
assert.deepEqual(asked, []);
|
||||
});
|
||||
|
||||
test("mirror: a kept release the feeds no longer name still gets its bundles, for the files R2 holds of it (v0.1.3978)", async () => {
|
||||
const env = { RELEASES: bucket() };
|
||||
// v0.1.3978 was the newest for one run, which copied its files and spent
|
||||
// its budget; by the next run v0.1.3979 had taken its place in the feed
|
||||
await hold(env.RELEASES, "v0.1.3978", "a", "A");
|
||||
await hold(env.RELEASES, "v0.1.3978", "b", "B");
|
||||
await hold(env.RELEASES, "v0.1.3890", "a", "old");
|
||||
const rel = { version: "0.1.3979", assets: { c: { sha256: sha("C") } } };
|
||||
const asked = [];
|
||||
const attest = async (h) => (asked.push(h), [{ for: h }]);
|
||||
const done = await mirror(env, [rel], async () => new Response("C"), Date.now, attest);
|
||||
assert.deepEqual(done.copied.sort(), ["v0.1.3978/attestations.jsonl", "v0.1.3979/attestations.jsonl", "v0.1.3979/c"]);
|
||||
const res = await ask(env, "/files/v0.1.3978/attestations.jsonl");
|
||||
assert.equal(res.status, 200);
|
||||
const lines = (await res.text()).trimEnd().split("\n").map((l) => JSON.parse(l));
|
||||
assert.deepEqual(lines.map((l) => l.for).sort(), [sha("A"), sha("B")].sort());
|
||||
// a kept release from before the attestations is not asked
|
||||
assert.equal(asked.includes(sha("old")), false);
|
||||
// written once: the next run asks nothing more
|
||||
asked.length = 0;
|
||||
await mirror(env, [rel], async () => new Response("C"), Date.now, attest);
|
||||
assert.deepEqual(asked, []);
|
||||
});
|
||||
|
||||
test("mirror: one statement signing every file is asked for once a release, not once a file", async () => {
|
||||
const env = { RELEASES: bucket() };
|
||||
const names = ["a", "b", "c"];
|
||||
const rel = { version: "0.1.3982", assets: Object.fromEntries(names.map((n) => [n, { sha256: sha(n) }])) };
|
||||
const statement = { subject: names.map((n) => ({ name: n, digest: { sha256: sha(n) } })) };
|
||||
const bundle = { dsseEnvelope: { payload: btoa(JSON.stringify(statement)) } };
|
||||
const asked = [];
|
||||
const attest = async (h) => (asked.push(h), [bundle]);
|
||||
const done = await mirror(env, [rel], async (n) => new Response(n), Date.now, attest);
|
||||
assert.ok(done.copied.includes("v0.1.3982/attestations.jsonl"));
|
||||
assert.equal(asked.length, 1);
|
||||
const res = await ask(env, "/files/v0.1.3982/attestations.jsonl");
|
||||
assert.deepEqual((await res.text()).trimEnd().split("\n").map((l) => JSON.parse(l)), [bundle]);
|
||||
});
|
||||
|
||||
test("mirror: a release from before the attestations is not asked for any", async () => {
|
||||
const env = { RELEASES: bucket() };
|
||||
const rel = { version: "0.1.3890", assets: { a: { sha256: sha("A") } } };
|
||||
|
||||
@@ -318,7 +318,6 @@ href = <span class="s">"https://usemagpie.ai/import#"</span> + urlencode({
|
||||
<tr><td>Linux</td><td>By a desktop entry (<code>x-scheme-handler/magpie</code>), written by the installer and again on first run.</td></tr>
|
||||
<tr><td>Terminal</td><td><code>magpie import <link></code> shows the same summary and asks before adding.</td></tr>
|
||||
</table></div>
|
||||
<p><b>CC Switch links.</b> magpie also opens the <code>ccswitch://v1/import?resource=provider&…</code> links relays make for CC Switch (<code>app</code>, <code>name</code>, <code>endpoint</code>, <code>apiKey</code>, <code>apiFormat</code>, <code>model</code>, or a base64 <code>config</code>), with the same confirmation. Only providers are taken, not prompts, MCP servers or skills. magpie claims the scheme only when no other app has it, so CC Switch, if installed, keeps its links (on macOS, where both can claim it, the system picks).</p>
|
||||
<p>Import links need magpie 0.1.8 or later. When magpie is already running, the link goes to that instance and its window comes forward.</p>
|
||||
</article>
|
||||
</main>
|
||||
|
||||
@@ -318,7 +318,6 @@ href = <span class="s">"https://usemagpie.ai/import#"</span> + urlencode({
|
||||
<tr><td>Linux</td><td>デスクトップエントリ(<code>x-scheme-handler/magpie</code>)で登録します。インストーラが書き込み、初回起動時にも再度書き込みます。</td></tr>
|
||||
<tr><td>ターミナル</td><td><code>magpie import <リンク></code> が同じ概要を表示し、追加前に確認します。</td></tr>
|
||||
</table></div>
|
||||
<p><b>CC Switch のリンク。</b>magpie は、リレーが CC Switch 向けに作る <code>ccswitch://v1/import?resource=provider&…</code> リンクも開きます(<code>app</code>、<code>name</code>、<code>endpoint</code>、<code>apiKey</code>、<code>apiFormat</code>、<code>model</code>、または base64 の <code>config</code>)。確認は同じです。取り込むのはプロバイダーだけで、プロンプト、MCP、スキルは対象外です。ほかのアプリがスキームを持っていない場合にだけ登録するため、CC Switch があればそちらが開きます(両方が宣言できる macOS ではシステムが選びます)。</p>
|
||||
<p>インポートリンクには magpie 0.1.8 以降が必要です。magpie がすでに起動している場合、リンクはそのインスタンスに渡され、ウィンドウが前面に表示されます。</p>
|
||||
</article>
|
||||
</main>
|
||||
|
||||
@@ -318,7 +318,6 @@ href = <span class="s">"https://usemagpie.ai/import#"</span> + urlencode({
|
||||
<tr><td>Linux</td><td>通过桌面文件(<code>x-scheme-handler/magpie</code>)注册,安装器写一次,首次运行时再写一次。</td></tr>
|
||||
<tr><td>终端</td><td><code>magpie import <链接></code> 显示同样的摘要,添加前会询问。</td></tr>
|
||||
</table></div>
|
||||
<p><b>CC Switch 链接。</b>magpie 也能打开中转站为 CC Switch 做的 <code>ccswitch://v1/import?resource=provider&…</code> 链接(<code>app</code>、<code>name</code>、<code>endpoint</code>、<code>apiKey</code>、<code>apiFormat</code>、<code>model</code>,或 base64 的 <code>config</code>),同样要用户确认。只收供应商,不收提示词、MCP 和技能。只有没有别的应用占用这个协议时,magpie 才会注册它:装了 CC Switch 就仍由它打开(macOS 上两者都能声明,由系统选择)。</p>
|
||||
<p>导入链接需要 magpie 0.1.8 或更新版本。magpie 已在运行时,链接会交给那个实例,并把它的窗口调到前台。</p>
|
||||
</article>
|
||||
</main>
|
||||
|
||||
@@ -286,16 +286,6 @@ if [ -n "$uninstall" ]; then
|
||||
if [ -f "$apps/magpie.desktop" ] && { [ "$run" = "$exe" ] || [ ! -e "$run" ]; }; then
|
||||
gone "$apps/magpie.desktop"
|
||||
fi
|
||||
# the entry for ccswitch:// links, on the same terms, and its default
|
||||
cc=$(runs "$apps/magpie-ccswitch.desktop" Exec)
|
||||
if [ -f "$apps/magpie-ccswitch.desktop" ] && { [ "$cc" = "$exe" ] || [ ! -e "$cc" ]; }; then
|
||||
gone "$apps/magpie-ccswitch.desktop"
|
||||
list="$config/mimeapps.list"
|
||||
if [ -f "$list" ] && grep -qx 'x-scheme-handler/ccswitch=magpie-ccswitch\.desktop;\{0,1\}' "$list"; then
|
||||
grep -vx 'x-scheme-handler/ccswitch=magpie-ccswitch\.desktop;\{0,1\}' "$list" > "$list.magpie-new" || true
|
||||
mv "$list.magpie-new" "$list"
|
||||
fi
|
||||
fi
|
||||
# with no menu entry (this one, or the one magpie uninstall took),
|
||||
# what came with it: the icon, the magpie:// default xdg-mime set
|
||||
# (that line only) and the menu's cache when it lists nothing else
|
||||
|
||||
@@ -10979,8 +10979,6 @@ An import link is a suggestion. The user decides.
|
||||
| Linux | By a desktop entry (`x-scheme-handler/magpie`), written by the installer and again on first run. |
|
||||
| Terminal | `magpie import <link>` shows the same summary and asks before adding. |
|
||||
|
||||
**CC Switch links.** magpie also opens the `ccswitch://v1/import?resource=provider&…` links relays make for CC Switch (`app`, `name`, `endpoint`, `apiKey`, `apiFormat`, `model`, or a base64 `config`), with the same confirmation. Only providers are taken, not prompts, MCP servers or skills. magpie claims the scheme only when no other app has it, so CC Switch, if installed, keeps its links (on macOS, where both can claim it, the system picks).
|
||||
|
||||
Import links need magpie 0.1.8 or later. When magpie is already running, the link goes to that instance and its window comes forward.
|
||||
|
||||
---
|
||||
|
||||
Reference in New Issue
Block a user