diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index 6175a42e1..5fa1b9c6a 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -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 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 diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 0148279d7..d3fd439d9 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -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 yes|no no: its models serve only through routing groups, not in the list + magpie provider this-device 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 switch it off (kept, but no agent or request uses it), or on again magpie provider test [--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 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 diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index 4046f9899..7e2038fd4 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -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 } diff --git a/internal/davsync/this_device_test.go b/internal/davsync/this_device_test.go new file mode 100644 index 000000000..72a3bccc4 --- /dev/null +++ b/internal/davsync/this_device_test.go @@ -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") + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 5f91d0f79..dc8593e05 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -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); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 043f15f44..303df34cb 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 9e9863a5e..c3a1677d6 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -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 diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 835eb08ac..21bcae9bf 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -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) diff --git a/internal/gui/tests/provider-find.test.cjs b/internal/gui/tests/provider-find.test.cjs index e00f20f24..1d772799f 100644 --- a/internal/gui/tests/provider-find.test.cjs +++ b/internal/gui/tests/provider-find.test.cjs @@ -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"]); diff --git a/internal/gui/tests/this-device.test.cjs b/internal/gui/tests/this-device.test.cjs new file mode 100644 index 000000000..7a71c2137 --- /dev/null +++ b/internal/gui/tests/this-device.test.cjs @@ -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, []); + }); + } + } +} diff --git a/internal/provider/backup.go b/internal/provider/backup.go index 21fb71ba8..6ad59b99e 100644 --- a/internal/provider/backup.go +++ b/internal/provider/backup.go @@ -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] }) +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 29b53f137..9dc66aa51 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -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