provider, plugin, settings: accounts left all zero by a crash are read from their last good copy, and every state file is flushed before it is renamed in (#1505, Zhangwier)
Zhangwier's Windows machine went down hard, and logins.json (10783 bytes)
and plugin-auth.json (29926 bytes) came back at full length with every byte
0x00. Every account was gone. The rename had reached the disk before the
data. magpie then read "no accounts", and its next write would have made
that final.
What changed:
- Flushed before rename: steady.WriteFile writes a temp file, fsyncs it,
then renames it in. A failed write or flush removes the temp file and
leaves the old file as it was. edit.WriteAtomic, Kiro's writer, the
Codex session rewrite and the plugin host's writeDurable (host.js)
flush the same way. So do writePrivate (providers, logins, migrations),
settings, profiles, plugins.json, plugin-auth.json and mcp-signins.json.
- A last good generation: before each write, lastgood.Keep keeps the
valid file there as <file>.bak. A file that isn't valid is copied aside
as <file>.bad-<time>, with -2, -3 when two land in one second (O_EXCL),
and is never overwritten before that copy exists. The .bak lags one
write behind on purpose, since a crash zeroes the latest write.
- A failed read is unknown, never empty. On a cold start, logins.json,
providers.json, migrations.json, settings.json, profiles.json,
plugins.json, plugin-auth.json (Go and the host) and mcp-signins.json
are read from their .bak when they don't read. The recovery is logged
and listed in /api/state's recovered, and the window says it once in
every language. With no good .bak, a sign-out leaves plugin-auth.json
and mcp-signins.json as they are (the host's changeAuth no longer
writes {} over them). magpie's own sign-out returns the error, and a
sign-in copies the bad file aside before writing.
- caller-keys.json is flushed but never read from a .bak. A key revoked
in the last write would come back, so a store that doesn't read still
refuses every key, as its tests require.
ggbdpq's patch (f230bcae) is where the fsync-before-rename in
writePrivate, writeWhole and writeAuth came from. This change puts it in
one shared helper and reaches every other writer of magpie's state. The
JS write cleans up its temp file. The .bak recovery, the .bad copies and
the GUI notice are added here.
What was run:
- New tests, built from the literal case (10783 and 29926 zero bytes):
- internal/lastgood
- provider: TestZeroedLogins*, TestZeroedMigrations*,
TestZeroedProviders*, TestWritePrivateSyncsBeforeRename
- plugin: TestZeroedPluginAuth* against the real bun host,
TestPluginAuthSyncedBeforeRename with a plugin that makes fsync fail,
TestZeroedPluginList*
- TestZeroedSettings*, TestZeroedProfiles*, TestZeroedMCPSignIns*
- steady TestWriteFileSyncsBeforeRename, edit
TestWriteAtomicSyncsBeforeRename
- gui recovered-file.test.cjs (en/zh/zh-TW/ja/de, Chromium and WebKit)
- Broken by hand, each going red:
- Without the sync: the steady, edit, writePrivate and host fsync tests.
- Without the .bak fallback: every TestZeroed* test.
- The old changeAuth writes "{}\n" over the zeros.
- The old readLogins default.
- KeepBad without suffixes fails the one-second test.
- Without recoveredOnce, the GUI test fails 5/5.
- macOS: go test -tags nogui ./... in a sandbox HOME. The only failures
were the two access tests (then fixed by not recovering caller keys) and
TestProvidersCmdSaysUnreadable, which now removes the .bak to test the
no-backup case. Both packages were rerun and pass. gofmt -l prints
nothing. go vet, and GOOS=linux and GOOS=windows go vet -tags nogui, are
clean on the touched packages.
- GUI: recovered-file, whats-new, click-scroll, gui-de, gui-ja,
gui-zh-tw and i18n-keys pass.
- Windows box (cross-compiled test exes, sandboxed USERPROFILE/APPDATA):
lastgood, steady, provider, plugin (real bun host), settings, mcpauth,
edit and access pass. In profile, TestProfileSwitchesModelList and
TestOldProfileKeepsModelList fail the same on origin/main (filed as
#1517).
Reported-by: Zhangwier
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
@@ -97,7 +97,8 @@ no decision model was discovered (`Test` in
|
||||
- A Codex account is known by its email, with the plan for a workspace seat (`codexUser`), and a second seat of one email in another workspace by that name with its workspace after it (`codexName`): `me@example.com · Team · ws-two`. The account Codex is signed in to goes by the name it is saved under (`codexLiveName`) everywhere: its provider's `Account.User` (`codexAccount`), `liveLogin`, and its session identity (`SessionIdentities`). Its allowance, rests and sticks (`restKey`), cap, proxy, model list, a gateway key's account list (`LoginID`) and the Routing page all go by that name, so two seats of one email are never read as one (#1424).
|
||||
- The Copilot account the editors and CLI keep is read by `copilotLogin` ([account.go](../../internal/provider/account.go)): an editor's github.com sign-in in `~/.config/github-copilot/apps.json` or `hosts.json` first, then the Copilot CLI's, then an editor's on GHE.com. When GitHub refuses the editor token's trade for a session token (401 or 403, `copilotRefusals`, retried after an hour), the CLI's sign-in of the same login on the same host takes its place, sent as the CLI sends it, from that request on and on the Usage card (`copilotStandIn`); a CLI signed in to another account is never used for it, and the error names the editors' file (#1238). A sign-in from magpie of the account whose editor token is refused is kept and stands for it (`copilotProbeEditor`, `addCopilotLogin`); while the editor token works, it is let go as the agent's own, as before.
|
||||
- An unreadable `providers.json` is an error, never an empty list. Saving over an empty list would lose every provider.
|
||||
- When `logins.json` cannot be decoded as saved accounts, reads keep the accounts read before. Before saving a change, `keepUnreadLogins` copies the original file aside, including valid JSON with invalid account field types, so its credentials can be recovered. If the existing file cannot be read or the backup fails, saving returns the error and leaves the original file unchanged. A missing file can be created normally.
|
||||
- When `logins.json` cannot be decoded as saved accounts, reads keep the accounts read before. Before saving a change, `lastgood.Keep` ([lastgood.go](../../internal/lastgood/lastgood.go)) keeps the file there now: as `logins.json.bak`, its last good generation, when it reads, or copied aside as `logins.json.bad-<time>` (`-2`, `-3`… for another within one second) when it doesn't, including valid JSON with invalid account field types, so its credentials can be recovered. If the existing file cannot be read or the copy fails, saving returns the error and leaves the original file unchanged. A missing file can be created normally.
|
||||
- A Windows machine that went down mid-write left `logins.json` and `plugin-auth.json` at their full length, every byte zero (#1505): the rename reached the disk before the data. Every write of magpie's own state goes through `steady.WriteFile` (or `edit.WriteAtomic`), which flushes the temp file before renaming it in, and the plugin host's `writeDurable` does the same. A file that is there but doesn't read on a cold start is read from its `.bak` (`lastgood.Read`/`Fallback`): `logins.json`, `providers.json`, `migrations.json`, `settings.json`, `profiles.json`, `plugins.json`, `plugin-auth.json` and `mcp-signins.json`. `caller-keys.json` is flushed the same way but never read from a `.bak`: a key revoked in the last write would come back, so a store that doesn't read still refuses every key. The recovery is logged and listed in `/api/state`'s `recovered`, which the window tells once (`recoveredOnce`). The `.bak` lags one write behind on purpose: a crash zeroes the latest write, so a copy made with it could be zeroed too. With no good `.bak` the file is unknown, never empty: a sign-out leaves `plugin-auth.json` or `mcp-signins.json` as it is (magpie's own returns the error), and a sign-in added copies the file aside before it writes.
|
||||
- The account Codex or Claude Code is signed in to can be paused (`SetLoginOn` off, #263) only while another of its accounts is on. The gateway then sends it nothing: Codex's own-model turns go through routing, which passes over it (`OwnPaused`), and a native compaction (`/responses/compact`) goes to the first account on that isn't resting, signed as that account (`compactOn` in [codex_backend.go](../../internal/gateway/codex_backend.go)). The last other account off, the paused one is used again. A switched-off Codex provider is not a pause: Codex's own-model requests still relay on its sign-in as they came.
|
||||
- A switched-off provider (`Off`, #163) stays saved. The gateway says it is off instead of saying the model is unknown.
|
||||
- A provider removed or switched off takes its models out of the catalog. [Agent wiring](agent-wiring.md)'s `Reseat` moves agents off them.
|
||||
|
||||
@@ -85,6 +85,13 @@ func WriteAtomic(path string, data []byte) error {
|
||||
cleanup()
|
||||
return err
|
||||
}
|
||||
// on the disk before it is renamed in: a machine that goes down
|
||||
// between the two can leave the file at its length, all zero (#1505)
|
||||
if err := steady.Sync(tmp); err != nil {
|
||||
tmp.Close()
|
||||
cleanup()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
cleanup()
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package edit
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
|
||||
// WriteAtomic (settings, profiles, caller keys, agents' configs) flushes
|
||||
// the new file before renaming it in (#1505): one that fails to flush
|
||||
// leaves the old file.
|
||||
func TestWriteAtomicSyncsBeforeRename(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "settings.json")
|
||||
os.WriteFile(p, []byte(`{"old":1}`), 0o600)
|
||||
defer func() { steady.Sync = (*os.File).Sync }()
|
||||
steady.Sync = func(*os.File) error { return errors.New("the disk went away") }
|
||||
if err := WriteAtomic(p, []byte(`{"new":1}`)); err == nil {
|
||||
t.Fatal("written without a flush")
|
||||
}
|
||||
if b, _ := os.ReadFile(p); string(b) != `{"old":1}` {
|
||||
t.Fatalf("a failed flush left %q", b)
|
||||
}
|
||||
if left, _ := filepath.Glob(filepath.Join(filepath.Dir(p), "*")); len(left) != 1 {
|
||||
t.Fatalf("left %v", left)
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/fonts"
|
||||
"github.com/yetone/magpie/internal/fx"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/profile"
|
||||
@@ -259,6 +260,10 @@ type stateJSON struct {
|
||||
// Unlisted are the models kept for routing groups, which the pickers
|
||||
// don't offer: a filter that finds one of them says why it isn't there
|
||||
Unlisted []unlistedJSON `json:"unlisted,omitempty"`
|
||||
// Recovered are magpie's files a crash left unreadable (all zero,
|
||||
// #1505) that were read from their last good generation: the page
|
||||
// tells the user once each
|
||||
Recovered []lastgood.Note `json:"recovered,omitempty"`
|
||||
}
|
||||
|
||||
// unlistedJSON is a model of a provider kept for routing groups, and the
|
||||
@@ -1764,6 +1769,7 @@ func state() stateJSON {
|
||||
s.Profiles = append(s.Profiles, pj)
|
||||
}
|
||||
}
|
||||
s.Recovered = lastgood.Recovered()
|
||||
return s
|
||||
}
|
||||
|
||||
|
||||
@@ -3229,6 +3229,22 @@ async function load(again) {
|
||||
renderUpdateBadge();
|
||||
cliBehindOnce();
|
||||
whatsNewOnce();
|
||||
recoveredOnce();
|
||||
}
|
||||
|
||||
// recoveredOnce tells, once each, of a file of magpie's own a crash left
|
||||
// unreadable (all zero, #1505) that was read back from its last good copy:
|
||||
// the accounts in it are as they were then, a later change may be missing.
|
||||
const recoveredShown = new Set();
|
||||
function recoveredOnce() {
|
||||
const fresh = (state?.recovered || []).filter((n) => !recoveredShown.has(n.path + "\n" + n.at));
|
||||
if (!fresh.length) return;
|
||||
for (const n of fresh) recoveredShown.add(n.path + "\n" + n.at);
|
||||
const files = fresh.map((n) => n.file).join(", ");
|
||||
const bak = fresh.length === 1 && fresh[0].bak && !fresh[0].bak.startsWith("0001-") ? new Date(fresh[0].bak) : null;
|
||||
status(bak
|
||||
? t("{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup of {time}. A change made after that may be missing; the damaged file is kept beside it.", { file: files, time: bak.toLocaleString(locale) })
|
||||
: t("{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup. A change made after that may be missing; the damaged file is kept beside it.", { file: files }), "warn", 20000);
|
||||
}
|
||||
|
||||
// installFrom is what a restart to update tells the app: the window's tab,
|
||||
|
||||
@@ -2681,6 +2681,8 @@ const I18N = {
|
||||
"Hide until the next version": "隐藏,直到下一个版本",
|
||||
"Update hidden until the next version; Settings still has it": "已隐藏更新按钮,下一个版本发布时再显示;设置里仍可更新",
|
||||
"The `magpie` command is a copy": "终端里的 `magpie` 命令是一份拷贝",
|
||||
"{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup of {time}. A change made after that may be missing; the damaged file is kept beside it.": "{file} 已损坏(多半是电脑在写入途中停机),magpie 已从 {time} 的备份恢复。之后的改动可能缺失;损坏的文件保留在旁边。",
|
||||
"{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup. A change made after that may be missing; the damaged file is kept beside it.": "{file} 已损坏(多半是电脑在写入途中停机),magpie 已从备份恢复。之后的改动可能缺失;损坏的文件保留在旁边。",
|
||||
"The `magpie` command at {path} is a copied file, not the installer's link to the app: it won't follow the app's updates, and an old copy can break what a new one fixed. Re-run the installer, or link it by hand.": "`magpie` 命令({path})是拷贝的文件,不是安装脚本建立的应用链接:不会随应用更新,旧拷贝可能使新版的修复失效。请重新运行安装脚本,或手动建立链接。",
|
||||
"Update button": "更新按钮",
|
||||
"Shows in the header when a newer magpie is out": "magpie 有新版本时显示在顶栏",
|
||||
@@ -6739,6 +6741,8 @@ const I18N = {
|
||||
"Hide until the next version": "隱藏,直到下一個版本",
|
||||
"Update hidden until the next version; Settings still has it": "已隱藏更新按鈕,下一個版本釋出時再顯示;設定裡仍可更新",
|
||||
"The `magpie` command is a copy": "終端機裡的 `magpie` 命令是一份複製",
|
||||
"{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup of {time}. A change made after that may be missing; the damaged file is kept beside it.": "{file} 已損壞(多半是電腦在寫入途中停機),magpie 已從 {time} 的備份還原。之後的變更可能缺失;損壞的檔案保留在旁邊。",
|
||||
"{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup. A change made after that may be missing; the damaged file is kept beside it.": "{file} 已損壞(多半是電腦在寫入途中停機),magpie 已從備份還原。之後的變更可能缺失;損壞的檔案保留在旁邊。",
|
||||
"The `magpie` command at {path} is a copied file, not the installer's link to the app: it won't follow the app's updates, and an old copy can break what a new one fixed. Re-run the installer, or link it by hand.": "`magpie` 命令({path})是複製的檔案,不是安裝指令碼建立的應用連結:不會隨應用更新,舊複製可能使新版的修復失效。請重新執行安裝指令碼,或手動建立連結。",
|
||||
"Update button": "更新按鈕",
|
||||
"Shows in the header when a newer magpie is out": "magpie 有新版本時顯示在頂欄",
|
||||
@@ -10808,6 +10812,8 @@ const I18N = {
|
||||
"Hide until the next version": "次のバージョンまで非表示",
|
||||
"Update hidden until the next version; Settings still has it": "次のバージョンまでアップデートを非表示にしました。設定からは引き続きアップデートできます",
|
||||
"The `magpie` command is a copy": "`magpie` コマンドはコピーです",
|
||||
"{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup of {time}. A change made after that may be missing; the damaged file is kept beside it.": "{file} が破損していました(書き込み中にコンピューターが停止した可能性があります)。magpie は {time} のバックアップから復元しました。それ以降の変更は失われている可能性があります。破損したファイルはそのそばに残してあります。",
|
||||
"{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup. A change made after that may be missing; the damaged file is kept beside it.": "{file} が破損していました(書き込み中にコンピューターが停止した可能性があります)。magpie はバックアップから復元しました。それ以降の変更は失われている可能性があります。破損したファイルはそのそばに残してあります。",
|
||||
"The `magpie` command at {path} is a copied file, not the installer's link to the app: it won't follow the app's updates, and an old copy can break what a new one fixed. Re-run the installer, or link it by hand.": "{path} にある `magpie` コマンドはコピーされたファイルで、インストーラーが作成したアプリへのリンクではありません。アプリのアップデートに追従せず、古いコピーは新しいバージョンで修正された内容を壊すことがあります。インストーラーを再実行するか、手動でリンクを作成してください。",
|
||||
"Update button": "アップデートボタン",
|
||||
"Shows in the header when a newer magpie is out": "新しい magpie が出たときにヘッダーに表示します",
|
||||
@@ -14876,6 +14882,8 @@ const I18N = {
|
||||
"Hide until the next version": "Bis zur nächsten Version ausblenden",
|
||||
"Update hidden until the next version; Settings still has it": "Update bis zur nächsten Version ausgeblendet; in den Einstellungen weiterhin verfügbar",
|
||||
"The `magpie` command is a copy": "Der Befehl `magpie` ist eine Kopie",
|
||||
"{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup of {time}. A change made after that may be missing; the damaged file is kept beside it.": "{file} war beschädigt (der Computer ist wohl mitten im Schreiben ausgefallen), daher hat magpie die Datei aus ihrer Sicherung vom {time} wiederhergestellt. Spätere Änderungen fehlen eventuell; die beschädigte Datei liegt daneben.",
|
||||
"{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup. A change made after that may be missing; the damaged file is kept beside it.": "{file} war beschädigt (der Computer ist wohl mitten im Schreiben ausgefallen), daher hat magpie die Datei aus ihrer Sicherung wiederhergestellt. Spätere Änderungen fehlen eventuell; die beschädigte Datei liegt daneben.",
|
||||
"The `magpie` command at {path} is a copied file, not the installer's link to the app: it won't follow the app's updates, and an old copy can break what a new one fixed. Re-run the installer, or link it by hand.": "Der Befehl `magpie` unter {path} ist eine kopierte Datei, nicht die Verknüpfung des Installers zur App: Er folgt den Updates der App nicht, und eine alte Kopie kann kaputt machen, was eine neue behoben hat. Führen Sie den Installer erneut aus oder verknüpfen Sie ihn von Hand.",
|
||||
"Update button": "Update-Button",
|
||||
"Shows in the header when a newer magpie is out": "Erscheint in der Kopfzeile, wenn eine neuere magpie-Version verfügbar ist",
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A file of magpie's own a crash left unreadable (#1505: logins.json and
|
||||
// plugin-auth.json at their full length, every byte zero) is read back from
|
||||
// its last good copy, and /api/state's recovered says so: the window tells
|
||||
// the user once which file, from when, that a later change may be missing
|
||||
// and the damaged file is kept. A later load doesn't tell it again; a
|
||||
// recovery noted later is told. In every language, Chromium and WebKit;
|
||||
// the API is faked.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
|
||||
const BAK = "2026-10-09T21:14:03+08:00";
|
||||
const LOGINS = { file: "logins.json", path: "/home/u/.config/magpie/logins.json", why: "10783 bytes, every one zero", bak: BAK, at: "2026-10-10T08:00:00Z" };
|
||||
const AUTH = { file: "plugin-auth.json", path: "/home/u/.config/magpie/plugin-auth.json", why: "29926 bytes, every one zero", bak: BAK, at: "2026-10-10T08:00:05Z" };
|
||||
|
||||
function serve(lang, ctl) {
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light"};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") {
|
||||
ctl.states++;
|
||||
return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, recovered: ctl.recovered });
|
||||
}
|
||||
if (url.pathname === "/api/whatsnew") return json({ show: false, releases: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
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 route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
// what each language says: the start of the message, and that the damaged
|
||||
// file is kept
|
||||
const words = {
|
||||
en: ["logins.json was damaged", "the damaged file is kept beside it"],
|
||||
zh: ["logins.json 已损坏", "损坏的文件保留在旁边"],
|
||||
"zh-TW": ["logins.json 已損壞", "損壞的檔案保留在旁邊"],
|
||||
ja: ["logins.json が破損していました", "破損したファイルはそのそばに残してあります"],
|
||||
de: ["logins.json war beschädigt", "die beschädigte Datei liegt daneben"],
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const [lang, [start, kept]] of Object.entries(words)) {
|
||||
test(`${engine} ${lang}: a file restored from its backup is told once`, async () => {
|
||||
const browser = await { chromium, webkit }[engine].launch();
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 420, height: 760 } });
|
||||
const ctl = { states: 0, recovered: [LOGINS] };
|
||||
await page.route("**/*", serve(lang, ctl));
|
||||
await page.goto("http://magpie.test/");
|
||||
const st = page.locator("#status");
|
||||
await st.filter({ hasText: start }).waitFor({ timeout: 10000 });
|
||||
const said = await st.textContent();
|
||||
assert.ok(said.includes(kept), said);
|
||||
// the backup's time, in the page's language: its year and day
|
||||
assert.match(said, /2026/);
|
||||
assert.match(said, /9|10/);
|
||||
assert.equal(await st.getAttribute("class"), "status warn");
|
||||
// narrow: the pill stays in the window
|
||||
const box = await st.boundingBox();
|
||||
assert.ok(box.x >= 0 && box.x + box.width <= 420 + 1, JSON.stringify(box));
|
||||
|
||||
// loaded again: not told again
|
||||
await page.evaluate(() => { const s = document.querySelector("#status"); s.textContent = ""; s.className = "status"; });
|
||||
const before = ctl.states;
|
||||
await page.evaluate(() => load());
|
||||
assert.ok(ctl.states > before);
|
||||
assert.equal(await st.textContent(), "");
|
||||
|
||||
// a recovery noted later (the plugin host's) is told
|
||||
ctl.recovered = [LOGINS, AUTH];
|
||||
await page.evaluate(() => load());
|
||||
await st.filter({ hasText: "plugin-auth.json" }).waitFor({ timeout: 10000 });
|
||||
assert.ok(!(await st.textContent()).includes("logins.json"), await st.textContent());
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
// Package lastgood keeps the last good generation of magpie's own state
|
||||
// files (accounts, sign-ins, providers, settings) and reads it back when
|
||||
// the file itself can't be read.
|
||||
//
|
||||
// A Windows machine that went down mid-write left logins.json and
|
||||
// plugin-auth.json at their full length with every byte zero (#1505).
|
||||
// magpie then read no accounts, and its next write made that final. Here a
|
||||
// file that is there but not valid is unknown, never empty: before each
|
||||
// write the file there now is kept as <file>.bak when it is valid, or
|
||||
// copied aside as <file>.bad-<time> when it isn't, and a read of a file
|
||||
// that isn't valid gives the .bak's contents instead, noted for the GUI and
|
||||
// the log.
|
||||
package lastgood
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
|
||||
// Valid is whether b is a good copy of a file's contents.
|
||||
type Valid func(b []byte) bool
|
||||
|
||||
// JSON is a file that holds one JSON value: a file of zero bytes, empty or
|
||||
// whitespace only, or cut short is not.
|
||||
func JSON(b []byte) bool {
|
||||
b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf"))
|
||||
return len(bytes.TrimSpace(b)) > 0 && json.Valid(b)
|
||||
}
|
||||
|
||||
// Bak is where path's last good generation is kept.
|
||||
func Bak(path string) string { return path + ".bak" }
|
||||
|
||||
// ErrUnreadable is a file that is there but neither it nor its .bak is
|
||||
// valid: unknown, never empty.
|
||||
var ErrUnreadable = errors.New("unreadable")
|
||||
|
||||
// UnreadableError says which file, and why it didn't read.
|
||||
type UnreadableError struct {
|
||||
Path string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *UnreadableError) Error() string {
|
||||
return fmt.Sprintf("%s can't be read (%v) and has no good backup", e.Path, e.Err)
|
||||
}
|
||||
|
||||
func (e *UnreadableError) Unwrap() []error { return []error{ErrUnreadable, e.Err} }
|
||||
|
||||
// Read gives path's contents when they are valid. A file there that isn't
|
||||
// gives its .bak's contents, when that is valid, and the recovery is noted
|
||||
// (Recovered). A file not there is fs.ErrNotExist, its .bak not looked at:
|
||||
// a crash leaves a file renamed over as it was or as it became, never
|
||||
// gone, so one gone was removed on purpose. Anything else is an
|
||||
// *UnreadableError, or the error that stopped the read.
|
||||
func Read(path string, valid Valid) ([]byte, error) {
|
||||
b, err := steady.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if valid(b) {
|
||||
return b, nil
|
||||
}
|
||||
return Fallback(path, b, valid)
|
||||
}
|
||||
|
||||
// Fallback is Read for a caller that read path itself and found bad (its
|
||||
// contents, or nil when only its parse said so): the .bak's contents when
|
||||
// they are valid, noted, else an *UnreadableError.
|
||||
func Fallback(path string, bad []byte, valid Valid) ([]byte, error) {
|
||||
why := describe(bad)
|
||||
if b, err := steady.ReadFile(Bak(path)); err == nil && valid(b) {
|
||||
note(path, why)
|
||||
return b, nil
|
||||
}
|
||||
return nil, &UnreadableError{Path: path, Err: errors.New(why)}
|
||||
}
|
||||
|
||||
// describe says what is wrong with a bad file, for the log and the GUI.
|
||||
func describe(b []byte) string {
|
||||
switch {
|
||||
case b == nil:
|
||||
return "it doesn't parse"
|
||||
case len(bytes.Trim(b, "\x00")) == 0 && len(b) > 0:
|
||||
return strconv.Itoa(len(b)) + " bytes, every one zero"
|
||||
case len(bytes.TrimSpace(b)) == 0:
|
||||
return "it is empty"
|
||||
}
|
||||
return "it doesn't parse"
|
||||
}
|
||||
|
||||
// Keep is called before path is replaced, under the lock its writer
|
||||
// holds: the file there now, when valid, becomes the last good generation,
|
||||
// path.bak, written to the disk before path is; one that isn't valid is
|
||||
// copied aside (path.bad-<time>) and the .bak left as it is, so a file
|
||||
// that can't be read is never written over before a copy of it is kept.
|
||||
// A file not there needs neither. An error stops the write: the file there
|
||||
// couldn't be read, or a bad one couldn't be kept.
|
||||
func Keep(path string, valid Valid, perm fs.FileMode) error {
|
||||
b, err := steady.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if valid(b) {
|
||||
if old, err := os.ReadFile(Bak(path)); err == nil && bytes.Equal(old, b) {
|
||||
return nil
|
||||
}
|
||||
return steady.WriteFile(Bak(path), b, perm)
|
||||
}
|
||||
_, err = KeepBad(path, b)
|
||||
return err
|
||||
}
|
||||
|
||||
// now is time.Now; a test stands in for it.
|
||||
var now = time.Now
|
||||
|
||||
// KeepBad copies b, path's contents that aren't valid, aside as
|
||||
// path.bad-<time> and gives that name. Two bad files within one second
|
||||
// are both kept (.bad-<time>-2, …); the same bad bytes kept already are
|
||||
// not kept again.
|
||||
func KeepBad(path string, b []byte) (string, error) {
|
||||
stamp := path + ".bad-" + now().Format("20060102-150405")
|
||||
for i := 1; i < 1000; i++ {
|
||||
name := stamp
|
||||
if i > 1 {
|
||||
name += "-" + strconv.Itoa(i)
|
||||
}
|
||||
if old, err := os.ReadFile(name); err == nil {
|
||||
if bytes.Equal(old, b) {
|
||||
return name, nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if errors.Is(err, fs.ErrExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("%s can't be read and couldn't be kept: %v", filepath.Base(path), err)
|
||||
return "", err
|
||||
}
|
||||
_, err = f.Write(b)
|
||||
if err == nil {
|
||||
err = steady.Sync(f)
|
||||
}
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(name)
|
||||
log.Printf("%s can't be read and couldn't be kept: %v", filepath.Base(path), err)
|
||||
return "", err
|
||||
}
|
||||
log.Printf("%s can't be read (%s); it is kept as %s", filepath.Base(path), describe(b), filepath.Base(name))
|
||||
return name, nil
|
||||
}
|
||||
return "", fmt.Errorf("%s can't be read and there is no free name to keep it under", filepath.Base(path))
|
||||
}
|
||||
|
||||
// A Note is one file read back from its last good generation.
|
||||
type Note struct {
|
||||
File string `json:"file"` // the file's name: logins.json
|
||||
Path string `json:"path"`
|
||||
Why string `json:"why"` // what was wrong with it
|
||||
Bak time.Time `json:"bak"` // when the .bak was written
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
var (
|
||||
notesMu sync.Mutex
|
||||
notes []Note
|
||||
)
|
||||
|
||||
// note records that path was read from its .bak, once per path until
|
||||
// Forget: a file read hundreds of times over is logged once.
|
||||
func note(path, why string) {
|
||||
notesMu.Lock()
|
||||
defer notesMu.Unlock()
|
||||
if slices.ContainsFunc(notes, func(n Note) bool { return n.Path == path }) {
|
||||
return
|
||||
}
|
||||
n := Note{File: filepath.Base(path), Path: path, Why: why, At: now()}
|
||||
if fi, err := os.Stat(Bak(path)); err == nil {
|
||||
n.Bak = fi.ModTime()
|
||||
}
|
||||
notes = append(notes, n)
|
||||
log.Printf("%s can't be read (%s); what it held at %s is used, from %s", n.File, why, n.Bak.Local().Format("2006-01-02 15:04:05"), filepath.Base(Bak(path)))
|
||||
}
|
||||
|
||||
// Noted records a recovery another process made (the plugin host's of
|
||||
// plugin-auth.json).
|
||||
func Noted(path, why string) { note(path, why) }
|
||||
|
||||
// Recovered are the files read back from their last good generation since
|
||||
// magpie started, for the GUI to tell the user.
|
||||
func Recovered() []Note {
|
||||
notesMu.Lock()
|
||||
defer notesMu.Unlock()
|
||||
return slices.Clone(notes)
|
||||
}
|
||||
|
||||
// Reset forgets the notes; for tests.
|
||||
func Reset() {
|
||||
notesMu.Lock()
|
||||
notes = nil
|
||||
notesMu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package lastgood
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// zeros is what #1505's Windows crash left: logins.json at its full
|
||||
// length, 10,783 bytes, every one 0x00.
|
||||
func zeros(n int) []byte { return make([]byte, n) }
|
||||
|
||||
func setup(t *testing.T) string {
|
||||
t.Helper()
|
||||
Reset()
|
||||
t.Cleanup(Reset)
|
||||
return filepath.Join(t.TempDir(), "logins.json")
|
||||
}
|
||||
|
||||
func TestZeroedFileReadFromItsBackup(t *testing.T) {
|
||||
p := setup(t)
|
||||
good := []byte(`[{"agent":"codex","user":"a@x.com"}]` + "\n")
|
||||
if err := os.WriteFile(p, good, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// a write keeps the file there now as the last good generation
|
||||
if err := Keep(p, JSON, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(Bak(p)); !bytes.Equal(b, good) {
|
||||
t.Fatalf(".bak = %q", b)
|
||||
}
|
||||
if err := os.WriteFile(p, zeros(10783), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := Read(p, JSON)
|
||||
if err != nil || !bytes.Equal(b, good) {
|
||||
t.Fatalf("a zeroed file read as %q, %v; want its backup", b, err)
|
||||
}
|
||||
n := Recovered()
|
||||
if len(n) != 1 || n[0].File != "logins.json" || n[0].Why != "10783 bytes, every one zero" || n[0].Bak.IsZero() {
|
||||
t.Fatalf("recovery noted as %+v", n)
|
||||
}
|
||||
// read again, it is noted once
|
||||
Read(p, JSON)
|
||||
if len(Recovered()) != 1 {
|
||||
t.Fatalf("noted %d times", len(Recovered()))
|
||||
}
|
||||
}
|
||||
|
||||
// With no good backup, a zeroed file is unknown, never empty, and a file
|
||||
// not there is still not there.
|
||||
func TestZeroedFileWithoutBackupIsUnknown(t *testing.T) {
|
||||
p := setup(t)
|
||||
if _, err := Read(p, JSON); !errors.Is(err, fs.ErrNotExist) {
|
||||
t.Fatalf("a missing file read as %v", err)
|
||||
}
|
||||
os.WriteFile(p, zeros(29926), 0o600)
|
||||
if b, err := Read(p, JSON); !errors.Is(err, ErrUnreadable) || b != nil {
|
||||
t.Fatalf("a zeroed file without a backup read as %q, %v", b, err)
|
||||
}
|
||||
os.WriteFile(Bak(p), zeros(29926), 0o600) // the backup zeroed too
|
||||
if _, err := Read(p, JSON); !errors.Is(err, ErrUnreadable) {
|
||||
t.Fatalf("a zeroed backup taken: %v", err)
|
||||
}
|
||||
if len(Recovered()) != 0 {
|
||||
t.Fatalf("noted %+v", Recovered())
|
||||
}
|
||||
}
|
||||
|
||||
// Before a zeroed file is written over, it is copied aside and the good
|
||||
// backup left as it is.
|
||||
func TestKeepCopiesABadFileAside(t *testing.T) {
|
||||
p := setup(t)
|
||||
os.WriteFile(Bak(p), []byte(`["good"]`), 0o600)
|
||||
os.WriteFile(p, zeros(10783), 0o600)
|
||||
if err := Keep(p, JSON, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kept, _ := filepath.Glob(p + ".bad-*")
|
||||
if len(kept) != 1 {
|
||||
t.Fatalf("kept %v", kept)
|
||||
}
|
||||
if b, _ := os.ReadFile(kept[0]); !bytes.Equal(b, zeros(10783)) {
|
||||
t.Fatalf("kept %d bytes", len(b))
|
||||
}
|
||||
if b, _ := os.ReadFile(Bak(p)); string(b) != `["good"]` {
|
||||
t.Fatalf("the good backup became %q", b)
|
||||
}
|
||||
// kept again (the write after failed): no second copy
|
||||
if err := Keep(p, JSON, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if again, _ := filepath.Glob(p + ".bad-*"); len(again) != 1 {
|
||||
t.Fatalf("the same bad file kept twice: %v", again)
|
||||
}
|
||||
}
|
||||
|
||||
// Two different bad files within one second are both kept; a name made
|
||||
// from the clock is tried either side of a second's boundary.
|
||||
func TestBadCopiesInOneSecondBothKept(t *testing.T) {
|
||||
p := setup(t)
|
||||
defer func() { now = time.Now }()
|
||||
at := time.Date(2026, 10, 10, 12, 0, 0, 999_000_000, time.Local)
|
||||
now = func() time.Time { return at }
|
||||
var names []string
|
||||
for i, b := range [][]byte{zeros(10), []byte(`{"half`), zeros(11)} {
|
||||
if i == 2 {
|
||||
at = at.Add(2 * time.Millisecond) // over the boundary
|
||||
}
|
||||
name, err := KeepBad(p, b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := os.ReadFile(name); !bytes.Equal(got, b) {
|
||||
t.Fatalf("%s holds %q, want %q", name, got, b)
|
||||
}
|
||||
names = append(names, filepath.Base(name))
|
||||
}
|
||||
want := []string{"logins.json.bad-20261010-120000", "logins.json.bad-20261010-120000-2", "logins.json.bad-20261010-120001"}
|
||||
if strings.Join(names, " ") != strings.Join(want, " ") {
|
||||
t.Fatalf("kept as %v, want %v", names, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A bad file that can't be copied aside stops the write.
|
||||
func TestKeepFailsWhenTheBadFileCantBeKept(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a folder's mode doesn't stop a new file on Windows")
|
||||
}
|
||||
p := setup(t)
|
||||
os.WriteFile(p, zeros(64), 0o600)
|
||||
dir := filepath.Dir(p)
|
||||
os.Chmod(dir, 0o500)
|
||||
defer os.Chmod(dir, 0o700)
|
||||
if f, err := os.Create(filepath.Join(dir, "probe")); err == nil {
|
||||
f.Close()
|
||||
t.Skip("the filesystem does not enforce the read-only folder")
|
||||
}
|
||||
if err := Keep(p, JSON, 0o600); err == nil {
|
||||
t.Fatal("a bad file not kept, and the write let go on")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDescribe(t *testing.T) {
|
||||
for b, want := range map[string]string{
|
||||
string(zeros(3)): "3 bytes, every one zero",
|
||||
"": "it is empty",
|
||||
" \n": "it is empty",
|
||||
`{"a":`: "it doesn't parse",
|
||||
} {
|
||||
if got := describe([]byte(b)); got != want {
|
||||
t.Errorf("describe(%q) = %q, want %q", b, got, want)
|
||||
}
|
||||
}
|
||||
if JSON([]byte("\xef\xbb\xbf{}")) != true || JSON(zeros(5)) || JSON(nil) {
|
||||
t.Error("JSON misjudged")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package lastgood
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// The tests run in a home of their own, never the user's real files.
|
||||
func TestMain(m *testing.M) { testenv.Main(m) }
|
||||
+36
-23
@@ -25,6 +25,7 @@ import (
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -35,6 +36,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
@@ -98,18 +100,39 @@ var fileMu sync.Mutex
|
||||
func path() string { return filepath.Join(settings.Dir(), "mcp-signins.json") }
|
||||
|
||||
func load() map[string]*Record {
|
||||
m := map[string]*Record{}
|
||||
if b, err := os.ReadFile(path()); err == nil {
|
||||
_ = json.Unmarshal(b, &m)
|
||||
}
|
||||
m, _ := read()
|
||||
return m
|
||||
}
|
||||
|
||||
// read is the sign-ins, or their last good generation when a crash left
|
||||
// the file all zero (#1505); an error when neither reads, for a change
|
||||
// not to write them over as none.
|
||||
func read() (map[string]*Record, error) {
|
||||
m := map[string]*Record{}
|
||||
b, err := lastgood.Read(path(), validRecords)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return m, nil
|
||||
}
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
_ = json.Unmarshal(b, &m)
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func validRecords(b []byte) bool {
|
||||
var m map[string]*Record
|
||||
return json.Unmarshal(b, &m) == nil
|
||||
}
|
||||
|
||||
func save(m map[string]*Record) error {
|
||||
b, err := json.MarshalIndent(m, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := lastgood.Keep(path(), validRecords, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return writePrivate(path(), append(b, '\n'))
|
||||
}
|
||||
|
||||
@@ -122,30 +145,20 @@ func writePrivate(p string, b []byte) error {
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(p), "."+filepath.Base(p)+".*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := tmp.Write(b); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Chmod(0o600); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return steady.Rename(tmp.Name(), p)
|
||||
return steady.WriteFile(p, b, 0o600) // on the disk before it is renamed in
|
||||
}
|
||||
|
||||
func update(f func(m map[string]*Record) bool) error {
|
||||
fileMu.Lock()
|
||||
defer fileMu.Unlock()
|
||||
m := load()
|
||||
if !f(m) {
|
||||
// sign-ins that don't read are kept aside before a new one is saved
|
||||
// (save), and never written over with none
|
||||
m, err := read()
|
||||
changed := f(m)
|
||||
if err != nil && len(m) == 0 {
|
||||
return err // what to change may be in what doesn't read
|
||||
}
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
return save(m)
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package mcpauth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// mcp-signins.json zeroed by a crash (#1505) is its last good generation;
|
||||
// with none, a sign-out doesn't write none over sign-ins that don't read.
|
||||
func TestZeroedMCPSignInsReadFromBackup(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
for _, n := range []string{"a", "b"} {
|
||||
if err := update(func(m map[string]*Record) bool { m[n] = &Record{URL: "https://" + n + ".invalid/mcp"}; return true }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
zeroed := make([]byte, 900)
|
||||
os.WriteFile(path(), zeroed, 0o600)
|
||||
if _, ok := Get("a"); !ok {
|
||||
t.Fatal("a zeroed mcp-signins.json read as no sign-in to a")
|
||||
}
|
||||
|
||||
os.Remove(path() + ".bak")
|
||||
if err := SignOut("b"); err == nil {
|
||||
t.Fatal("a sign-out over sign-ins that don't read said done")
|
||||
}
|
||||
if got, _ := os.ReadFile(path()); !bytes.Equal(got, zeroed) {
|
||||
t.Fatalf("a sign-out wrote %q over sign-ins that don't read", got)
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
@@ -925,6 +926,10 @@ func (h *host) dispatch(m message) {
|
||||
switch m.Event {
|
||||
case "auth":
|
||||
changed()
|
||||
case "recovered":
|
||||
// the host read plugin-auth.json from its last good
|
||||
// generation (#1505): the GUI says so
|
||||
lastgood.Noted(AuthPath(), m.Said)
|
||||
case "renewing":
|
||||
h.renewing.Store(int32(m.Count))
|
||||
case "signIn":
|
||||
|
||||
+158
-22
@@ -525,41 +525,175 @@ function tunnel(p, host, port) {
|
||||
|
||||
// ---- auth.json ---------------------------------------------------------------
|
||||
|
||||
function readAuth() {
|
||||
let text
|
||||
// A crash can leave plugin-auth.json at its full length with every byte
|
||||
// zero (#1505). Such a file is unknown, never "no sign-ins": it is read
|
||||
// from its last good generation, plugin-auth.json.bak, which each write
|
||||
// keeps first; a write over one that doesn't read copies it aside
|
||||
// (plugin-auth.json.bad-<time>) first, and never writes none over it. As
|
||||
// internal/lastgood does for magpie's own files.
|
||||
|
||||
// parseAuth is the sign-ins in text, null when it isn't one JSON object.
|
||||
function parseAuth(text) {
|
||||
try {
|
||||
const v = JSON.parse(text)
|
||||
return v && typeof v === "object" && !Array.isArray(v) ? v : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function readFileSteady(p) {
|
||||
for (let i = 0; ; i++) {
|
||||
try {
|
||||
text = fs.readFileSync(authPath, "utf8")
|
||||
break
|
||||
return fs.readFileSync(p)
|
||||
} catch (e) {
|
||||
if (e?.code === "ENOENT") return {}
|
||||
if (e?.code === "ENOENT") return null
|
||||
// Windows refuses a file being renamed over for a moment: read as
|
||||
// none, the next setAuth would write the others' accounts away
|
||||
if (i >= 50) throw e
|
||||
pause(10)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// describeBad says what is wrong with a file that doesn't read.
|
||||
function describeBad(buf) {
|
||||
if (buf.length > 0 && buf.every((b) => b === 0)) return `${buf.length} bytes, every one zero`
|
||||
if (buf.toString("utf8").trim() === "") return "it is empty"
|
||||
return "it doesn't parse"
|
||||
}
|
||||
|
||||
let authRecovered = false
|
||||
let authUnread = false
|
||||
|
||||
// readAuthState is the sign-ins and whether they are known: a file not
|
||||
// there is none, known; one that doesn't read is its .bak's, known, or
|
||||
// none, unknown.
|
||||
function readAuthState() {
|
||||
const buf = readFileSteady(authPath)
|
||||
if (buf === null) return { all: {}, known: true }
|
||||
const v = parseAuth(buf.toString("utf8"))
|
||||
if (v) return { all: v, known: true }
|
||||
const why = describeBad(buf)
|
||||
let bak = null
|
||||
try {
|
||||
const v = JSON.parse(text)
|
||||
return v && typeof v === "object" ? v : {}
|
||||
} catch {
|
||||
return {}
|
||||
bak = parseAuth(fs.readFileSync(authPath + ".bak", "utf8"))
|
||||
} catch {}
|
||||
if (bak) {
|
||||
if (!authRecovered) {
|
||||
authRecovered = true
|
||||
toErr(`plugin-auth.json can't be read (${why}); the sign-ins in plugin-auth.json.bak are used`)
|
||||
send({ event: "recovered", said: why })
|
||||
}
|
||||
return { all: bak, known: true }
|
||||
}
|
||||
if (!authUnread) {
|
||||
authUnread = true
|
||||
toErr(`plugin-auth.json can't be read (${why}) and has no good backup`)
|
||||
}
|
||||
return { all: {}, known: false }
|
||||
}
|
||||
|
||||
function readAuth() {
|
||||
return readAuthState().all
|
||||
}
|
||||
|
||||
// writeDurable replaces p with data through a temp file flushed to the
|
||||
// disk before it is renamed over p: a rename reaches the disk on its own
|
||||
// schedule, the data behind it later, and a machine that went down between
|
||||
// the two left plugin-auth.json all zero (#1505). A write or flush that
|
||||
// fails leaves p as it was.
|
||||
function writeDurable(p, data) {
|
||||
const tmp = p + ".tmp-" + process.pid
|
||||
try {
|
||||
const f = fs.openSync(tmp, "w", 0o600)
|
||||
try {
|
||||
for (let off = 0; off < data.length; ) off += fs.writeSync(f, data, off, data.length - off)
|
||||
fs.fsyncSync(f)
|
||||
} finally {
|
||||
fs.closeSync(f)
|
||||
}
|
||||
// and a file held open by a reader refuses to be renamed over
|
||||
for (let i = 0; ; i++) {
|
||||
try {
|
||||
return fs.renameSync(tmp, p)
|
||||
} catch (e) {
|
||||
if (i >= 50 || !["EPERM", "EACCES", "EBUSY"].includes(e?.code)) throw e
|
||||
pause(10)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
try {
|
||||
fs.unlinkSync(tmp)
|
||||
} catch {}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// badStamp is the time a bad file is kept under, as Go's lastgood names it.
|
||||
function badStamp(d = new Date()) {
|
||||
const p = (n) => String(n).padStart(2, "0")
|
||||
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`
|
||||
}
|
||||
|
||||
// keepBad copies buf, a plugin-auth.json that doesn't read, aside: two
|
||||
// within one second are both kept (-2, …), the same bytes kept already
|
||||
// not again.
|
||||
function keepBad(buf) {
|
||||
const stamp = authPath + ".bad-" + badStamp()
|
||||
for (let i = 1; i < 1000; i++) {
|
||||
const name = i > 1 ? `${stamp}-${i}` : stamp
|
||||
let f
|
||||
try {
|
||||
f = fs.openSync(name, "wx", 0o600)
|
||||
} catch (e) {
|
||||
if (e?.code !== "EEXIST") throw e
|
||||
let old = null
|
||||
try {
|
||||
old = fs.readFileSync(name)
|
||||
} catch {}
|
||||
if (old && old.equals(buf)) return name
|
||||
continue
|
||||
}
|
||||
try {
|
||||
for (let off = 0; off < buf.length; ) off += fs.writeSync(f, buf, off, buf.length - off)
|
||||
fs.fsyncSync(f)
|
||||
} catch (e) {
|
||||
fs.closeSync(f)
|
||||
try {
|
||||
fs.unlinkSync(name)
|
||||
} catch {}
|
||||
throw e
|
||||
}
|
||||
fs.closeSync(f)
|
||||
toErr(`plugin-auth.json can't be read (${describeBad(buf)}); it is kept as ${path.basename(name)}`)
|
||||
return name
|
||||
}
|
||||
throw new Error("plugin-auth.json can't be read and there is no free name to keep it under")
|
||||
}
|
||||
|
||||
// keepAuth is called before plugin-auth.json is replaced: the file there
|
||||
// now becomes plugin-auth.json.bak when it reads, or is copied aside when
|
||||
// it doesn't. A failure stops the write.
|
||||
function keepAuth() {
|
||||
const buf = readFileSteady(authPath)
|
||||
if (buf === null) return
|
||||
if (!parseAuth(buf.toString("utf8"))) {
|
||||
keepBad(buf)
|
||||
return
|
||||
}
|
||||
const bak = authPath + ".bak"
|
||||
let old = null
|
||||
try {
|
||||
old = fs.readFileSync(bak)
|
||||
} catch {}
|
||||
if (!old || !old.equals(buf)) writeDurable(bak, buf)
|
||||
}
|
||||
|
||||
function writeAuth(all) {
|
||||
fs.mkdirSync(path.dirname(authPath), { recursive: true })
|
||||
const tmp = authPath + ".tmp-" + process.pid
|
||||
fs.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 0o600 })
|
||||
// and a file held open by a reader refuses to be renamed over
|
||||
for (let i = 0; ; i++) {
|
||||
try {
|
||||
return fs.renameSync(tmp, authPath)
|
||||
} catch (e) {
|
||||
if (i >= 50 || !["EPERM", "EACCES", "EBUSY"].includes(e?.code)) throw e
|
||||
pause(10)
|
||||
}
|
||||
}
|
||||
keepAuth()
|
||||
writeDurable(authPath, Buffer.from(JSON.stringify(all, null, 2) + "\n"))
|
||||
}
|
||||
|
||||
function pause(ms) {
|
||||
@@ -606,9 +740,11 @@ function lockAuth() {
|
||||
function changeAuth(change) {
|
||||
const unlock = lockAuth()
|
||||
try {
|
||||
const all = readAuth()
|
||||
const { all, known } = readAuthState()
|
||||
const out = change(all)
|
||||
if (out !== false) writeAuth(all)
|
||||
// sign-ins that don't read are never written over with none: a
|
||||
// sign-out of one of them waits for the file to be put right
|
||||
if (out !== false && (known || Object.keys(all).length > 0)) writeAuth(all)
|
||||
return out
|
||||
} finally {
|
||||
unlock()
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
@@ -293,7 +295,7 @@ func listingProxies() map[string]map[string]string {
|
||||
return out
|
||||
}
|
||||
var m map[string]json.RawMessage
|
||||
if b, err := steady.ReadFile(AuthPath()); err == nil {
|
||||
if b, err := readAuthFile(); err == nil {
|
||||
_ = json.Unmarshal(b, &m)
|
||||
}
|
||||
for k := range m {
|
||||
@@ -541,12 +543,23 @@ func firstNonEmpty(ss ...string) string {
|
||||
|
||||
func readAuth() map[string]storedAuth {
|
||||
var m map[string]storedAuth
|
||||
if b, err := steady.ReadFile(AuthPath()); err == nil {
|
||||
if b, err := readAuthFile(); err == nil {
|
||||
_ = json.Unmarshal(b, &m)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// validAuth is plugin-auth.json's contents: one object of sign-ins.
|
||||
func validAuth(b []byte) bool {
|
||||
var m map[string]json.RawMessage
|
||||
return json.Unmarshal(b, &m) == nil
|
||||
}
|
||||
|
||||
// readAuthFile is plugin-auth.json, or its last good generation when a
|
||||
// crash left it all zero (#1505): sign-ins that don't read are unknown,
|
||||
// never none.
|
||||
func readAuthFile() ([]byte, error) { return lastgood.Read(AuthPath(), validAuth) }
|
||||
|
||||
// SignedIn is whether a plugin sign-in is kept for provider.
|
||||
func SignedIn(provider string) bool {
|
||||
return len(accountsOf(readAuth(), provider)) > 0
|
||||
@@ -674,10 +687,13 @@ func SignOut(ctx context.Context, provider, account string) error {
|
||||
unlock := lockAuth()
|
||||
defer unlock()
|
||||
var m map[string]json.RawMessage
|
||||
b, err := steady.ReadFile(AuthPath())
|
||||
if err != nil {
|
||||
b, err := readAuthFile()
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err // sign-ins that don't read are not written over
|
||||
}
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -687,6 +703,9 @@ func SignOut(ctx context.Context, provider, account string) error {
|
||||
}
|
||||
}
|
||||
b, _ = json.MarshalIndent(m, "", " ")
|
||||
if err := lastgood.Keep(AuthPath(), validAuth, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeWhole(AuthPath(), append(b, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -781,7 +800,7 @@ func Check(ctx context.Context, provider, account string) (Checked, error) {
|
||||
// Auths are provider's sign-ins as plugin-auth.json keeps them, by key.
|
||||
func Auths(provider string) map[string]map[string]any {
|
||||
var m map[string]map[string]any
|
||||
if b, err := steady.ReadFile(AuthPath()); err == nil {
|
||||
if b, err := readAuthFile(); err == nil {
|
||||
_ = json.Unmarshal(b, &m)
|
||||
}
|
||||
out := map[string]map[string]any{}
|
||||
|
||||
+12
-18
@@ -34,6 +34,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
@@ -120,7 +121,9 @@ var pluginsList struct {
|
||||
// changed; Load gives the mutable copy.
|
||||
func list() List {
|
||||
path := listPath()
|
||||
b, err := steady.ReadFile(path)
|
||||
// one a crash left all zero (#1505) is its last good generation: the
|
||||
// plugins installed are unknown, never none
|
||||
b, err := lastgood.Read(path, lastgood.JSON)
|
||||
if err != nil {
|
||||
// Do not cache read failures; a later call will read the file again.
|
||||
return List{}
|
||||
@@ -188,24 +191,12 @@ func cloneJSON(v any) any {
|
||||
}
|
||||
|
||||
// writeWhole writes b to p by a rename, so a magpie or the host reading
|
||||
// p meanwhile reads the old file or the new one, never one half-written;
|
||||
// read back with steady.ReadFile, which waits out the rename on Windows.
|
||||
// p meanwhile reads the old file or the new one, never one half-written,
|
||||
// and flushed to the disk first, so a machine that goes down meanwhile
|
||||
// doesn't leave p all zero (#1505); read back with steady.ReadFile, which
|
||||
// waits out the rename on Windows.
|
||||
func writeWhole(p string, b []byte) error {
|
||||
f, err := os.CreateTemp(filepath.Dir(p), filepath.Base(p)+".*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.Write(b)
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = steady.Rename(f.Name(), p)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(f.Name())
|
||||
}
|
||||
return err
|
||||
return steady.WriteFile(p, b, 0o600)
|
||||
}
|
||||
|
||||
func save(l List) error {
|
||||
@@ -216,6 +207,9 @@ func save(l List) error {
|
||||
if err := os.MkdirAll(settings.Dir(), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := lastgood.Keep(listPath(), lastgood.JSON, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeWhole(listPath(), append(b, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// plugins.json zeroed by a crash (#1505) is its last good generation: the
|
||||
// plugins installed are not none.
|
||||
func TestZeroedPluginListReadFromBackup(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, "config"))
|
||||
os.MkdirAll(filepath.Dir(listPath()), 0o700)
|
||||
for _, l := range []List{{Plugins: []Entry{{Spec: "a"}}}, {Plugins: []Entry{{Spec: "a"}, {Spec: "b"}}}} {
|
||||
if err := save(l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
os.WriteFile(listPath(), make([]byte, 300), 0o600)
|
||||
if l := list(); len(l.Plugins) != 1 || l.Plugins[0].Spec != "a" {
|
||||
t.Fatalf("a zeroed plugins.json read as %+v", l.Plugins)
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
// A plugin signing in with a key to a made-up provider, which makes the
|
||||
// disk refuse to flush a file (fs.fsyncSync throws) while the file named
|
||||
// by $FSYNC_FAIL is there: the host shares node:fs with it, so its writes
|
||||
// of plugin-auth.json meet the same disk.
|
||||
import fs from "node:fs"
|
||||
|
||||
const fsync = fs.fsyncSync
|
||||
fs.fsyncSync = (fd) => {
|
||||
if (process.env.FSYNC_FAIL && fs.existsSync(process.env.FSYNC_FAIL)) throw Object.assign(new Error("EIO: i/o error, fsync"), { code: "EIO" })
|
||||
return fsync(fd)
|
||||
}
|
||||
|
||||
export const NoFsyncPlugin = async () => ({
|
||||
config: async (cfg) => {
|
||||
cfg.provider = cfg.provider ?? {}
|
||||
cfg.provider.syncco = {
|
||||
name: "SyncCo",
|
||||
npm: "@ai-sdk/openai-compatible",
|
||||
api: "https://sync.invalid/v1",
|
||||
models: { "sync-1": { name: "Sync One", limit: { context: 1000, output: 100 } } },
|
||||
}
|
||||
},
|
||||
auth: {
|
||||
provider: "syncco",
|
||||
methods: [{ type: "api", label: "API key" }],
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
)
|
||||
|
||||
// zeroedAuth is plugin-auth.json as #1505's Windows crash left it: its full
|
||||
// length, 29,926 bytes, every one 0x00.
|
||||
var zeroedAuth = make([]byte, 29926)
|
||||
|
||||
func addRenew(t *testing.T, ctx context.Context) {
|
||||
t.Helper()
|
||||
t.Setenv("FAKE_BASE", "http://127.0.0.1:1/v1")
|
||||
t.Setenv("RENEW_LOG", filepath.Join(t.TempDir(), "renewals"))
|
||||
abs, _ := filepath.Abs("testdata/renew/index.js")
|
||||
if _, err := Add(ctx, abs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func importRenew(t *testing.T, ctx context.Context, who string) string {
|
||||
t.Helper()
|
||||
k, err := Import(ctx, "renewco", map[string]any{"type": "oauth", "refresh": "r-ok-" + who, "access": "a", "expires": time.Now().Add(time.Hour).UnixMilli(), "accountId": who})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
// The host reads a zeroed plugin-auth.json from its last good generation,
|
||||
// tells magpie, which tells the user, and a sign-in added keeps the
|
||||
// accounts and the zeroed file aside.
|
||||
func TestZeroedPluginAuthReadFromBackup(t *testing.T) {
|
||||
sandbox(t)
|
||||
lastgood.Reset()
|
||||
t.Cleanup(lastgood.Reset)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
addRenew(t, ctx)
|
||||
a := importRenew(t, ctx, "a@renew")
|
||||
b := importRenew(t, ctx, "b@renew")
|
||||
Restart()
|
||||
if _, err := os.Stat(lastgood.Bak(AuthPath())); err != nil {
|
||||
t.Fatalf("no last good generation kept: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(AuthPath(), zeroedAuth, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// magpie's own reads: the .bak lags one write, so it holds a
|
||||
if got := Auths("renewco"); len(got) != 1 || got[a] == nil {
|
||||
t.Fatalf("a zeroed plugin-auth.json read as %v", got)
|
||||
}
|
||||
if len(lastgood.Recovered()) != 1 {
|
||||
t.Fatalf("magpie's read not noted: %+v", lastgood.Recovered())
|
||||
}
|
||||
lastgood.Reset() // the host's own read is told magpie too
|
||||
|
||||
// the host's
|
||||
c := importRenew(t, ctx, "c@renew")
|
||||
all := authFile(t)
|
||||
if all[a] == nil || all[c] == nil {
|
||||
t.Fatalf("after a sign-in added over a zeroed file: %v", all)
|
||||
}
|
||||
_ = b // the write the crash took
|
||||
kept, _ := filepath.Glob(AuthPath() + ".bad-*")
|
||||
if len(kept) != 1 {
|
||||
t.Fatalf("the zeroed file not kept aside: %v", kept)
|
||||
}
|
||||
if got, _ := os.ReadFile(kept[0]); !bytes.Equal(got, zeroedAuth) {
|
||||
t.Fatalf("kept %d bytes", len(got))
|
||||
}
|
||||
for wait := time.Now().Add(5 * time.Second); len(lastgood.Recovered()) == 0 && time.Now().Before(wait); {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if n := lastgood.Recovered(); len(n) != 1 || n[0].File != "plugin-auth.json" || n[0].Why != "29926 bytes, every one zero" {
|
||||
t.Fatalf("the host's recovery isn't told: %+v", n)
|
||||
}
|
||||
}
|
||||
|
||||
// With no backup, a zeroed plugin-auth.json is unknown, never none: a
|
||||
// sign-out doesn't write none over it, magpie's or the host's.
|
||||
func TestZeroedPluginAuthWithoutBackupNotWrittenOver(t *testing.T) {
|
||||
sandbox(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
addRenew(t, ctx)
|
||||
if _, err := get(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.MkdirAll(filepath.Dir(AuthPath()), 0o700)
|
||||
os.WriteFile(AuthPath(), zeroedAuth, 0o600)
|
||||
// one account named, and every one of the provider's
|
||||
for _, account := range []string{"renewco#a@renew", ""} {
|
||||
if err := SignOut(ctx, "renewco", account); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := os.ReadFile(AuthPath()); !bytes.Equal(got, zeroedAuth) {
|
||||
t.Fatalf("the host's sign-out of %q wrote %q over sign-ins that don't read", account, got)
|
||||
}
|
||||
}
|
||||
Restart()
|
||||
if err := SignOut(ctx, "renewco", ""); err == nil {
|
||||
t.Fatal("magpie's sign-out of sign-ins that don't read said done")
|
||||
}
|
||||
if got, _ := os.ReadFile(AuthPath()); !bytes.Equal(got, zeroedAuth) {
|
||||
t.Fatalf("magpie's sign-out wrote %q over sign-ins that don't read", got)
|
||||
}
|
||||
// a sign-in added writes, the zeroed file kept aside first
|
||||
k := importRenew(t, ctx, "new@renew")
|
||||
if authFile(t)[k] == nil {
|
||||
t.Fatal("the sign-in added wasn't kept")
|
||||
}
|
||||
if kept, _ := filepath.Glob(AuthPath() + ".bad-*"); len(kept) != 1 {
|
||||
t.Fatalf("the zeroed file not kept aside: %v", kept)
|
||||
}
|
||||
}
|
||||
|
||||
// The host flushes plugin-auth.json before renaming it over the old: a
|
||||
// flush that fails leaves the sign-ins there as they were.
|
||||
func TestPluginAuthSyncedBeforeRename(t *testing.T) {
|
||||
sandbox(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
flag := filepath.Join(t.TempDir(), "fail")
|
||||
t.Setenv("FSYNC_FAIL", flag)
|
||||
abs, _ := filepath.Abs("testdata/nofsync/index.js")
|
||||
if _, err := Add(ctx, abs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Import(ctx, "syncco", map[string]any{"type": "api", "key": "k-old"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := os.ReadFile(AuthPath())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(flag, nil, 0o600)
|
||||
if _, err := Import(ctx, "syncco", map[string]any{"type": "api", "key": "k-new"}); err == nil {
|
||||
t.Fatal("a sign-in saved without its flush said done")
|
||||
}
|
||||
if after, _ := os.ReadFile(AuthPath()); !bytes.Equal(after, before) {
|
||||
t.Fatalf("a failed flush changed plugin-auth.json:\n%s\nwas\n%s", after, before)
|
||||
}
|
||||
if left, _ := filepath.Glob(AuthPath() + ".tmp-*"); len(left) != 0 {
|
||||
t.Fatalf("a failed write left %v", left)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
@@ -106,11 +107,24 @@ func Load() (map[string]Profile, error) {
|
||||
return out, nil
|
||||
}
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", Path(), err)
|
||||
// one a crash left all zero (#1505) is its last good generation
|
||||
bak, ferr := lastgood.Fallback(Path(), b, validProfiles)
|
||||
if ferr != nil {
|
||||
return nil, fmt.Errorf("%s: %w", Path(), err)
|
||||
}
|
||||
out = map[string]Profile{}
|
||||
if err := json.Unmarshal(bak, &out); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", Path(), err)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func validProfiles(b []byte) bool {
|
||||
var m map[string]Profile
|
||||
return json.Unmarshal(b, &m) == nil
|
||||
}
|
||||
|
||||
// Names lists profiles alphabetically.
|
||||
func Names(ps map[string]Profile) []string {
|
||||
names := make([]string, 0, len(ps))
|
||||
@@ -126,6 +140,9 @@ func store(ps map[string]Profile) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := lastgood.Keep(Path(), validProfiles, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return edit.WriteAtomic(Path(), append(b, '\n'))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package profile
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
)
|
||||
|
||||
// profiles.json zeroed by a crash (#1505) is its last good generation.
|
||||
func TestZeroedProfilesReadFromBackup(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
os.MkdirAll(appdir.Config(), 0o700)
|
||||
for _, ps := range []map[string]Profile{
|
||||
{"work": {Fields: map[string]string{"codex.model": "a"}}},
|
||||
{"work": {Fields: map[string]string{"codex.model": "a"}}, "home": {Fields: map[string]string{"codex.model": "b"}}},
|
||||
} {
|
||||
if err := store(ps); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
os.WriteFile(Path(), make([]byte, 512), 0o600)
|
||||
ps, err := Load()
|
||||
if err != nil || len(ps) != 1 || ps["work"].Fields["codex.model"] != "a" {
|
||||
t.Fatalf("a zeroed profiles.json read as %v, %v", ps, err)
|
||||
}
|
||||
}
|
||||
@@ -469,11 +469,7 @@ func writeFileAtomic(path string, b []byte) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := path + ".magpie-tmp"
|
||||
if err := os.WriteFile(tmp, b, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return steady.Rename(tmp, path)
|
||||
return steady.WriteFile(path, b, 0o600) // on the disk before it is renamed in (#1505)
|
||||
}
|
||||
|
||||
// kiroPost posts to a sign-in endpoint.
|
||||
|
||||
+50
-58
@@ -28,6 +28,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
@@ -153,65 +154,69 @@ func loginsPath() string { return filepath.Join(filepath.Dir(Path()), "logins.js
|
||||
// lastLogins is the accounts last read from logins.json: a read that fails
|
||||
// (a file half there, one magpie can't open for a moment) is them, not no
|
||||
// accounts, which the next change of an account would write back over
|
||||
// every account.
|
||||
// every account. loginsKnown is whether there are any such, read or
|
||||
// written by this magpie.
|
||||
var (
|
||||
lastLoginsMu sync.Mutex
|
||||
lastLogins []savedLogin
|
||||
loginsKnown bool
|
||||
)
|
||||
|
||||
// parseLogins is logins.json's accounts.
|
||||
func parseLogins(b []byte) ([]savedLogin, error) {
|
||||
var out []savedLogin
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// DimAgent's accounts: magpie no longer signs in to it (DimAgent
|
||||
// doesn't allow its subscription used outside its client), so one
|
||||
// signed in before is left out, and gone from the file at its next write
|
||||
out = slices.DeleteFunc(out, func(l savedLogin) bool { return l.Agent == "dimagent" })
|
||||
return nameAlike(dedupeLogins(out)), nil
|
||||
}
|
||||
|
||||
// validLogins is logins.json's contents read as accounts: valid JSON can
|
||||
// still have field types they don't take.
|
||||
func validLogins(b []byte) bool {
|
||||
var ls []savedLogin
|
||||
return json.Unmarshal(b, &ls) == nil
|
||||
}
|
||||
|
||||
func readLogins() []savedLogin {
|
||||
// parsed once until the file changes: a state of the page asks for it
|
||||
// dozens of times (every agent's drift and models), and with the
|
||||
// accounts' credentials in it the file is large — a Save of a profile
|
||||
// waited seconds on it
|
||||
ls, err := filememo.Read("logins", loginsPath(), func(b []byte) ([]savedLogin, error) {
|
||||
var out []savedLogin
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// DimAgent's accounts: magpie no longer signs in to it (DimAgent
|
||||
// doesn't allow its subscription used outside its client), so one
|
||||
// signed in before is left out, and gone from the file at its next write
|
||||
out = slices.DeleteFunc(out, func(l savedLogin) bool { return l.Agent == "dimagent" })
|
||||
return nameAlike(dedupeLogins(out)), nil
|
||||
})
|
||||
ls, err := filememo.Read("logins", loginsPath(), parseLogins)
|
||||
lastLoginsMu.Lock()
|
||||
defer lastLoginsMu.Unlock()
|
||||
switch {
|
||||
case err == nil:
|
||||
lastLogins = ls
|
||||
lastLogins, loginsKnown = ls, true
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
lastLogins = nil
|
||||
default:
|
||||
lastLogins, loginsKnown = nil, true
|
||||
case loginsKnown:
|
||||
log.Printf("logins.json: %v; the accounts read before are kept", err)
|
||||
ls = lastLogins
|
||||
default:
|
||||
// magpie just started on a file that doesn't read (all zero after
|
||||
// a crash, #1505): the accounts are its last good generation's
|
||||
ls = nil
|
||||
if b, ferr := lastgood.Fallback(loginsPath(), unreadBytes(loginsPath()), validLogins); ferr == nil {
|
||||
ls, _ = parseLogins(b)
|
||||
lastLogins, loginsKnown = ls, true
|
||||
} else {
|
||||
log.Printf("logins.json: %v; %v", err, ferr)
|
||||
}
|
||||
}
|
||||
return slices.Clone(ls) // callers change theirs
|
||||
}
|
||||
|
||||
// keepUnreadLogins copies a logins.json that doesn't parse aside before it
|
||||
// is written over, so the accounts in it can still be got back. A failure
|
||||
// to read or keep an existing file stops the write.
|
||||
func keepUnreadLogins(path string) error {
|
||||
b, err := os.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Match readLogins: valid JSON can still have unreadable field types.
|
||||
var ls []savedLogin
|
||||
if json.Unmarshal(b, &ls) == nil {
|
||||
return nil
|
||||
}
|
||||
bad := path + ".bad-" + time.Now().Format("20060102-150405")
|
||||
if err := os.WriteFile(bad, b, 0o600); err != nil {
|
||||
log.Printf("logins.json doesn't parse and couldn't be kept: %v", err)
|
||||
return err
|
||||
}
|
||||
log.Printf("logins.json didn't parse; it is kept as %s", filepath.Base(bad))
|
||||
return nil
|
||||
// unreadBytes are a file's bytes, nil when it can't be read: for the log
|
||||
// to say what was wrong with it.
|
||||
func unreadBytes(path string) []byte {
|
||||
b, _ := os.ReadFile(path)
|
||||
return b
|
||||
}
|
||||
|
||||
func writeLogins(ls []savedLogin) error {
|
||||
@@ -243,20 +248,23 @@ func writeLogins(ls []savedLogin) error {
|
||||
return err
|
||||
}
|
||||
defer Changed() // an account added, switched or gone: All builds anew
|
||||
if err := keepUnreadLogins(loginsPath()); err != nil {
|
||||
// the file there now is kept first: as its last good generation, or
|
||||
// copied aside when it doesn't read, never written over unkept
|
||||
if err := lastgood.Keep(loginsPath(), validLogins, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writePrivate(loginsPath(), append(b, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
lastLoginsMu.Lock()
|
||||
lastLogins = slices.Clone(ls)
|
||||
lastLogins, loginsKnown = slices.Clone(ls), true
|
||||
lastLoginsMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// writePrivate replaces a file readable by the user alone, atomically, so
|
||||
// an agent reading it at that moment sees either version, never half.
|
||||
// an agent reading it at that moment sees either version, never half; the
|
||||
// new one is on the disk before it is renamed over the old (#1505).
|
||||
func writePrivate(path string, b []byte) error {
|
||||
defer filememo.Forget() // read again, where a request holds it
|
||||
path, err := edit.Target(path) // a symlink stays, its target written
|
||||
@@ -266,23 +274,7 @@ func writePrivate(path string, b []byte) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := tmp.Write(b); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Chmod(0o600); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return steady.Rename(tmp.Name(), path)
|
||||
return steady.WriteFile(path, b, 0o600)
|
||||
}
|
||||
|
||||
func upsertLogin(ls []savedLogin, l savedLogin) []savedLogin {
|
||||
|
||||
@@ -47,10 +47,18 @@ func TestUnreadLoginsWriteErrorsKeepCredentials(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
// the folder takes no new file, so the bad copy can't
|
||||
// be made
|
||||
blocked = p + ".bad-" + time.Now().Format("20060102-150405")
|
||||
if err := os.Mkdir(blocked, 0o700); err != nil {
|
||||
dir := filepath.Dir(p)
|
||||
if err := os.Chmod(dir, 0o500); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chmod(dir, 0o700) })
|
||||
if f, err := os.Create(filepath.Join(dir, "probe")); err == nil {
|
||||
f.Close()
|
||||
t.Skip("the filesystem does not enforce the read-only folder")
|
||||
}
|
||||
}
|
||||
err := addGoogleLogin("gemini", "new@example.com", "", googleAuth{RefreshToken: "new-refresh-token", Project: "p"})
|
||||
if chmodErr := os.Chmod(p, 0o600); chmodErr != nil {
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"maps"
|
||||
"net/http"
|
||||
@@ -40,6 +41,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
)
|
||||
@@ -296,14 +298,31 @@ var migrationsMu sync.Mutex
|
||||
func readMigrations() map[string]Migration { return heldOf("migrations", readMigrationsFile) }
|
||||
|
||||
func readMigrationsFile() map[string]Migration {
|
||||
m, _ := filememo.Read("migrations", migrationsPath(), func(b []byte) (map[string]Migration, error) {
|
||||
var m map[string]Migration
|
||||
_ = json.Unmarshal(b, &m)
|
||||
return m, nil
|
||||
})
|
||||
m, err := filememo.Read("migrations", migrationsPath(), parseMigrations)
|
||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
// one that doesn't read (all zero after a crash, #1505) is not
|
||||
// "nothing moved": a moved subscription would come back as its
|
||||
// built-in, and the next move write that over every other's
|
||||
if b, ferr := lastgood.Fallback(migrationsPath(), unreadBytes(migrationsPath()), validMigrations); ferr == nil {
|
||||
m, _ = parseMigrations(b)
|
||||
} else {
|
||||
log.Printf("migrations.json: %v", ferr)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func parseMigrations(b []byte) (map[string]Migration, error) {
|
||||
var m map[string]Migration
|
||||
err := json.Unmarshal(b, &m)
|
||||
return m, err
|
||||
}
|
||||
|
||||
func validMigrations(b []byte) bool {
|
||||
_, err := parseMigrations(b)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// MigrationOf is where the built-in id's move stands.
|
||||
func MigrationOf(id string) (Migration, bool) {
|
||||
m, ok := readMigrations()[id]
|
||||
@@ -359,6 +378,9 @@ func setMigration(id string, f func(m *Migration)) error {
|
||||
return err
|
||||
}
|
||||
defer Changed()
|
||||
if err := lastgood.Keep(migrationsPath(), validMigrations, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return writePrivate(migrationsPath(), append(b, '\n'))
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
@@ -360,11 +361,25 @@ func read() (file, error) {
|
||||
return f, &unreadableError{Path(), err}
|
||||
}
|
||||
if err := json.Unmarshal(b, &f); err != nil {
|
||||
return file{}, &unreadableError{Path(), err}
|
||||
// one left all zero by a crash (#1505) is its last good generation
|
||||
bak, ferr := lastgood.Fallback(Path(), b, validProviders)
|
||||
if ferr != nil {
|
||||
return file{}, &unreadableError{Path(), err}
|
||||
}
|
||||
f = file{}
|
||||
if err := json.Unmarshal(bak, &f); err != nil {
|
||||
return file{}, &unreadableError{Path(), err}
|
||||
}
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// validProviders is providers.json's contents read as the catalog.
|
||||
func validProviders(b []byte) bool {
|
||||
var f file
|
||||
return json.Unmarshal(b, &f) == nil
|
||||
}
|
||||
|
||||
// FileError is why providers.json can't be read, nil when it can or isn't
|
||||
// there: for what lists the providers to say so, not "none yet".
|
||||
func FileError() error {
|
||||
@@ -390,6 +405,9 @@ func store(f file) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := lastgood.Keep(p, validProviders, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writePrivate(p, append(b, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
|
||||
// #1505: a Windows machine that went down mid-write left logins.json at
|
||||
// its full length, 10,783 bytes, every one 0x00, and magpie started with
|
||||
// no accounts. Its last good generation, kept beside it, is read instead,
|
||||
// and the user told.
|
||||
func TestZeroedLoginsReadFromBackup(t *testing.T) {
|
||||
googleSandbox(t, &fakeGoogle{})
|
||||
lastgood.Reset()
|
||||
t.Cleanup(lastgood.Reset)
|
||||
for _, u := range []string{"a@x.com", "b@x.com", "c@x.com"} {
|
||||
if err := addGoogleLogin("antigravity", u, "", googleAuth{RefreshToken: "1//" + u, Project: "p"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
p := loginsPath()
|
||||
if _, err := os.Stat(lastgood.Bak(p)); err != nil {
|
||||
t.Fatalf("no last good generation kept: %v", err)
|
||||
}
|
||||
// the crash: the file as Zhangwier found it, and magpie starting anew
|
||||
if err := os.WriteFile(p, make([]byte, 10783), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lastLoginsMu.Lock()
|
||||
lastLogins, loginsKnown = nil, false
|
||||
lastLoginsMu.Unlock()
|
||||
|
||||
users := func() string {
|
||||
var us []string
|
||||
for _, l := range readLogins() {
|
||||
us = append(us, l.User)
|
||||
}
|
||||
return strings.Join(us, ",")
|
||||
}
|
||||
// the backup lags one write: it holds a and b, the write of c is the
|
||||
// one the crash took
|
||||
if got := users(); got != "a@x.com,b@x.com" {
|
||||
t.Fatalf("a zeroed logins.json read as %q", got)
|
||||
}
|
||||
if n := lastgood.Recovered(); len(n) != 1 || n[0].File != "logins.json" || !strings.Contains(n[0].Why, "10783 bytes") {
|
||||
t.Fatalf("the user isn't told: %+v", n)
|
||||
}
|
||||
// the next account added keeps them, and the zeroed file aside
|
||||
if err := addGoogleLogin("antigravity", "d@x.com", "", googleAuth{RefreshToken: "1//d", Project: "p"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := users(); got != "a@x.com,b@x.com,d@x.com" {
|
||||
t.Fatalf("after an account added: %q", got)
|
||||
}
|
||||
kept, _ := filepath.Glob(p + ".bad-*")
|
||||
if len(kept) != 1 {
|
||||
t.Fatalf("the zeroed file not kept aside: %v", kept)
|
||||
}
|
||||
if b, _ := os.ReadFile(kept[0]); !bytes.Equal(b, make([]byte, 10783)) {
|
||||
t.Fatalf("kept %d bytes", len(b))
|
||||
}
|
||||
}
|
||||
|
||||
// With no backup, a zeroed logins.json is copied aside before an account
|
||||
// added writes over it.
|
||||
func TestZeroedLoginsWithoutBackupKeptAside(t *testing.T) {
|
||||
googleSandbox(t, &fakeGoogle{})
|
||||
lastgood.Reset()
|
||||
t.Cleanup(lastgood.Reset)
|
||||
p := loginsPath()
|
||||
os.MkdirAll(filepath.Dir(p), 0o700)
|
||||
os.WriteFile(p, make([]byte, 10783), 0o600)
|
||||
lastLoginsMu.Lock()
|
||||
lastLogins, loginsKnown = nil, false
|
||||
lastLoginsMu.Unlock()
|
||||
if err := addGoogleLogin("antigravity", "new@x.com", "", googleAuth{RefreshToken: "1//n", Project: "p"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if kept, _ := filepath.Glob(p + ".bad-*"); len(kept) != 1 {
|
||||
t.Fatalf("the zeroed file not kept aside: %v", kept)
|
||||
}
|
||||
if _, err := os.Stat(lastgood.Bak(p)); err == nil {
|
||||
t.Fatal("a zeroed file kept as the last good generation")
|
||||
}
|
||||
}
|
||||
|
||||
// migrations.json says which subscriptions moved onto their plugins; one
|
||||
// zeroed by the crash is not "nothing moved".
|
||||
func TestZeroedMigrationsReadFromBackup(t *testing.T) {
|
||||
googleSandbox(t, &fakeGoogle{})
|
||||
lastgood.Reset()
|
||||
t.Cleanup(lastgood.Reset)
|
||||
for _, id := range []string{"zed", "kiro"} {
|
||||
if err := setMigration(id, func(m *Migration) { m.State = MovePlugin }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
p := migrationsPath()
|
||||
os.WriteFile(p, make([]byte, 4096), 0o600)
|
||||
if !Moved("zed") {
|
||||
t.Fatal("a zeroed migrations.json read as zed not moved")
|
||||
}
|
||||
if len(lastgood.Recovered()) != 1 {
|
||||
t.Fatalf("not noted: %+v", lastgood.Recovered())
|
||||
}
|
||||
}
|
||||
|
||||
// providers.json zeroed: its providers are its last good generation's.
|
||||
func TestZeroedProvidersReadFromBackup(t *testing.T) {
|
||||
providerFileHome(t)
|
||||
lastgood.Reset()
|
||||
t.Cleanup(lastgood.Reset)
|
||||
writeProviderFile(t, originalProviderFile)
|
||||
if err := Save(Provider{ID: "new", Name: "New", Chat: "https://new.example.invalid/v1", Key: "synthetic-new"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(Path(), make([]byte, 2048), 0o600)
|
||||
if err := FileError(); err != nil {
|
||||
t.Fatalf("a zeroed providers.json with a backup: %v", err)
|
||||
}
|
||||
ps := load().Providers
|
||||
if len(ps) != 1 || ps[0].ID != "original" {
|
||||
t.Fatalf("providers = %+v, want the backup's", ps)
|
||||
}
|
||||
}
|
||||
|
||||
// writePrivate, which writes logins.json, migrations.json and
|
||||
// providers.json, flushes the new file before the rename; one that fails
|
||||
// to flush leaves the old file.
|
||||
func TestWritePrivateSyncsBeforeRename(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "logins.json")
|
||||
os.WriteFile(p, []byte(`["old"]`), 0o600)
|
||||
defer func() { steady.Sync = (*os.File).Sync }()
|
||||
steady.Sync = func(*os.File) error { return errors.New("the disk went away") }
|
||||
if err := writePrivate(p, []byte(`["new"]`)); err == nil {
|
||||
t.Fatal("written without a flush")
|
||||
}
|
||||
if b, _ := os.ReadFile(p); string(b) != `["old"]` {
|
||||
t.Fatalf("a failed flush left %q", b)
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
|
||||
// Codex lists, in its history and its resume picker, only the sessions made
|
||||
@@ -450,6 +451,11 @@ func rewriteCodexProvider(path, to string) (bool, error) {
|
||||
if err := tmp.Chmod(fi.Mode().Perm()); err != nil {
|
||||
return false, err
|
||||
}
|
||||
// the user's session on the disk before it is renamed over the old
|
||||
// one: a machine that goes down between can leave it all zero (#1505)
|
||||
if err := steady.Sync(tmp); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/fonts"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/redact"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
@@ -830,11 +831,24 @@ func load() Settings {
|
||||
// the settings for every model of every agent (hundreds of reads, a
|
||||
// fifth of the Agents page's wait)
|
||||
if b, err := filememo.Read("settings", Path(), func(b []byte) ([]byte, error) { return b, nil }); err == nil {
|
||||
_ = json.Unmarshal(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")), &s)
|
||||
// parsed once: this runs for every model of every agent
|
||||
if err := json.Unmarshal(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")), &s); err != nil {
|
||||
// one left all zero by a crash (#1505) is its last good generation
|
||||
if bak, err := lastgood.Fallback(Path(), b, validSettings); err == nil {
|
||||
s = Settings{}
|
||||
_ = json.Unmarshal(bytes.TrimPrefix(bak, []byte("\xef\xbb\xbf")), &s)
|
||||
}
|
||||
}
|
||||
}
|
||||
return s.normal()
|
||||
}
|
||||
|
||||
// validSettings is settings.json's contents read as Settings.
|
||||
func validSettings(b []byte) bool {
|
||||
var s Settings
|
||||
return json.Unmarshal(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")), &s) == nil
|
||||
}
|
||||
|
||||
// CheckProxy says whether p is a proxy setting magpie takes: "" (follow),
|
||||
// "direct", or an http://, https:// or socks5:// address (host:port
|
||||
// meaning http). The global Proxy and a provider's own are both checked
|
||||
@@ -1037,7 +1051,14 @@ func save(s Settings, recording bool) error {
|
||||
if len(bytes.TrimSpace(b)) != 0 {
|
||||
var stored Settings
|
||||
if err := json.Unmarshal(b, &stored); err != nil {
|
||||
return fmt.Errorf("could not read settings at %s; repair or move that file aside before saving: %w", Path(), err)
|
||||
// a file a crash left all zero (#1505) is saved over once it
|
||||
// is kept aside, when Load had its last good generation
|
||||
bak, ferr := lastgood.Fallback(Path(), b, validSettings)
|
||||
if ferr != nil {
|
||||
return fmt.Errorf("could not read settings at %s; repair or move that file aside before saving: %w", Path(), err)
|
||||
}
|
||||
stored = Settings{}
|
||||
_ = json.Unmarshal(bytes.TrimPrefix(bak, []byte("\xef\xbb\xbf")), &stored)
|
||||
}
|
||||
consent = stored.GatewayConversations
|
||||
}
|
||||
@@ -1047,6 +1068,11 @@ func save(s Settings, recording bool) error {
|
||||
if !recording {
|
||||
s.GatewayConversations = consent
|
||||
}
|
||||
// the file there now is kept first, before anything below can make
|
||||
// one: as the last good generation, or aside when it doesn't read
|
||||
if err := lastgood.Keep(Path(), validSettings, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(Dir(), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
)
|
||||
|
||||
// A settings.json a crash left at its length, every byte zero (#1505), is
|
||||
// read from its last good generation, and saved over once kept aside.
|
||||
func TestZeroedSettingsReadFromBackup(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
lastgood.Reset()
|
||||
t.Cleanup(lastgood.Reset)
|
||||
for _, theme := range []string{"dark", "light"} {
|
||||
if err := Save(Settings{Theme: theme}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
os.WriteFile(Path(), make([]byte, 1873), 0o600)
|
||||
if got := Load().Theme; got != "dark" {
|
||||
t.Fatalf("a zeroed settings.json read with theme %q, want the backup's", got)
|
||||
}
|
||||
if len(lastgood.Recovered()) != 1 {
|
||||
t.Fatalf("not noted: %+v", lastgood.Recovered())
|
||||
}
|
||||
if err := Save(Settings{Theme: "system"}); err != nil {
|
||||
t.Fatalf("saving over a zeroed file with a backup: %v", err)
|
||||
}
|
||||
if kept, _ := filepath.Glob(Path() + ".bad-*"); len(kept) != 1 {
|
||||
t.Fatalf("the zeroed file not kept aside: %v", kept)
|
||||
}
|
||||
if got := Load().Theme; got != "system" {
|
||||
t.Fatalf("after a save: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
@@ -97,3 +98,36 @@ func ReadFile(p string) ([]byte, error) {
|
||||
func Rename(oldpath, newpath string) error {
|
||||
return retry(func() error { return os.Rename(oldpath, newpath) })
|
||||
}
|
||||
|
||||
// Sync is (*os.File).Sync; a test stands in for it to make a flush fail.
|
||||
var Sync = (*os.File).Sync
|
||||
|
||||
// WriteFile replaces p with b, mode perm, through a temp file beside it
|
||||
// that is flushed to the disk before it is renamed over p. A rename reaches
|
||||
// the disk on its own schedule and the data behind it later: a Windows
|
||||
// machine that went down between the two left logins.json and
|
||||
// plugin-auth.json at their full length with every byte zero (#1505). A
|
||||
// write or flush that fails removes the temp file and leaves p as it was.
|
||||
func WriteFile(p string, b []byte, perm fs.FileMode) error {
|
||||
tmp, err := os.CreateTemp(filepath.Dir(p), "."+filepath.Base(p)+".*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tmp.Write(b)
|
||||
if err == nil {
|
||||
err = tmp.Chmod(perm)
|
||||
}
|
||||
if err == nil {
|
||||
err = Sync(tmp)
|
||||
}
|
||||
if cerr := tmp.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = Rename(tmp.Name(), p)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(tmp.Name())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package steady
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A file is flushed to the disk before it is renamed over the old one: a
|
||||
// Windows machine that went down between the two left logins.json at its
|
||||
// full length, every byte zero (#1505). The flush is of the new contents,
|
||||
// before the old file is replaced; one that fails leaves the old file and
|
||||
// no temp file beside it.
|
||||
func TestWriteFileSyncsBeforeRename(t *testing.T) {
|
||||
defer func() { Sync = (*os.File).Sync }()
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "logins.json")
|
||||
if err := os.WriteFile(p, []byte(`["old"]`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
synced := 0
|
||||
Sync = func(f *os.File) error {
|
||||
synced++
|
||||
if b, _ := os.ReadFile(p); string(b) != `["old"]` {
|
||||
t.Errorf("flushed after the rename: the file was already %q", b)
|
||||
}
|
||||
if b, _ := os.ReadFile(f.Name()); string(b) != `["new"]` {
|
||||
t.Errorf("flushed %q, want the new contents", b)
|
||||
}
|
||||
return f.Sync()
|
||||
}
|
||||
if err := WriteFile(p, []byte(`["new"]`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if synced != 1 {
|
||||
t.Fatalf("flushed %d times, want once", synced)
|
||||
}
|
||||
if b, _ := os.ReadFile(p); string(b) != `["new"]` {
|
||||
t.Fatalf("file = %q", b)
|
||||
}
|
||||
|
||||
Sync = func(*os.File) error { return errors.New("the disk went away") }
|
||||
if err := WriteFile(p, []byte(`["newer"]`), 0o600); err == nil {
|
||||
t.Fatal("a flush that failed reported as written")
|
||||
}
|
||||
if b, _ := os.ReadFile(p); string(b) != `["new"]` {
|
||||
t.Fatalf("a failed flush changed the file to %q", b)
|
||||
}
|
||||
if left, _ := os.ReadDir(dir); len(left) != 1 {
|
||||
t.Fatalf("a failed write left %v", left)
|
||||
}
|
||||
}
|
||||
@@ -38,10 +38,14 @@ func printed(t *testing.T, fn func() error) (string, error) {
|
||||
|
||||
// A providers.json that can't be read is not "no providers yet": magpie
|
||||
// providers and magpie models end in why, and leave the file as it is
|
||||
// (#415's review).
|
||||
// (#415's review). With no good providers.json.bak to read instead
|
||||
// (#1505), it is unknown.
|
||||
func TestProvidersCmdSaysUnreadable(t *testing.T) {
|
||||
groupsHome(t)
|
||||
catalog.Changed = nil
|
||||
if err := os.Remove(provider.Path() + ".bak"); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
whole, err := os.ReadFile(provider.Path())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
Reference in New Issue
Block a user