sync: a provider can stay only on this device (treydtw on X)

Providers sync between computers (WebDAV, S3, GitHub), so a model served
from one machine's localhost reached the others, where it can't be
reached. A provider now has "Only on this device": sync neither sends it
out nor lets a copy from another computer replace or delete it.

Provider.ThisDevice is set from the provider row's right-click menu
(Only on this device, a check when on) or `magpie provider this-device
<id> yes|no`, over POST /api/provider/thisdevice. davsync's collect drops
those providers and their order entries (provider.SyncedOnly); Mirror
skips an incoming copy of one and keeps the local ones; Restore keeps a
local mark. A normal editor save keeps the mark. File backups still carry
the provider with its mark.

Default is off for every provider, localhost included. A 127.0.0.1
provider is also what another computer runs for its own copy of the same
local server, and default-on would remove those copies on their next
sync; a LAN address is reachable from the other computers. Turning it on
at one computer removes the synced copy at the others on their next sync.
docs/subsystems/sync-backup.md says so.

The menu item gives no toast: its check mark is the answer, which also
keeps the core script budget at +151 bytes (1,263,700 to
1,263,851).

Run, on mica: new davsync TestProviderOnThisDeviceStaysOnIt (two
computers over a fake DAV) and this-device.test.cjs (chromium and
webkit, en zh zh-TW ja de, widths 1100 and 420); provider-find updated
for the new menu entry; davsync, provider, backup, cli, gui Go packages
ok except TestCoreScriptBudget, then fixed; vet on darwin, windows and
linux nogui clean. Broken by hand: SyncedOnly made a no-op turns the
davsync test red ("a sends its own model out"), and the Mirror skip
removed turns it red ("b after a's model synced"). GUI files that fail
in a loaded run (claude-quota-onboarding, provider-find, skill-fold-all,
usage-agents-hide, usage-cards-hide, usage-hidden-way-back) were run
alone on origin/main 5e933e153: usage-hidden-way-back (#6295) and
usage-agents-hide (#3414) are red there too, the rest pass; this branch
gives the same result. gui-de and gui-ja "has every zh string" are red on
5e933e153 as well.

Not tried: a real WebDAV/S3/GitHub server between two real computers;
the CLI command has no test of its own.
This commit is contained in:
yetone
2026-11-12 19:31:11 +08:00
parent 96f8726ed1
commit 05cadcafd4
12 changed files with 300 additions and 6 deletions
+16
View File
@@ -108,6 +108,22 @@ sync both ways throughout. A kept agent is not listed under Kept on this
computer, which is the implicit own fields only (`TestAgentHereThroughSync`,
`TestAgentsHereIsThisComputers`, `agent-here.test.cjs`).
A provider can also be kept on one computer
([`Provider.ThisDevice`](../../internal/provider/provider.go): the provider
row's menu, `magpie provider this-device <id> yes|no`), for a local model that
exists only there (treydtw on X). `collect` leaves it, and its place in the
provider order, out of what sync sends, so changing it is no change to push
and the other computers lose their copy of it at their next sync. When a
bundle is brought in, `provider.Mirror` neither replaces nor removes a provider
kept here, whatever the other computers have under its id, and takes in none
that a bundle marks as kept on its computer
(`TestProviderOnThisDeviceStaysOnIt`). It is off by default for every provider,
local addresses included: a copy of a `127.0.0.1` provider on a computer that
runs the same local server works, and turning it on by default would take the
copies off the computers that have one. A file backup (`backup.Collect`) still
carries the provider, with the mark, and a Restore keeps the mark a provider
here has.
Sharing turned on at one computer never turns it on or off at another
(Lullaby on Discord). A backup restored onto a new computer leaves sharing as
that computer has it, off on a fresh one: sharing opens the gateway to the
+22
View File
@@ -139,6 +139,9 @@ const providerUsage = `usage:
rest at all, while out of quota, its key refused or rate limited
still rests it
magpie provider listed <id> yes|no no: its models serve only through routing groups, not in the list
magpie provider this-device <id> yes|no
yes: kept on this computer; sync neither sends it out nor lets
another computer's copy replace or remove it
magpie provider off|on <id> switch it off (kept, but no agent or request uses it), or on again
magpie provider test <id> [--as codex|claude-code] [model…]
send a tiny request through each endpoint, or to each model;
@@ -708,6 +711,25 @@ func providerCmd(args []string) error {
fmt.Println(green.Render("✓"), p.Name, muted.Render("its models are listed"))
}
return nil
case "this-device":
// yes: sync neither sends the provider out nor lets another
// computer's copy replace or remove it (treydtw on X)
if len(rest) != 2 || (rest[1] != "yes" && rest[1] != "no") {
return fmt.Errorf("magpie provider this-device <id> yes|no")
}
p, err := provider.Find(rest[0])
if err != nil {
return err
}
if err := provider.SetThisDevice(p.ID, rest[1] == "yes"); err != nil {
return err
}
if rest[1] == "yes" {
fmt.Println(green.Render("✓"), p.Name, muted.Render("stays on this device: sync doesn't send it out or change it"))
} else {
fmt.Println(green.Render("✓"), p.Name, muted.Render("syncs with your other computers"))
}
return nil
case "off", "on":
// off: kept with its keys, but agents are given none of its
// models and no request goes to it
+2
View File
@@ -854,6 +854,8 @@ func collect(c Config) (backup.Bundle, error) {
s := settings.Load()
b.Settings = &s
}
// a provider kept on this computer (Provider.ThisDevice) never goes out
b.Providers, b.Order = provider.SyncedOnly(b.Providers, b.Order)
if !c.Agents {
b.Agents = nil
}
+86
View File
@@ -0,0 +1,86 @@
package davsync
import (
"context"
"net/http/httptest"
"slices"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A provider kept on one computer (Provider.ThisDevice) is not sent out,
// and what another computer's sync brings neither replaces nor removes it
// (treydtw on X: a local model that exists only on this machine, synced to
// the others where it is unreachable).
func TestProviderOnThisDeviceStaysOnIt(t *testing.T) {
fake := &fakeDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}}
srv := httptest.NewServer(fake)
defer srv.Close()
ctx := context.Background()
cfg := Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "correct horse", Keys: true}
a, b := newComputer(t), newComputer(t)
sync := func(c computer) {
t.Helper()
c.use(t)
if err := Now(ctx); err != nil {
t.Fatal(err)
}
}
local := func(id, key string) provider.Provider {
return provider.Provider{ID: id, Name: id, Chat: "http://127.0.0.1:11434/v1", Key: key, ThisDevice: true}
}
a.use(t)
provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k1"})
provider.Save(local("ollama", "ka"))
if err := Configure(cfg); err != nil {
t.Fatal(err)
}
sync(a)
if out, err := collect(cfg); err != nil || slices.ContainsFunc(out.Providers, func(p provider.Provider) bool { return p.ID == "ollama" }) || slices.Contains(out.Order, "ollama") {
t.Fatalf("a sends its own model out: %v, %d providers, order %v", err, len(out.Providers), out.Order)
}
// b has a model of its own under the same id as a's, and another
b.use(t)
provider.Save(local("ollama", "kb"))
provider.Save(local("lmstudio", "kb2"))
if err := Configure(cfg); err != nil {
t.Fatal(err)
}
sync(b)
if got := ids(); !slices.Equal(got, []string{"deepseek=k1", "lmstudio=kb2", "ollama=kb"}) {
t.Fatalf("b after joining: %v", got)
}
// a drops DeepSeek: it goes from b, and b's own stay
a.use(t)
if err := provider.Delete("deepseek"); err != nil {
t.Fatal(err)
}
sync(a)
sync(b)
if got := ids(); !slices.Equal(got, []string{"lmstudio=kb2", "ollama=kb"}) {
t.Fatalf("b after a dropped DeepSeek: %v", got)
}
sync(a)
if got := ids(); !slices.Equal(got, []string{"ollama=ka"}) {
t.Fatalf("a after b's syncs: %v", got)
}
// a lets its model sync: it goes out, but b keeps its own under that id
if err := provider.SetThisDevice("ollama", false); err != nil {
t.Fatal(err)
}
sync(a)
sync(b)
if got := ids(); !slices.Equal(got, []string{"lmstudio=kb2", "ollama=kb"}) {
t.Fatalf("b after a's model synced: %v", got)
}
// and a model another computer sends out does not come to one kept here
b.use(t)
if ps, _ := provider.Stored(); !slices.ContainsFunc(ps, func(p provider.Provider) bool { return p.ID == "ollama" && p.ThisDevice }) {
t.Fatal("b's own ollama lost its mark")
}
}
+1
View File
@@ -6238,6 +6238,7 @@ function openProviderMenu(anchor, p, at) {
{ name: "Move to bottom", icon: MOVE_BOTTOM, key: ALT + SHIFT + "↓", off: i === on.length - 1, run: () => arrangeProvider(p.id, on.length - 1) },
{ name: "Use first", icon: p.useFirst ? CHECK : "", sep: !0, run: () => accountAction("provider/usefirst", { id: p.id, useFirst: !p.useFirst }, t(p.useFirst ? "{name} takes its turn with the others" : "{name} is used first", { name: p.name })) },
{ name: "Never a fallback", icon: p.noStandIn ? CHECK : "", run: () => accountAction("provider/standin", { id: p.id, noStandIn: !p.noStandIn }, t(p.noStandIn ? "{name} can be a fallback again" : "{name} is never a fallback for another model", { name: p.name })) },
{ name: "Only on this device", icon: p.thisDevice ? CHECK : "", sep: !0, run: () => accountAction("provider/thisdevice", { id: p.id, thisDevice: !p.thisDevice }) },
...magpie.actions?.("provider", { provider: { id: p.id, name: p.name } }) || [],
], at);
}
+4
View File
@@ -3651,6 +3651,7 @@ const I18N = {
"{name} is used first": "{name} 优先使用",
"{name} takes its turn with the others": "{name} 和其他供应商照常排序",
"Never a fallback": "从不作为备用",
"Only on this device": "仅限此设备",
"{name} is never a fallback for another model": "{name} 不再接其他模型的备用请求",
"{name} can be a fallback again": "{name} 可再作为备用",
"right-click to move it to the top or the bottom": "右键可移到顶部或底部",
@@ -8765,6 +8766,7 @@ const I18N = {
"{name} is used first": "{name} 優先使用",
"{name} takes its turn with the others": "{name} 和其他供應商照常排序",
"Never a fallback": "從不作為備用",
"Only on this device": "僅限此裝置",
"{name} is never a fallback for another model": "{name} 不再接其他模型的備用請求",
"{name} can be a fallback again": "{name} 可再作為備用",
"right-click to move it to the top or the bottom": "按右鍵可移到頂部或底部",
@@ -13886,6 +13888,7 @@ const I18N = {
"{name} is used first": "{name} を優先して使います",
"{name} takes its turn with the others": "{name} は他と同じ順番に戻りました",
"Never a fallback": "フォールバックにしない",
"Only on this device": "このデバイスのみ",
"{name} is never a fallback for another model": "{name} は他のモデルのフォールバックになりません",
"{name} can be a fallback again": "{name} は再びフォールバックになります",
"right-click to move it to the top or the bottom": "右クリックで一番上・一番下へ移動",
@@ -19016,6 +19019,7 @@ const I18N = {
"{name} is used first": "{name} wird zuerst verwendet",
"{name} takes its turn with the others": "{name} reiht sich wieder bei den anderen ein",
"Never a fallback": "Nie als Fallback",
"Only on this device": "Nur auf diesem Gerät",
"{name} is never a fallback for another model": "{name} ist nie Fallback für ein anderes Modell",
"{name} can be a fallback again": "{name} kann wieder Fallback sein",
"right-click to move it to the top or the bottom": "Rechtsklick, um ihn ganz nach oben oder unten zu verschieben",
+1 -1
View File
@@ -18,7 +18,7 @@ import (
// `git log -L` of this file.
const (
appScriptBudget = 1_086_267 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had
coreScriptBudget = 1_263_700 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to
coreScriptBudget = 1_263_851 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations
)
// codeBytes is how many bytes of b are code: its blank lines, its lines
+11 -1
View File
@@ -355,6 +355,8 @@ type providerJSON struct {
// routing unless KeepSelf (provider.Provider.SelfAnswered)
Self bool `json:"self,omitempty"`
KeepSelf bool `json:"keepSelf,omitempty"`
// ThisDevice: kept on this computer, out of sync (provider.Provider.ThisDevice)
ThisDevice bool `json:"thisDevice,omitempty"`
// LibraryMCP: a Remote magpie whose router is a Library server, or
// is to be one (library.RemoteMCPOn)
LibraryMCP bool `json:"libraryMCP,omitempty"`
@@ -870,7 +872,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, Billing: p.Billing, BillingKind: p.BillingKind(), InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, ClientCert: tilde(p.ClientCert), ClientKey: tilde(p.ClientKey), ServerCA: tilde(p.ServerCA), TakesClientCert: p.TakesClientCert(), ServerPin: p.ServerPin, TakesServerPin: p.TakesServerPin(), Socket: p.Socket, TakesSocket: p.TakesSocket(), LimitRestOff: p.LimitRestOff, UpstreamProviders: p.UpstreamProviders, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, NoBalanceProbe: p.NoBalanceProbe, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(),
Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)),
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, NoStandIn: p.NoStandIn, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, NoStandIn: p.NoStandIn, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, ThisDevice: p.ThisDevice, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate,
RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()),
AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM,
@@ -2413,6 +2415,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
in.KeepLoginAs = old.KeepLoginAs
in.SwitchOnly, in.RestartApp = old.SwitchOnly, old.RestartApp // switchonly, restartapp
in.KeepSelf = old.KeepSelf // keepself
in.ThisDevice = old.ThisDevice // thisdevice
in.CapStop, in.CapCareful = old.CapStop, old.CapCareful // capstop, capcareful
in.UseFirst = old.UseFirst // usefirst
in.NoStandIn = old.NoStandIn // standin
@@ -2739,6 +2742,13 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
fail(rw, err)
return
}
case "thisdevice":
// kept on this computer: sync neither sends the provider out nor
// lets another computer's copy replace or remove it (treydtw on X)
if err := provider.SetThisDevice(in.ID, in.ThisDevice); err != nil {
fail(rw, err)
return
}
case "capstop":
// a request ends at the accounts' caps, 429, or goes on to the
// fallbacks (plugins#349)
+3 -3
View File
@@ -190,8 +190,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await menu.waitFor();
await atPointer(page, row.locator(".name"), menu);
const names = await menu.locator(".rm-name").allTextContents();
assert.deepEqual(names, [await tr("Move to top"), await tr("Move up"), await tr("Move down"), await tr("Move to bottom"), await tr("Use first"), await tr("Never a fallback")]);
assert.deepEqual(await menu.locator(".rm-item").evaluateAll((bs) => bs.map((b) => b.disabled)), [false, false, true, true, false, false]);
assert.deepEqual(names, [await tr("Move to top"), await tr("Move up"), await tr("Move down"), await tr("Move to bottom"), await tr("Use first"), await tr("Never a fallback"), await tr("Only on this device")]);
assert.deepEqual(await menu.locator(".rm-item").evaluateAll((bs) => bs.map((b) => b.disabled)), [false, false, true, true, false, false, false]);
await menu.locator(".rm-item").first().click();
await page.waitForFunction(() => document.querySelector("#providers > .row.provider").dataset.id === "zhipu");
assert.deepEqual(f.posted.at(-1), ["zhipu", "openai", "relay-two", "relay-one", "anthropic", "relay-three", "deepseek", "moonshot", "relay-off"]);
@@ -200,7 +200,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the first one's: Move to Bottom
await page.locator('#providers > .row.provider[data-id="zhipu"] .name').click({ button: "right" });
await menu.waitFor();
assert.deepEqual(await menu.locator(".rm-item").evaluateAll((bs) => bs.map((b) => b.disabled)), [true, true, false, false, false, false]);
assert.deepEqual(await menu.locator(".rm-item").evaluateAll((bs) => bs.map((b) => b.disabled)), [true, true, false, false, false, false, false]);
await menu.locator(".rm-item").nth(3).click();
await page.waitForFunction(() => [...document.querySelectorAll("#providers > .row.provider")].at(-1).dataset.id === "zhipu");
assert.deepEqual(f.posted.at(-1), ["openai", "relay-two", "relay-one", "anthropic", "relay-three", "deepseek", "moonshot", "zhipu", "relay-off"]);
+110
View File
@@ -0,0 +1,110 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// treydtw on X: a local model that exists only on this computer must not be
// synced to the others. A provider row's right-click has Only on this
// device: it posts provider/thisdevice, and once on the item shows a tick
// and posts it off again. The page doesn't move. Every language, Chromium
// and WebKit, at 1100 and 420 wide; 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 CHECK = "m3.5 8.5 3 3 6-7";
const now = new Date();
const ago = (minutes) => new Date(now.getTime() - minutes * 60e3).toISOString();
const prov = (id, name, extra = {}) => ({
id, name, icon: "generic", host: id + ".example.com", chat: "https://" + id + ".example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "gpt-5.5", name: "GPT-5.5", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…" + id }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ...extra,
});
const order = [{ id: "ollama#k", provider: "ollama", name: "Ollama", who: "Ollama", kind: "key", model: "qwen3", routing: "" }];
const left = [{ id: "openai#k", provider: "openai", name: "OpenAI", who: "OpenAI", kind: "key", model: "gpt-5.5", routing: "", fallback: true, unlisted: true, standIn: true }];
function serve(lang, posts) {
let list = [prov("ollama", "Ollama", { fallback: ["openai/gpt-5.5"] }), prov("openai", "OpenAI")];
const providers = () => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } });
const route = {
id: 1, seq: 1, time: ago(1), agent: "codex", model: "ollama/qwen3", provider: "ollama", done: true, status: 503, ms: 900, order, left,
tries: [{ id: "ollama#k", model: "qwen3", start: ago(1), done: true, status: 503, ms: 900 }],
};
return async (request) => {
const url = new URL(request.request().url());
const json = (data) => request.fulfill({ json: data });
if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json(providers());
if (url.pathname === "/api/provider/thisdevice") {
const body = request.request().postDataJSON();
posts.push(body);
list = list.map((p) => p.id === body.id ? { ...p, thisDevice: body.thisDevice } : p);
return json(providers());
}
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1 }, routes: [route] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname.startsWith("/api/")) return 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 request.fulfill({ body: await fs.readFile(file), contentType });
};
}
const strings = [
"Only on this device",
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [1100, 420]) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${width} ${lang}: a provider's right-click turns Only on this device on and off`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
const say = (key) => page.evaluate(([lang, key]) => (lang !== "en" && I18N[lang]?.[key]) || key, [lang, key]);
await page.locator(".row.provider").first().waitFor();
if (lang === "en") {
const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings);
assert.deepEqual(missing, [], "every string has its translations");
}
const row = page.locator('#providers > .row.provider[data-id="ollama"]');
const menu = page.locator(".pop.row-menu");
const item = menu.locator(".rm-item", { hasText: await say("Only on this device") });
await row.locator(".name").click({ button: "right" });
await menu.waitFor();
assert.equal(await item.count(), 1);
assert.notEqual(await item.locator("path").getAttribute("d"), CHECK, "off, no tick");
const box = await menu.boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= width, `the menu fits across ${width}`);
await item.click();
await page.waitForFunction(() => !document.querySelector(".pop.row-menu"));
assert.deepEqual(posts, [{ id: "ollama", thisDevice: true }]);
await row.locator(".name").click({ button: "right" });
await menu.waitFor();
assert.equal(await item.locator("path").getAttribute("d"), CHECK, "on, a tick");
await item.click();
await page.waitForFunction(() => !document.querySelector(".pop.row-menu"));
assert.deepEqual(posts, [{ id: "ollama", thisDevice: true }, { id: "ollama", thisDevice: false }]);
await page.locator('#providers > .row.provider[data-id="openai"] .name').click({ button: "right" });
await menu.waitFor();
assert.notEqual(await item.locator("path").getAttribute("d"), CHECK, "another provider is off");
await page.keyboard.press("Escape");
assert.deepEqual(errors, []);
});
}
}
}
+40 -1
View File
@@ -50,8 +50,10 @@ func Restore(ps []Provider) (added, replaced int, err error) {
continue
}
keepSelf := f.Providers[i].KeepSelf // this computer's own (Mirror)
keepThis := f.Providers[i].ThisDevice
f.Providers[i] = KeepSecrets(p, f.Providers[i], p.Key == "" && len(p.Keys) == 0)
f.Providers[i].KeepSelf = keepSelf
f.Providers[i].ThisDevice = f.Providers[i].ThisDevice || keepThis // a restore doesn't send it away
replaced++
}
if added+replaced == 0 {
@@ -99,7 +101,9 @@ func RestoreGroups(gs []Group) error {
// restarted to follow (RestartApp), and whether a Remote magpie that is
// this magpie is used anyway (KeepSelf), is this computer's own:
// one person signs in to a personal account at home and a work account at
// the office, and sync set each computer to the other's every day.
// the office, and sync set each computer to the other's every day. A
// provider kept on this computer (ThisDevice) is neither replaced nor
// removed by them.
func Mirror(ps []Provider, gs []Group) error {
f, err := read()
if err != nil {
@@ -115,6 +119,12 @@ func Mirror(ps []Provider, gs []Group) error {
if p.ID == "" || p.ID != Slug(p.ID) || p.ID == "magpie" {
continue
}
// a provider kept on this computer isn't replaced by another
// computer's copy of its id, and one another computer kept is not
// here to be taken in
if p.ThisDevice || here[p.ID].ThisDevice {
continue
}
if h, ok := here[p.ID]; ok {
p = KeepSecrets(p, h, p.Key == "" && len(p.Keys) == 0)
p.KeepLogin, p.KeepLoginAs, p.SwitchOnly, p.RestartApp = h.KeepLogin, h.KeepLoginAs, h.SwitchOnly, h.RestartApp
@@ -125,6 +135,11 @@ func Mirror(ps []Provider, gs []Group) error {
}
out = append(out, p)
}
for _, h := range f.Providers { // and those kept here stay, whatever the others have
if h.ThisDevice {
out = append(out, h)
}
}
f.Providers = out
f.Groups = slices.DeleteFunc(slices.Clone(gs), func(g Group) bool { return g.ID == "" || g.ID != GroupSlug(g.ID) })
return store(f)
@@ -251,3 +266,27 @@ func notSignedIn(ps []Provider, have map[string]bool) []string {
// model picks and settings alone, with no endpoint or key of its own: it
// is signed in to, never given a key.
func OnlyPicks(p Provider) bool { return !hasEndpoint(normalize(p)) }
// SetThisDevice keeps a provider on this computer, out of sync, or lets it
// sync again (Provider.ThisDevice).
func SetThisDevice(id string, only bool) error {
p, err := Find(id)
if err != nil {
return err
}
p.ThisDevice = only
return Save(*p)
}
// SyncedOnly is the providers and their order without those kept on this
// computer (ThisDevice): what sync sends out.
func SyncedOnly(ps []Provider, order []string) ([]Provider, []string) {
here := map[string]bool{}
out := slices.DeleteFunc(slices.Clone(ps), func(p Provider) bool {
if p.ThisDevice {
here[p.ID] = true
}
return p.ThisDevice
})
return out, slices.DeleteFunc(slices.Clone(order), func(id string) bool { return here[id] })
}
+4
View File
@@ -207,6 +207,10 @@ type Provider struct {
// sync's copy of the provider on the other computer points at a
// magpie that is not that one (hanslin1666 on Discord).
KeepSelf bool `json:"keepSelf,omitempty"`
// ThisDevice keeps the provider on this computer: sync never sends it
// out, and what another computer's sync brings neither replaces nor
// removes it. For a local model that exists only here (treydtw on X).
ThisDevice bool `json:"thisDevice,omitempty"`
// MaxConcurrency is how many requests may be out at the vendor at once
// on each of its keys or accounts (Discord, Lemon: a Codex account is