Files
magpie/internal/gui/tests/data-folder.test.cjs
T
yetone bb4dd86790 appdir: magpie's files and cache move to another disk, a link left where they were (CHENGJIAHEGOXIS and buhaodeshiyehao on X)
CHENGJIAHEGOXIS asked to keep magpie's data and cache on an external SSD
instead of the Mac's own disk. buhaodeshiyehao asked to keep magpie's
personal data on another disk. Settings › Sync now has a Data folder row.
It shows where magpie's files are, with Show, Move… and Move back.
`magpie data` does the same from a terminal.

- What moves: appdir.Config() and Cache() only, into <picked>/magpie/config
  and /cache. The agents' own folders and session histories stay where
  each agent reads them. A link is left at each old path, so every path
  the agents were given still works. On Windows, when symlinks need a
  privilege (#973), the link is a junction; library's junction code moved
  into appdir for this.
- Never under a running magpie. Move… explains first in the app's own
  dialog, then asks for the move (move-to.json). The app restarts itself
  through the update path's relaunch and quits, and the new process makes
  the move in cli.Main before it reads anything, once. A failed move is
  kept in move-result.json and shown under the row. When another magpie
  serves the gateway, or for magpie web, the app doesn't restart, and the
  row says the move waits, with Cancel.
- Refused before anything quits: a relative or missing folder, a
  magpie folder there with files in it, or a folder inside magpie's own.
- One disk: a rename. Across disks: a copy. The old folder is put aside
  until the link is made, and a failed copy leaves everything as it was.
- Disk unplugged: magpie stops with an error (and a native alert from the
  app, as #989) instead of starting empty and writing over the link.
- Usage history in auto backups is left for a follow-up: auto backups are
  plain JSON kept 7 times, and usage is large and synced separately.

Docs: sync-backup.md has a "Data folder on another disk" section, and
docs/start's #data-folder (en, zh, ja) describes Move….

Run (mote, at this tree on 0791c91c5):
- gofmt -l: clean
- go vet: darwin, linux -tags nogui and windows, for appdir, cli, gui and
  library: ok
- go test -count=1 ./internal/appdir ./internal/cli ./internal/library
  ./internal/gui: ok. cli was red first, on TestEveryRouteHasACommandOrIsNamed;
  the routes are now mapped to magpie data.
- Windows (xiaomi-gpu): appdir's Move tests, including TestMoveByJunction
  with symlink forced to fail with ERROR_PRIVILEGE_NOT_HELD, and
  TestDataFolderMoveRestarts: ok. TestFoldersJoinedOnce is red there,
  which is #4846 (appdir.go is untouched).
- GUI, chromium + webkit: data-folder (5 languages x 1100/420px),
  auto-backup, sync-*, settings-sections, segs-press-redraw, old-webkit,
  github-sync, s3-sync, skill-how, usage-computers,
  webdav-settings-refresh, i18n-keys and i18n-en-no-cjk: ok except
  phone-no-sideways de 375 (#5869) and s3-sync webkit en (#3413/#5872,
  red 3 of 3 on this tree too), both already red on main.
- Linux (WSL magpie-desktop): appdir -run Move and
  TestDataFolderMoveRestarts (nogui): ok.

Again after rebasing on 0a44c1c84 (mote): gofmt, the three vets, go test
./internal/appdir ./internal/cli ./internal/gui, and the GUI files
data-folder, i18n-keys, i18n-en-no-cjk, auto-backup and settings-sections
in both engines (60 of 60): ok. Pushed on 5426c43cc, which touches only
the gateway's dsh_compact and the routing plugin, none of these files.

Broken by hand (each went red):
- no removal of a half copy: TestMoveCopyFailsLeavesAll "a half copy
  is left on the disk"
- no Unreachable check for a gone disk: TestMovedDiskGoneIsUnreachable
- restarting with another magpie serving: TestDataFolderMoveRestarts
  "2 restarts"

Not tried: a real app restart making a real move on a real external disk
(the restart is the update path's relaunch, faked in the test); a real
unplug.
2026-11-10 13:46:13 +08:00

170 lines
9.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Run with Node's test runner and Playwright on the module path; see README.md.
// Settings › Sync's Data folder (CHENGJIAHEGOXIS and buhaodeshiyehao on X:
// magpie's files on another disk). The row shows where magpie's files are,
// with Show and Move…; Move… says what a move does in the app's own dialog
// before anything is picked, Cancel posts nothing, and Choose a folder…
// posts the move, the button then saying magpie restarts. A move that
// can't restart (another magpie serving) says it waits, with Cancel; once
// moved, the row shows the folder on the disk and Move back, and a move
// that failed says why. In all five languages, at 1100 and 420px,
// Chromium and WebKit, nothing wider than the window. The API is faked;
// nothing is moved.
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 { openPart } = require("./reader.cjs");
const { strings } = require("./strings.cjs");
const assets = path.resolve(__dirname, "../assets");
const { I18N } = strings();
const tr = (lang, k, vars = {}) => {
const s = lang === "en" ? k : I18N[lang][k];
assert.equal(typeof s, "string", `${lang} has ${JSON.stringify(k)}`);
return s.replace(/\{(\w+)\}/g, (_, v) => vars[v]);
};
const home = { config: "~/.config/magpie", cache: "~/.cache/magpie" };
const disk = "/Volumes/Samsung T7 Shield with a long name to wrap/magpie";
function serve(lang, posts, state) {
const settings = {
theme: "light", lang, tray: "panel", version: "test", dir: "/tmp/magpie",
gateway: "http://127.0.0.1:3425", visionModels: [], imageGenModels: [],
fx: { rate: 7.2, stale: false },
};
return async (route) => {
const request = route.request();
const pathname = new URL(request.url()).pathname;
const json = (data) => route.fulfill({ json: data });
if (pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (pathname === "/api/settings") return json(settings);
if (pathname === "/api/usage/quotas") return json([]);
if (pathname === "/api/groups") return json({ groups: [], models: [] });
if (pathname === "/api/plugins") return json({ plugins: [] });
if (pathname === "/api/davsync") return json({ on: false });
if (pathname === "/api/autobackup") return json({ on: false, hours: 24, keep: 7, dir: "~/backups", backups: [] });
if (pathname === "/api/datafolder") return json(state.view);
if (pathname.startsWith("/api/datafolder/")) {
const action = pathname.slice("/api/datafolder/".length);
posts.push(action);
if (action === "move") {
state.view = { ...state.view, pending: disk, other: state.other };
return json({ view: state.view, restart: !state.other });
}
if (action === "cancel") state.view = { ...state.view, pending: undefined, other: undefined };
return json({ view: state.view });
}
if (pathname.startsWith("/api/")) return json({});
const file = path.join(assets, pathname === "/" ? "index.html" : pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
return route.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [1100, 420]) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
const w = (k, vars) => tr(lang, k, vars);
test(`${engine} ${width}px ${lang}: Data folder moves after saying so, and says where it is`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
const errors = [], posts = [];
const state = { view: { ...home }, other: false };
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts, state));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${width}-${lang}-data-folder.png`), fullPage: true });
}
await browser.close();
});
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
await page.goto("http://magpie.test/");
await page.locator("#prefs").click();
await openPart(page, "sync");
const list = page.locator("#syncList");
const row = list.locator(".row.pref.data-folder");
await row.waitFor({ state: "visible" });
// the app opened again on the server's view now
const reopen = async () => {
await page.reload();
await page.locator("#prefs").click();
await openPart(page, "sync");
await row.waitFor({ state: "visible" });
};
assert.equal(await row.locator(".name").textContent(), w("Data folder"));
assert.equal(await row.locator(".data-folder-dir").textContent(), home.config);
for (const b of ["Show", "Move…"]) await row.locator("button", { hasText: w(b) }).waitFor();
assert.equal(await row.locator("button", { hasText: w("Move back") }).count(), 0, "nothing to move back from");
// Move… says what it does first; Cancel posts nothing
await row.locator("button", { hasText: w("Move…") }).click();
const ask = page.locator(".data-folder-ask");
await ask.waitFor({ state: "visible" });
assert.equal(await ask.locator(".ehead b").textContent(), w("Move magpie's files to another disk?"));
await ask.locator("button", { hasText: w("Cancel") }).click();
await ask.waitFor({ state: "detached" });
assert.deepEqual(posts, []);
// Choose a folder… moves: magpie restarts for it
await row.locator("button", { hasText: w("Move…") }).click();
await ask.locator("button", { hasText: w("Choose a folder…") }).click();
await page.waitForFunction((s) => document.querySelector(".data-folder-ask .primary")?.textContent === s, w("Restarting…"));
assert.deepEqual(posts, ["move"]);
await page.evaluate(() => closeConfirmAsk());
// another magpie serving: the move waits, said, with Cancel
state.view = { ...home };
state.other = true;
await reopen();
await row.locator("button", { hasText: w("Move…") }).click();
await ask.locator("button", { hasText: w("Choose a folder…") }).click();
await ask.waitFor({ state: "detached" });
await page.waitForFunction(() => document.querySelectorAll("#syncList .data-folder-said").length === 2);
assert.deepEqual(await row.locator(".data-folder-said").allTextContents(), [
w("Moves to {dir} when magpie starts again", { dir: disk }),
w("Another magpie serves the gateway (magpie serve): stop it, then open magpie again to move them"),
]);
assert.equal(await row.locator("button", { hasText: w("Move…") }).count(), 0, "no second move while one waits");
await row.locator("button", { hasText: w("Cancel") }).click();
await page.waitForFunction(() => document.querySelectorAll("#syncList .data-folder-said").length === 0);
assert.deepEqual(posts, ["move", "move", "cancel"]);
// moved: the folder on the disk, and Move back, which asks too;
// the last failure said under it
state.view = { ...home, configAt: disk + "/config", cacheAt: disk + "/cache", moved: disk, error: "/Volumes/X/magpie has files in it already: pick another folder, or empty it" };
await reopen();
assert.equal(await row.locator(".data-folder-dir").textContent(), disk);
const bad = row.locator(".data-folder-said.bad");
assert.equal(await bad.textContent(), w("The last move wasn't made: {error}", { error: state.view.error }));
await row.locator("button", { hasText: w("Move back") }).click();
await ask.waitFor({ state: "visible" });
assert.equal(await ask.locator(".ehead b").textContent(), w("Move magpie's files back to this computer?"));
assert.match(await ask.textContent(), new RegExp(home.config.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
await ask.locator("button", { hasText: w("Cancel") }).click();
await ask.waitFor({ state: "detached" });
// nothing wider than the window, the long folder wrapping
const wide = await page.evaluate(() => {
const out = [];
if (document.scrollingElement.scrollWidth > innerWidth) out.push("page " + document.scrollingElement.scrollWidth);
for (const r of document.querySelectorAll("#syncList .row.pref")) {
const b = r.getBoundingClientRect();
if (b.right > innerWidth + 0.5 || r.scrollWidth > r.clientWidth + 1) out.push(r.querySelector(".name")?.textContent + " " + b.right + "/" + r.scrollWidth + ">" + r.clientWidth);
}
return out;
});
assert.deepEqual(wide, [], "rows wider than the window");
assert.deepEqual(errors, []);
});
}
}
}