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 on0791c91c5): - 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 on0a44c1c84(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 on5426c43cc, 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.
This commit is contained in:
@@ -203,12 +203,58 @@ clock.
|
||||
case aside off Linux), the default included; Settings then says under the
|
||||
folder that a reinstalled system or a lost disk takes the backups too, and
|
||||
to pick one on another disk or a cloud drive's (two_2025. on Discord,
|
||||
magpie on C:). Keeping everything elsewhere is portable mode
|
||||
(`internal/appdir`); docs/start's `#data-folder` gives both
|
||||
(`TestAutoInsideMagpiesFolder`, `auto-backup.test.cjs`).
|
||||
magpie on C:). Keeping everything elsewhere is the Data folder's move
|
||||
(below) or portable mode (`internal/appdir`); docs/start's
|
||||
`#data-folder` gives all three (`TestAutoInsideMagpiesFolder`,
|
||||
`auto-backup.test.cjs`).
|
||||
- **Sign-ins:** off unless picked (`SignIns`, with `Passphrase`); see
|
||||
[Sign-ins, when picked](#sign-ins-when-picked).
|
||||
|
||||
## Data folder on another disk
|
||||
|
||||
Settings › Sync's Data folder (CHENGJIAHEGOXIS and buhaodeshiyehao on X)
|
||||
moves magpie's own files and cache to another disk, and back.
|
||||
[`internal/appdir/move.go`](../../internal/appdir/move.go) does it:
|
||||
|
||||
- **What moves:** `appdir.Config()` and `appdir.Cache()` only, into
|
||||
`<picked>/magpie/config` and `<picked>/magpie/cache`. The agents' own
|
||||
folders (`~/.claude`, `~/.codex`…) and their session histories stay where
|
||||
each agent reads them. A link is left at each old path (a symlink, or a
|
||||
junction on Windows when symlinks need a privilege, as in #973), so every
|
||||
path magpie and the agents were given still works. A portable magpie is
|
||||
never moved.
|
||||
- **Refused before anything quits** (`Target`): a relative path, a folder
|
||||
that isn't there, a `magpie` folder there with files in it, or a folder
|
||||
inside magpie's own folders.
|
||||
- **Never under a running magpie.** `AskMove` writes `move-to.json` in the
|
||||
config folder. The GUI then starts itself again (`restartSelf`, the
|
||||
update path's relaunch) and quits; when another magpie serves the gateway
|
||||
(`magpie serve`, a launch agent), or for magpie web, it doesn't restart,
|
||||
and the row says the move waits. The next start runs `MovePending` in
|
||||
`cli.Main` before anything reads a file, after the old process is gone
|
||||
and only when no gateway answers. It is made once: a failure is not asked
|
||||
for again, and why is kept in `move-result.json` for the row.
|
||||
- **How:** within one disk, a rename. Across disks, a copy, and the old
|
||||
folder is put aside (`.moved`) until the link is made, then removed; a
|
||||
failed copy removes the half copy and leaves the old folder as it was.
|
||||
Moving back takes the link away and renames the folder home; across
|
||||
disks it puts the link back, copies to `<config>.moving` and renames that
|
||||
into place. The empty `magpie` folder on the disk is then removed. The
|
||||
config moves first: a cache that fails after it says so and leaves the
|
||||
config moved.
|
||||
- **Disk gone:** a link that leads nowhere is `UnreachableError`. `cli.Main`
|
||||
stops on it, with a native alert from the app (as #989), rather than
|
||||
starting an empty magpie that would write a new config over the link.
|
||||
- **CLI:** `magpie data` says where they are; `magpie data move <folder>`
|
||||
moves at once with no gateway up, otherwise asks for it;
|
||||
`magpie data move --home` and `magpie data cancel`.
|
||||
|
||||
Routes: `GET /api/datafolder`, `POST /api/datafolder/{move,home,cancel,reveal}`
|
||||
([`datafolder.go`](../../internal/gui/datafolder.go)). Tests:
|
||||
`internal/appdir/move_test.go` (both disks, refused targets, a failed copy,
|
||||
disk gone, once only), `move_windows_test.go` (the junction),
|
||||
`TestDataFolderMoveRestarts` and `data-folder.test.cjs`.
|
||||
|
||||
## Sign-ins, when picked
|
||||
|
||||
A sign-in (a subscription account in logins.json, Codex's auth.json, a
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build !windows
|
||||
|
||||
package appdir
|
||||
|
||||
import "os"
|
||||
|
||||
// dirLink makes link a link to the folder target.
|
||||
func dirLink(target, link string) error { return os.Symlink(target, link) }
|
||||
@@ -0,0 +1,84 @@
|
||||
//go:build windows
|
||||
|
||||
package appdir
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"unicode/utf16"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// dirLink makes link a link to the folder target. Windows lets a user make
|
||||
// a symlink only with Developer Mode on or as an administrator (#973);
|
||||
// without that it is a junction, which every user can make and every
|
||||
// program follows as it does a symlink to a folder. A junction can't point
|
||||
// at a network share: that is still the symlink's error.
|
||||
func dirLink(target, link string) error {
|
||||
err := symlink(target, link)
|
||||
if err == nil || !errors.Is(err, windows.ERROR_PRIVILEGE_NOT_HELD) {
|
||||
return err
|
||||
}
|
||||
if jerr := Junction(target, link); jerr != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// symlink is os.Symlink; a test has it refused as without Developer Mode.
|
||||
var symlink = os.Symlink
|
||||
|
||||
// Junction makes link a junction to the folder target: an empty folder
|
||||
// given a mount-point reparse point. Nothing is left at link when it fails.
|
||||
func Junction(target, link string) error {
|
||||
abs, err := filepath.Abs(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if v := filepath.VolumeName(abs); len(v) != 2 || v[1] != ':' {
|
||||
return errors.New("a junction needs a local drive path: " + abs)
|
||||
}
|
||||
if err := os.Mkdir(link, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := setMountPoint(link, abs); err != nil {
|
||||
os.Remove(link)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func setMountPoint(dir, target string) error {
|
||||
p, err := windows.UTF16PtrFromString(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h, err := windows.CreateFile(p, windows.GENERIC_WRITE, 0, nil, windows.OPEN_EXISTING,
|
||||
windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer windows.CloseHandle(h)
|
||||
sub := utf16.Encode([]rune(`\??\` + target))
|
||||
shown := utf16.Encode([]rune(target))
|
||||
// REPARSE_DATA_BUFFER, MountPointReparseBuffer: both names end in a NUL
|
||||
path := make([]uint16, 0, len(sub)+len(shown)+2)
|
||||
path = append(append(append(append(path, sub...), 0), shown...), 0)
|
||||
data := make([]byte, 8+2*len(path))
|
||||
binary.LittleEndian.PutUint16(data[0:], 0)
|
||||
binary.LittleEndian.PutUint16(data[2:], uint16(2*len(sub)))
|
||||
binary.LittleEndian.PutUint16(data[4:], uint16(2*(len(sub)+1)))
|
||||
binary.LittleEndian.PutUint16(data[6:], uint16(2*len(shown)))
|
||||
for i, c := range path {
|
||||
binary.LittleEndian.PutUint16(data[8+2*i:], c)
|
||||
}
|
||||
buf := make([]byte, 8+len(data))
|
||||
binary.LittleEndian.PutUint32(buf[0:], windows.IO_REPARSE_TAG_MOUNT_POINT)
|
||||
binary.LittleEndian.PutUint16(buf[4:], uint16(len(data)))
|
||||
copy(buf[8:], data)
|
||||
var n uint32
|
||||
return windows.DeviceIoControl(h, windows.FSCTL_SET_REPARSE_POINT, &buf[0], uint32(len(buf)), nil, 0, &n, nil)
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
package appdir
|
||||
|
||||
// Moving magpie's folders to another disk (CHENGJIAHEGOXIS on X: from the
|
||||
// Mac's own disk to an external SSD; buhaodeshiyehao on X: personal data
|
||||
// kept on another disk). The folder magpie keeps its files in (Config) and
|
||||
// the one for what it can fetch again (Cache) go into a folder named
|
||||
// "magpie" in the one the user picks, as config and cache, and where each
|
||||
// was is left a link to it: a symlink, or on Windows a junction when the
|
||||
// user may not make symlinks (#973). Nothing else changes: every path magpie
|
||||
// reads is the one it always was, and so is every path magpie has written
|
||||
// into an agent's config, a skill link or an MCP server's command, all of
|
||||
// which keep working through the link.
|
||||
//
|
||||
// A move is never made under a running magpie: the app asks for it
|
||||
// (AskMove), quits, and the magpie it starts again makes it (MovePending,
|
||||
// from the cli's startUp, once the one it replaces has exited and before
|
||||
// anything is read or written). `magpie data move` makes it at once when no
|
||||
// magpie answers at the gateway's address. Within one disk it is a rename;
|
||||
// across disks a copy, and what was here is deleted only once the link is
|
||||
// in place. A copy that fails (the disk full, a file unreadable) is deleted
|
||||
// and everything stays where it was.
|
||||
//
|
||||
// Moving back (AskMove("")) copies the files home and takes the link away.
|
||||
//
|
||||
// The other disk unplugged is not a new magpie: a link that leads nowhere
|
||||
// is Unreachable, and main stops with that error rather than start an
|
||||
// empty setup in its place, which would read as everything lost and then
|
||||
// be written over by whatever the user did next (#989). Connecting the
|
||||
// disk again is the fix; the files never left it.
|
||||
//
|
||||
// A portable magpie isn't moved: its data folder is already wherever the
|
||||
// user puts magpie.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MoveName is the folder made in the one the user picks: config and cache
|
||||
// go into it.
|
||||
const MoveName = "magpie"
|
||||
|
||||
const (
|
||||
moveAsked = "move-to.json" // in Config: a move made at the next start
|
||||
moveResult = "move-result.json" // in Config: why the last one wasn't made
|
||||
)
|
||||
|
||||
// Place is where magpie's folders are.
|
||||
type Place struct {
|
||||
Config string `json:"config"` // where magpie reaches its files (~/.config/magpie)
|
||||
Cache string `json:"cache"` // and its cache (~/.cache/magpie)
|
||||
ConfigAt string `json:"configAt,omitempty"` // the folder Config links to, "" when it is no link
|
||||
CacheAt string `json:"cacheAt,omitempty"`
|
||||
// Moved is the folder they were moved into (Dir(ConfigAt)), "" when
|
||||
// they are where magpie keeps them by default
|
||||
Moved string `json:"moved,omitempty"`
|
||||
Portable bool `json:"portable,omitempty"` // a portable magpie, never moved
|
||||
// Pending is the folder a move asked for goes into at the next start,
|
||||
// "home" for back to the default; "" when none is asked for
|
||||
Pending string `json:"pending,omitempty"`
|
||||
Error string `json:"error,omitempty"` // why the last move wasn't made
|
||||
}
|
||||
|
||||
// Where says where magpie's folders are.
|
||||
func Where() Place {
|
||||
p := Place{Config: Config(), Cache: Cache(), Portable: Portable() != ""}
|
||||
if t, ok := linkOf(p.Config); ok {
|
||||
p.ConfigAt = t
|
||||
p.Moved = filepath.Dir(t)
|
||||
}
|
||||
if t, ok := linkOf(p.Cache); ok {
|
||||
p.CacheAt = t
|
||||
}
|
||||
if a, err := readAsked(); err == nil && a != nil {
|
||||
p.Pending = a.To
|
||||
if p.Pending == "" {
|
||||
p.Pending = "home"
|
||||
}
|
||||
}
|
||||
if b, err := os.ReadFile(filepath.Join(p.Config, moveResult)); err == nil {
|
||||
var r struct{ Error string }
|
||||
if json.Unmarshal(b, &r) == nil {
|
||||
p.Error = r.Error
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
type asked struct {
|
||||
To string `json:"to"` // the folder config and cache go into; "" is home
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
func readAsked() (*asked, error) {
|
||||
b, err := os.ReadFile(filepath.Join(Config(), moveAsked))
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var a asked
|
||||
if err := json.Unmarshal(b, &a); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", moveAsked, err)
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// Target is the folder magpie's folders go into when the user picks dir,
|
||||
// checked: an absolute folder that is there and can be written in, whose
|
||||
// "magpie" folder is empty or not there yet (or is where they are now),
|
||||
// and that is neither in magpie's folders nor holds them. "" is home.
|
||||
func Target(dir string) (string, error) {
|
||||
if Portable() != "" {
|
||||
return "", errors.New("this magpie is portable: its files are in the data folder beside it, which moves with it")
|
||||
}
|
||||
if dir == "" {
|
||||
if _, ok := linkOf(Config()); !ok {
|
||||
if _, ok := linkOf(Cache()); !ok {
|
||||
return "", errors.New("magpie's files are in their default folder already")
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
if !filepath.IsAbs(dir) {
|
||||
return "", fmt.Errorf("%s is not an absolute path", dir)
|
||||
}
|
||||
dir = filepath.Clean(dir)
|
||||
fi, err := os.Stat(dir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !fi.IsDir() {
|
||||
return "", fmt.Errorf("%s is not a folder", dir)
|
||||
}
|
||||
if err := canWrite(dir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
root := filepath.Join(dir, MoveName)
|
||||
if cur, ok := linkOf(Config()); ok && same(filepath.Dir(cur), root) {
|
||||
return "", fmt.Errorf("magpie's files are in %s already", root)
|
||||
}
|
||||
real := func(p string) string {
|
||||
if r, err := filepath.EvalSymlinks(p); err == nil {
|
||||
return r
|
||||
}
|
||||
return p
|
||||
}
|
||||
d := real(dir)
|
||||
for _, at := range []string{Config(), Cache()} {
|
||||
if a := real(at); same(a, d) || within(d, a) {
|
||||
return "", fmt.Errorf("%s is in magpie's folder %s", dir, at)
|
||||
}
|
||||
}
|
||||
if err := emptyOrNone(root); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return root, nil
|
||||
}
|
||||
|
||||
// canWrite says whether a file can be made in dir.
|
||||
func canWrite(dir string) error {
|
||||
f, err := os.CreateTemp(dir, ".magpie-write-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't write in %s: %w", dir, err)
|
||||
}
|
||||
name := f.Name()
|
||||
f.Close()
|
||||
return os.Remove(name)
|
||||
}
|
||||
|
||||
// emptyOrNone is nil when dir isn't there or is an empty folder.
|
||||
func emptyOrNone(dir string) error {
|
||||
es, err := os.ReadDir(dir)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(es) > 0 {
|
||||
return fmt.Errorf("%s has files in it already: pick another folder, or empty it", dir)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AskMove has magpie's folders moved into the folder named "magpie" in
|
||||
// dir, or home for "", when magpie next starts. It checks the folder now,
|
||||
// so the user hears what is wrong with it before magpie quits.
|
||||
func AskMove(dir string) (string, error) {
|
||||
root, err := Target(dir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
b, _ := json.Marshal(asked{To: root, At: time.Now()})
|
||||
if err := os.WriteFile(filepath.Join(Config(), moveAsked), b, 0o600); err != nil {
|
||||
return "", err
|
||||
}
|
||||
os.Remove(filepath.Join(Config(), moveResult))
|
||||
return root, nil
|
||||
}
|
||||
|
||||
// MoveAsked says whether a move is asked for, to be made at the next start.
|
||||
func MoveAsked() bool {
|
||||
_, err := os.Stat(filepath.Join(Config(), moveAsked))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// CancelMove forgets a move asked for.
|
||||
func CancelMove() error {
|
||||
err := os.Remove(filepath.Join(Config(), moveAsked))
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// MovePending makes the move AskMove asked for, if one was. It is made
|
||||
// once: the request is taken away first, so a move that fails, or a magpie
|
||||
// that dies in it, isn't tried at every start. Why it failed is kept for
|
||||
// Settings to say. The caller makes sure no other magpie is running.
|
||||
func MovePending() (bool, error) {
|
||||
a, err := readAsked()
|
||||
if a == nil && err == nil {
|
||||
return false, nil
|
||||
}
|
||||
os.Remove(filepath.Join(Config(), moveAsked))
|
||||
if err == nil {
|
||||
err = Move(a.To)
|
||||
}
|
||||
if err != nil {
|
||||
b, _ := json.Marshal(map[string]string{"error": err.Error()})
|
||||
os.WriteFile(filepath.Join(Config(), moveResult), b, 0o600)
|
||||
log.Printf("appdir: magpie's folders weren't moved: %v", err)
|
||||
return false, err
|
||||
}
|
||||
os.Remove(filepath.Join(Config(), moveResult))
|
||||
log.Printf("appdir: magpie's folders are in %s now", Where().Moved)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Move moves magpie's folders into root (root/config and root/cache), or
|
||||
// home for "", now. Nothing of magpie's may be running.
|
||||
func Move(root string) error {
|
||||
if Portable() != "" {
|
||||
return errors.New("this magpie is portable: its files are in the data folder beside it, which moves with it")
|
||||
}
|
||||
cfg, cache := Config(), Cache()
|
||||
prev, _ := linkOf(cfg) // the folder on the other disk, for a move home
|
||||
cfgTo, cacheTo := cfg, cache
|
||||
if root != "" {
|
||||
cfgTo, cacheTo = filepath.Join(root, "config"), filepath.Join(root, "cache")
|
||||
}
|
||||
if err := moveOne(cfg, cfgTo); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := moveOne(cache, cacheTo); err != nil {
|
||||
return fmt.Errorf("magpie's files moved, but its cache didn't: %w", err)
|
||||
}
|
||||
if root == "" && prev != "" {
|
||||
// the folder they were in on the other disk, if nothing else is in it
|
||||
os.Remove(filepath.Dir(prev))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// moveOne moves the folder magpie reaches at at so that it is at to: to
|
||||
// another disk with a link left at at, or home (to == at), the link
|
||||
// replaced by the folder.
|
||||
func moveOne(at, to string) error {
|
||||
cur, linked := linkOf(at)
|
||||
if !linked {
|
||||
cur = at
|
||||
}
|
||||
if same(cur, to) {
|
||||
return nil
|
||||
}
|
||||
fi, err := os.Stat(cur)
|
||||
there := err == nil
|
||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
if there && !fi.IsDir() {
|
||||
return fmt.Errorf("%s is not a folder", cur)
|
||||
}
|
||||
if linked && !there {
|
||||
return &UnreachableError{Link: at, Target: cur}
|
||||
}
|
||||
if to == at { // home: the link replaced by its folder, renamed or copied here
|
||||
if err := os.Remove(at); err != nil { // the link only
|
||||
return err
|
||||
}
|
||||
if rename(cur, at) == nil {
|
||||
return nil
|
||||
}
|
||||
if err := dirLink(cur, at); err != nil {
|
||||
return fmt.Errorf("can't link %s to %s again: %w", at, cur, err)
|
||||
}
|
||||
tmp := at + ".moving"
|
||||
os.RemoveAll(tmp) // a copy a magpie that died in this left; the folder itself is still there
|
||||
if err := copyTree(cur, tmp); err != nil {
|
||||
os.RemoveAll(tmp)
|
||||
return err
|
||||
}
|
||||
if err := os.Remove(at); err != nil { // the link only
|
||||
os.RemoveAll(tmp)
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, at); err != nil {
|
||||
dirLink(cur, at)
|
||||
os.RemoveAll(tmp)
|
||||
return err
|
||||
}
|
||||
return os.RemoveAll(cur)
|
||||
}
|
||||
if err := emptyOrNone(to); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(to), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if !there { // nothing yet (no cache made): an empty folder there
|
||||
if err := os.MkdirAll(to, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
if linked {
|
||||
os.Remove(at)
|
||||
} else {
|
||||
os.MkdirAll(filepath.Dir(at), 0o755)
|
||||
}
|
||||
return dirLink(to, at)
|
||||
}
|
||||
os.Remove(to) // an empty folder, which a rename can't go over on every system
|
||||
renamed := rename(cur, to) == nil
|
||||
if !renamed {
|
||||
if err := copyTree(cur, to); err != nil {
|
||||
os.RemoveAll(to)
|
||||
return err
|
||||
}
|
||||
}
|
||||
// what is at at now: a link to cur, or (not linked, copied) the folder
|
||||
// itself, put aside until the link is made
|
||||
aside := ""
|
||||
switch {
|
||||
case linked:
|
||||
if err := os.Remove(at); err != nil {
|
||||
undoMove(renamed, cur, to)
|
||||
return err
|
||||
}
|
||||
case !renamed:
|
||||
aside = at + ".moved"
|
||||
os.RemoveAll(aside)
|
||||
if err := os.Rename(at, aside); err != nil {
|
||||
os.RemoveAll(to)
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := dirLink(to, at); err != nil {
|
||||
switch {
|
||||
case linked:
|
||||
undoMove(renamed, cur, to)
|
||||
dirLink(cur, at)
|
||||
case renamed:
|
||||
os.Rename(to, at)
|
||||
default:
|
||||
os.Rename(aside, at)
|
||||
os.RemoveAll(to)
|
||||
}
|
||||
return fmt.Errorf("can't link %s to %s: %w", at, to, err)
|
||||
}
|
||||
switch {
|
||||
case aside != "":
|
||||
os.RemoveAll(aside)
|
||||
case linked && !renamed:
|
||||
os.RemoveAll(cur)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rename moves a folder within one disk; across disks it fails and the
|
||||
// folder is copied (a test has it fail to copy on one disk).
|
||||
var rename = os.Rename
|
||||
|
||||
// undoMove puts a folder renamed from cur to to back, or deletes the copy.
|
||||
func undoMove(renamed bool, cur, to string) {
|
||||
if renamed {
|
||||
os.Rename(to, cur)
|
||||
} else {
|
||||
os.RemoveAll(to)
|
||||
}
|
||||
}
|
||||
|
||||
// copyTree copies the folder from into to, which isn't there: folders,
|
||||
// files with their modes and times, links as links. Anything else (a
|
||||
// socket a process listened on) is left.
|
||||
func copyTree(from, to string) error {
|
||||
return filepath.WalkDir(from, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, err := filepath.Rel(from, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dst := filepath.Join(to, rel)
|
||||
info, err := d.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case d.IsDir():
|
||||
return os.MkdirAll(dst, info.Mode().Perm()|0o700)
|
||||
case d.Type()&fs.ModeSymlink != 0:
|
||||
t, err := os.Readlink(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Symlink(t, dst)
|
||||
case !d.Type().IsRegular():
|
||||
return nil
|
||||
}
|
||||
if err := copyFile(p, dst, info.Mode().Perm()); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chtimes(dst, info.ModTime(), info.ModTime())
|
||||
})
|
||||
}
|
||||
|
||||
func copyFile(from, to string, mode fs.FileMode) error {
|
||||
in, err := os.Open(from)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
out, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.Copy(out, in); err != nil {
|
||||
out.Close()
|
||||
return err
|
||||
}
|
||||
if err := out.Sync(); err != nil {
|
||||
out.Close()
|
||||
return err
|
||||
}
|
||||
return out.Close()
|
||||
}
|
||||
|
||||
// UnreachableError is one of magpie's folders moved to a folder that isn't
|
||||
// there now: the disk it is on isn't connected.
|
||||
type UnreachableError struct {
|
||||
Link, Target string
|
||||
}
|
||||
|
||||
func (e *UnreachableError) Error() string {
|
||||
return fmt.Sprintf("magpie's files were moved to %s, which isn't there now: connect the disk it is on, then open magpie again (%s links to it)", e.Target, e.Link)
|
||||
}
|
||||
|
||||
// Unreachable is an UnreachableError when magpie's folder, or its cache,
|
||||
// is a link to a folder that isn't there; nil otherwise. main stops on it
|
||||
// before anything is read or written: magpie started on an empty folder in
|
||||
// its place would look like a setup lost.
|
||||
func Unreachable() error {
|
||||
for _, at := range []string{Config(), Cache()} {
|
||||
t, ok := linkOf(at)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if _, err := os.Stat(t); errors.Is(err, fs.ErrNotExist) {
|
||||
return &UnreachableError{Link: at, Target: t}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// linkOf is the folder p links to, absolute, when p is a link (a symlink,
|
||||
// or a junction on Windows, which Go reports as irregular).
|
||||
func linkOf(p string) (string, bool) {
|
||||
fi, err := os.Lstat(p)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
if fi.Mode()&fs.ModeSymlink == 0 && !(runtime.GOOS == "windows" && fi.Mode()&fs.ModeIrregular != 0) {
|
||||
return "", false
|
||||
}
|
||||
t, err := os.Readlink(p)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
t = strings.TrimPrefix(t, `\??\`)
|
||||
}
|
||||
if !filepath.IsAbs(t) {
|
||||
t = filepath.Join(filepath.Dir(p), t)
|
||||
}
|
||||
return filepath.Clean(t), true
|
||||
}
|
||||
|
||||
// same says whether a and b name one folder.
|
||||
func same(a, b string) bool {
|
||||
a, b = filepath.Clean(a), filepath.Clean(b)
|
||||
if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
|
||||
return strings.EqualFold(a, b)
|
||||
}
|
||||
return a == b
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package appdir
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// moveHome is a sandbox with magpie's folders in it, each with files: the
|
||||
// config with a nested file and a link, the cache with one file.
|
||||
func moveHome(t *testing.T) (cfg, cache, disk string) {
|
||||
t.Helper()
|
||||
r := t.TempDir()
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(r, "home", ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(r, "home", ".cache"))
|
||||
cfg, cache = Config(), Cache()
|
||||
write := func(p, s string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(s), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write(filepath.Join(cfg, "providers.json"), "providers")
|
||||
write(filepath.Join(cfg, "skills", "a", "SKILL.md"), "skill")
|
||||
write(filepath.Join(cache, "calls", "1.json"), "call")
|
||||
if runtime.GOOS != "windows" {
|
||||
if err := os.Symlink("skills/a", filepath.Join(cfg, "current")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
disk = filepath.Join(r, "ssd")
|
||||
if err := os.MkdirAll(disk, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return cfg, cache, disk
|
||||
}
|
||||
|
||||
func readThrough(t *testing.T, p string) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func checkFiles(t *testing.T, cfg, cache string) {
|
||||
t.Helper()
|
||||
if got := readThrough(t, filepath.Join(cfg, "providers.json")); got != "providers" {
|
||||
t.Fatalf("providers.json = %q", got)
|
||||
}
|
||||
if got := readThrough(t, filepath.Join(cfg, "skills", "a", "SKILL.md")); got != "skill" {
|
||||
t.Fatalf("SKILL.md = %q", got)
|
||||
}
|
||||
if got := readThrough(t, filepath.Join(cache, "calls", "1.json")); got != "call" {
|
||||
t.Fatalf("cache file = %q", got)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
if got := readThrough(t, filepath.Join(cfg, "current", "SKILL.md")); got != "skill" {
|
||||
t.Fatalf("a link in the folder = %q", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The folders go to the other disk with a link left where they were, so
|
||||
// every path magpie and the agents know still reads them, and come back.
|
||||
// Across disks (rename failing) they are copied, and the old copy goes.
|
||||
func TestMoveToAnotherDiskAndBack(t *testing.T) { moveAndBack(t) }
|
||||
|
||||
func moveAndBack(t *testing.T) {
|
||||
for _, across := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "one disk", true: "across disks"}[across], func(t *testing.T) {
|
||||
if across {
|
||||
old := rename
|
||||
rename = func(string, string) error { return errors.New("cross-device link") }
|
||||
t.Cleanup(func() { rename = old })
|
||||
}
|
||||
cfg, cache, disk := moveHome(t)
|
||||
root, err := Target(disk)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := filepath.Join(disk, MoveName); root != want {
|
||||
t.Fatalf("Target = %s, want %s", root, want)
|
||||
}
|
||||
if err := Move(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := Where()
|
||||
if p.ConfigAt != filepath.Join(root, "config") || p.CacheAt != filepath.Join(root, "cache") || p.Moved != root {
|
||||
t.Fatalf("Where = %+v", p)
|
||||
}
|
||||
checkFiles(t, cfg, cache)
|
||||
checkFiles(t, filepath.Join(root, "config"), filepath.Join(root, "cache"))
|
||||
for _, left := range []string{cfg + ".moved", cache + ".moved"} {
|
||||
if _, err := os.Lstat(left); err == nil {
|
||||
t.Fatalf("%s is left", left)
|
||||
}
|
||||
}
|
||||
if err := Unreachable(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// a file written through the link lands on the disk
|
||||
os.WriteFile(filepath.Join(cfg, "new.json"), []byte("new"), 0o600)
|
||||
if got := readThrough(t, filepath.Join(root, "config", "new.json")); got != "new" {
|
||||
t.Fatalf("written through the link: %q", got)
|
||||
}
|
||||
|
||||
if _, err := Target(disk); err == nil {
|
||||
t.Fatal("moved to the folder they are in already")
|
||||
}
|
||||
home, err := Target("")
|
||||
if err != nil || home != "" {
|
||||
t.Fatalf("Target(home) = %q, %v", home, err)
|
||||
}
|
||||
if err := Move(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, d := range []string{cfg, cache} {
|
||||
if _, ok := linkOf(d); ok {
|
||||
t.Fatalf("%s is a link still", d)
|
||||
}
|
||||
if fi, err := os.Stat(d); err != nil || !fi.IsDir() {
|
||||
t.Fatalf("%s isn't a folder: %v", d, err)
|
||||
}
|
||||
}
|
||||
checkFiles(t, cfg, cache)
|
||||
if _, err := os.Stat(root); err == nil {
|
||||
t.Fatalf("%s is left on the disk", root)
|
||||
}
|
||||
if _, err := Target(""); err == nil {
|
||||
t.Fatal("moved home when home already")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A folder that has files in it already, one in magpie's own folder, or
|
||||
// a path that isn't absolute, is refused before magpie quits for it.
|
||||
func TestMoveTargetRefused(t *testing.T) {
|
||||
cfg, _, disk := moveHome(t)
|
||||
os.MkdirAll(filepath.Join(disk, MoveName), 0o755)
|
||||
os.WriteFile(filepath.Join(disk, MoveName, "theirs.txt"), []byte("x"), 0o600)
|
||||
for name, dir := range map[string]string{
|
||||
"has files": disk,
|
||||
"magpie's own": filepath.Join(cfg, "skills"),
|
||||
"magpie itself": cfg,
|
||||
"relative": "ssd",
|
||||
"not there": filepath.Join(disk, "gone"),
|
||||
} {
|
||||
if root, err := Target(dir); err == nil {
|
||||
t.Errorf("%s: Target(%s) = %s, want refused", name, dir, root)
|
||||
}
|
||||
if _, err := AskMove(dir); err == nil {
|
||||
t.Errorf("%s: AskMove(%s) asked", name, dir)
|
||||
}
|
||||
}
|
||||
if MoveAsked() {
|
||||
t.Fatal("a refused move is asked for")
|
||||
}
|
||||
if got := readThrough(t, filepath.Join(disk, MoveName, "theirs.txt")); got != "x" {
|
||||
t.Fatal("their file changed")
|
||||
}
|
||||
}
|
||||
|
||||
// A copy that fails leaves everything where it was, and nothing on the
|
||||
// other disk.
|
||||
func TestMoveCopyFailsLeavesAll(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a file can't be made unreadable by its mode on Windows")
|
||||
}
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("root reads every file")
|
||||
}
|
||||
old := rename
|
||||
rename = func(string, string) error { return errors.New("cross-device link") }
|
||||
t.Cleanup(func() { rename = old })
|
||||
cfg, cache, disk := moveHome(t)
|
||||
locked := filepath.Join(cfg, "locked.json")
|
||||
os.WriteFile(locked, []byte("x"), 0o000)
|
||||
t.Cleanup(func() { os.Chmod(locked, 0o600) })
|
||||
root, err := Target(disk)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Move(root); err == nil {
|
||||
t.Fatal("moved with a file it couldn't read")
|
||||
}
|
||||
if _, ok := linkOf(cfg); ok {
|
||||
t.Fatal("magpie's folder is a link after a failed copy")
|
||||
}
|
||||
checkFiles(t, cfg, cache)
|
||||
if _, err := os.Stat(filepath.Join(root, "config")); err == nil {
|
||||
t.Fatal("a half copy is left on the disk")
|
||||
}
|
||||
}
|
||||
|
||||
// The disk unplugged: magpie's folder leads nowhere, which is an error
|
||||
// main stops on, never an empty magpie; a move can't be made from it.
|
||||
func TestMovedDiskGoneIsUnreachable(t *testing.T) {
|
||||
cfg, _, disk := moveHome(t)
|
||||
root, err := Target(disk)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Move(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unplugged := disk + "-unplugged"
|
||||
if err := os.Rename(disk, unplugged); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ue *UnreachableError
|
||||
if err := Unreachable(); !errors.As(err, &ue) || ue.Link != cfg || !strings.HasPrefix(ue.Target, disk) {
|
||||
t.Fatalf("Unreachable = %v", err)
|
||||
}
|
||||
if err := Move(""); !errors.As(err, &ue) {
|
||||
t.Fatalf("Move home with the disk gone = %v", err)
|
||||
}
|
||||
if _, ok := linkOf(cfg); !ok {
|
||||
t.Fatal("the link was taken away with the disk gone")
|
||||
}
|
||||
os.Rename(unplugged, disk)
|
||||
if err := Unreachable(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A move asked for is made at the next start, once: one that fails is
|
||||
// not asked for again, and why is kept for Settings.
|
||||
func TestMovePendingOnce(t *testing.T) {
|
||||
cfg, cache, disk := moveHome(t)
|
||||
root, err := AskMove(disk)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p := Where(); p.Pending != root {
|
||||
t.Fatalf("Pending = %q, want %s", p.Pending, root)
|
||||
}
|
||||
// the folder filled after it was asked for
|
||||
os.MkdirAll(filepath.Join(root, "config"), 0o755)
|
||||
os.WriteFile(filepath.Join(root, "config", "x"), []byte("x"), 0o600)
|
||||
if moved, err := MovePending(); moved || err == nil {
|
||||
t.Fatalf("MovePending = %v, %v; want it refused", moved, err)
|
||||
}
|
||||
if MoveAsked() {
|
||||
t.Fatal("a failed move is asked for again")
|
||||
}
|
||||
if p := Where(); p.Error == "" || p.Pending != "" {
|
||||
t.Fatalf("Where after a failed move = %+v", p)
|
||||
}
|
||||
checkFiles(t, cfg, cache)
|
||||
os.RemoveAll(root)
|
||||
|
||||
if _, err := AskMove(disk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p := Where(); p.Error != "" {
|
||||
t.Fatalf("an old failure is kept after a new ask: %q", p.Error)
|
||||
}
|
||||
if moved, err := MovePending(); !moved || err != nil {
|
||||
t.Fatalf("MovePending = %v, %v", moved, err)
|
||||
}
|
||||
if p := Where(); p.Moved != root || p.Pending != "" || p.Error != "" {
|
||||
t.Fatalf("Where = %+v", p)
|
||||
}
|
||||
checkFiles(t, cfg, cache)
|
||||
if moved, err := MovePending(); moved || err != nil {
|
||||
t.Fatalf("MovePending with none asked = %v, %v", moved, err)
|
||||
}
|
||||
if _, err := AskMove(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p := Where(); p.Pending != "home" {
|
||||
t.Fatalf("Pending = %q, want home", p.Pending)
|
||||
}
|
||||
if err := CancelMove(); err != nil || MoveAsked() {
|
||||
t.Fatalf("CancelMove = %v, asked %v", err, MoveAsked())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package appdir
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// Without Developer Mode a user may not make symlinks (#973): magpie's
|
||||
// folders are linked by a junction, which moves and comes back the same.
|
||||
func TestMoveByJunction(t *testing.T) {
|
||||
old := symlink
|
||||
symlink = func(string, string) error {
|
||||
return &os.LinkError{Op: "symlink", Err: windows.ERROR_PRIVILEGE_NOT_HELD}
|
||||
}
|
||||
t.Cleanup(func() { symlink = old })
|
||||
moveAndBack(t)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//go:build !windows
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strconv"
|
||||
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
)
|
||||
|
||||
// alert says text in a box of the system's: an alert on a Mac, zenity's
|
||||
// where it is installed; nothing more elsewhere (stderr has it).
|
||||
func alert(title, text string) {
|
||||
switch {
|
||||
case runtime.GOOS == "darwin":
|
||||
proc.Command("/usr/bin/osascript", "-e", "display alert "+strconv.Quote(title)+" message "+strconv.Quote(text)+" as critical").Run()
|
||||
default:
|
||||
if z, err := exec.LookPath("zenity"); err == nil {
|
||||
proc.Command(z, "--error", "--title="+title, "--text="+text).Run()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package cli
|
||||
|
||||
import "golang.org/x/sys/windows"
|
||||
|
||||
// alert is Windows' own message box.
|
||||
func alert(title, text string) {
|
||||
t, _ := windows.UTF16PtrFromString(text)
|
||||
c, _ := windows.UTF16PtrFromString(title)
|
||||
windows.MessageBox(0, t, c, windows.MB_OK|windows.MB_ICONERROR|windows.MB_SETFOREGROUND|windows.MB_TOPMOST)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/codexrelay"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
)
|
||||
|
||||
// magpie data: where magpie keeps its files, and moving them to another
|
||||
// disk (CHENGJIAHEGOXIS and buhaodeshiyehao on X; appdir/move.go). A move
|
||||
// is made at once when no magpie serves the gateway, and otherwise at the
|
||||
// next start of the app, which Settings › Sync's Data folder restarts
|
||||
// it for.
|
||||
func dataCmd(args []string) error {
|
||||
if len(args) == 0 || args[0] == "where" {
|
||||
p := appdir.Where()
|
||||
fmt.Println("files:", p.Config)
|
||||
if p.ConfigAt != "" {
|
||||
fmt.Println(" →", p.ConfigAt)
|
||||
}
|
||||
fmt.Println("cache:", p.Cache)
|
||||
if p.CacheAt != "" {
|
||||
fmt.Println(" →", p.CacheAt)
|
||||
}
|
||||
if p.Portable {
|
||||
fmt.Println("portable: they move with magpie's data folder")
|
||||
}
|
||||
switch p.Pending {
|
||||
case "":
|
||||
case "home":
|
||||
fmt.Println("moving back to the default folders when magpie next starts")
|
||||
default:
|
||||
fmt.Println("moving to", p.Pending, "when magpie next starts")
|
||||
}
|
||||
if p.Error != "" {
|
||||
fmt.Println("the last move wasn't made:", p.Error)
|
||||
}
|
||||
return appdir.Unreachable()
|
||||
}
|
||||
switch args[0] {
|
||||
case "move":
|
||||
if len(args) != 2 || strings.HasPrefix(args[1], "-") && args[1] != "--home" {
|
||||
return errors.New("usage: magpie data move <folder> | --home")
|
||||
}
|
||||
dir := args[1]
|
||||
if dir == "--home" {
|
||||
dir = ""
|
||||
} else if a, err := filepath.Abs(dir); err == nil {
|
||||
dir = a
|
||||
}
|
||||
if gatewayUp() {
|
||||
root, err := appdir.AskMove(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("magpie is running: its files move to %s when it next starts (quit it and open it again)\n", homeOr(root))
|
||||
return nil
|
||||
}
|
||||
root, err := appdir.Target(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
appdir.CancelMove()
|
||||
if err := appdir.Move(root); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(green.Render("●"), "magpie's files are in", homeOr(root), "now")
|
||||
return nil
|
||||
case "cancel":
|
||||
return appdir.CancelMove()
|
||||
case "-h", "--help", "help":
|
||||
fmt.Print(dataUsage)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown data command %q\n%s", args[0], dataUsage)
|
||||
}
|
||||
|
||||
const dataUsage = `magpie data where magpie keeps its files and its cache
|
||||
magpie data move <folder> move them into <folder>/magpie (another disk), leaving a link where they were
|
||||
magpie data move --home move them back
|
||||
magpie data cancel forget a move asked for while magpie was running
|
||||
`
|
||||
|
||||
func homeOr(root string) string {
|
||||
if root == "" {
|
||||
return appdir.Where().Config
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
// gatewayUp says whether a magpie serves the gateway: one running holds
|
||||
// files in the folders a move would take away.
|
||||
var gatewayUp = func() bool {
|
||||
codexrelay.Leave() // what a quitting magpie left at the port lets go of it
|
||||
return gateway.ServedBy().Running
|
||||
}
|
||||
|
||||
// movePending makes the move Settings asked for, as the app starts again
|
||||
// for it: after the magpie it replaces has exited, and before anything is
|
||||
// read or written. With another magpie still serving the gateway (magpie
|
||||
// serve, a launch agent) the move waits for a start without one.
|
||||
func movePending() {
|
||||
if !appdir.MoveAsked() {
|
||||
return
|
||||
}
|
||||
update.AwaitPredecessor()
|
||||
if gatewayUp() {
|
||||
fmt.Fprintln(os.Stderr, "magpie: its folders move when no other magpie is running")
|
||||
return
|
||||
}
|
||||
if _, err := appdir.MovePending(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "magpie: its folders weren't moved:", err)
|
||||
}
|
||||
}
|
||||
|
||||
// unreachableStop ends magpie when its folders were moved to a disk that
|
||||
// isn't connected, saying so in a box for the app, which has no terminal.
|
||||
// magpie data still answers, to say where they are.
|
||||
func unreachableStop(args []string) {
|
||||
err := appdir.Unreachable()
|
||||
if err == nil || len(args) > 0 && args[0] == "data" {
|
||||
return
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, "magpie:", err)
|
||||
if hasGUI && (len(args) == 0 || servesPages(args) && args[0] != "serve" && args[0] != "tui" && args[0] != "web") {
|
||||
alert("magpie", err.Error())
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -76,6 +76,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
--sign-ins on backup: the subscriptions' and plugins' sign-ins too, sealed (off unless given); --no-sign-ins on restore leaves them out
|
||||
magpie uninstall [--yes] disconnect every agent, putting back what each had, then remove magpie's service and files
|
||||
--keep-data: all but deleting magpie's settings, providers and usage
|
||||
magpie data [move <folder>|move --home] where magpie keeps its files and cache, and moving them to another disk (a link is left where they were)
|
||||
magpie webdav [on <address>|set k=v…|now|off] the same, kept the same on every computer through a WebDAV folder (magpie webdav help)
|
||||
magpie s3 [on s3://<bucket>[/<prefix>]|set k=v…|now|off] the same through an S3-compatible bucket: AWS, R2, B2, MinIO… (magpie s3 help)
|
||||
magpie github [on github://<owner>/<repo>[/<folder>]|set k=v…|now|off] the same in an encrypted GitHub repository (magpie github help)
|
||||
@@ -216,6 +217,8 @@ func Main(v string) {
|
||||
fmt.Fprintln(os.Stderr, "magpie:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// moved to a disk that isn't connected: never an empty magpie in its place
|
||||
unreachableStop(os.Args[1:])
|
||||
slices.Sort(ignored)
|
||||
for _, v := range ignored {
|
||||
fmt.Fprintf(os.Stderr, "magpie: ignoring %s: not an absolute path (the programs magpie starts still get it)\n", v)
|
||||
@@ -405,6 +408,8 @@ func run(args []string) error {
|
||||
return toolCmd(args[1:])
|
||||
case codexrelay.Command: // internal: what a quitting magpie leaves for Codex's open threads
|
||||
return codexrelay.Main(args[1:], gateway.CodexRelay())
|
||||
case "data": // where magpie's files are, and moving them: before anything is made in them
|
||||
return dataCmd(args[1:])
|
||||
case "uninstall":
|
||||
// what the app starts as it quits from Settings › Uninstall
|
||||
// magpie: nothing is made again before its folders go
|
||||
@@ -422,6 +427,10 @@ func run(args []string) error {
|
||||
// a command that serves no pages starts a plugin host beside the
|
||||
// app's, whose page services it leaves to the app (#5187)
|
||||
plugin.ServePages(servesPages(args))
|
||||
// the app started again to move magpie's folders (Settings › General)
|
||||
if servesPages(args) {
|
||||
movePending()
|
||||
}
|
||||
startUp()
|
||||
// a provider added, edited or removed, or a list fetched anew, reaches
|
||||
// the model lists agents keep in files of their own, behind the save
|
||||
|
||||
@@ -192,6 +192,8 @@ var cliForRoute = map[string]string{
|
||||
"GET /api/davsync": "magpie webdav",
|
||||
"POST /api/backup/export": "magpie backup",
|
||||
"POST /api/backup/import": "magpie restore",
|
||||
"GET /api/datafolder": "magpie data",
|
||||
"POST /api/datafolder/{action}": "magpie data move",
|
||||
"POST /api/davsync/{action}": "magpie webdav",
|
||||
"GET /api/caller-keys": "magpie gateway-key list",
|
||||
"POST /api/caller-keys/{action}": "magpie gateway-key",
|
||||
|
||||
@@ -1495,6 +1495,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
sessionRoutes(mux, w)
|
||||
sessionManageRoutes(mux, w)
|
||||
backupRoutes(mux, w)
|
||||
dataFolderRoutes(mux, w)
|
||||
uninstallRoutes(mux, w)
|
||||
archiveRoutes(mux)
|
||||
libraryRoutes(mux, w)
|
||||
|
||||
@@ -25,7 +25,7 @@ window.autoBackupFill = function (at) {
|
||||
let drawn = [at];
|
||||
const draw = () => {
|
||||
if (!drawn[0].isConnected) return;
|
||||
const rows = autoBackupRows(autoBackupView);
|
||||
const rows = [...autoBackupRows(autoBackupView), ...dataFolderRows(dataFolderView)];
|
||||
drawn[0].before(...rows);
|
||||
for (const r of drawn) r.remove();
|
||||
drawn = rows;
|
||||
@@ -33,7 +33,10 @@ window.autoBackupFill = function (at) {
|
||||
if (autoBackupView) draw();
|
||||
if (Date.now() - autoBackupAt >= 30000) {
|
||||
autoBackupAt = Date.now();
|
||||
const load = api("autobackup").then((v) => { autoBackupView = v; }, (e) => { autoBackupView = { error: e.message, backups: [] }; });
|
||||
const load = Promise.all([
|
||||
api("autobackup").then((v) => { autoBackupView = v; }, (e) => { autoBackupView = { error: e.message, backups: [] }; }),
|
||||
api("datafolder").then((d) => { dataFolderView = d; }, () => {}),
|
||||
]);
|
||||
autoBackupLoad = load;
|
||||
load.then(() => { if (autoBackupLoad === load) autoBackupLoad = null; });
|
||||
}
|
||||
@@ -135,6 +138,87 @@ function autoBackupRows(v) {
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Data folder (CHENGJIAHEGOXIS on X: magpie's files on an external SSD;
|
||||
// buhaodeshiyehao on X): where magpie keeps its files and cache, moved into
|
||||
// a folder on another disk and back (appdir/move.go). magpie restarts to
|
||||
// move them, so nothing is moved under the running one.
|
||||
let dataFolderView = null;
|
||||
|
||||
function dataFolderRows(d) {
|
||||
if (!d?.config) return [];
|
||||
const r = el("div", "row pref auto-backup data-folder");
|
||||
const who = el("div", "who");
|
||||
const sub = el("div", "sub wraps data-folder-dir", d.moved || d.config);
|
||||
who.append(el("div", "name", t("Data folder")), sub);
|
||||
const val = el("div", "val");
|
||||
const btn = (label, fn) => { const b = el("button", "text", label); b.type = "button"; b.onclick = (e) => fn(b, e); return b; };
|
||||
val.append(btn(t("Show"), () => api("datafolder/reveal", {}).catch(statusErr)));
|
||||
if (d.pending) val.append(btn(t("Cancel"), (b) => dataFolderDo("cancel", b)));
|
||||
else if (!d.portable) {
|
||||
val.append(btn(t("Move…"), () => dataFolderAsk(d, false)));
|
||||
if (d.moved) val.append(btn(t("Move back"), () => dataFolderAsk(d, true)));
|
||||
}
|
||||
r.append(who, val);
|
||||
const said = [];
|
||||
if (d.pending) said.push([d.pending === "home" ? t("Moves back to this computer when magpie starts again") : t("Moves to {dir} when magpie starts again", { dir: d.pending })]);
|
||||
if (d.pending && d.other) said.push([t("Another magpie serves the gateway (magpie serve): stop it, then open magpie again to move them")]);
|
||||
if (d.error) said.push([t("The last move wasn't made: {error}", { error: d.error }), "bad"]);
|
||||
sub.after(...said.map(([s, bad]) => el("div", "sub wraps data-folder-said" + (bad ? " bad" : ""), s)));
|
||||
return [r];
|
||||
}
|
||||
|
||||
async function dataFolderDo(action, b) {
|
||||
b?.classList.add("busy");
|
||||
try {
|
||||
dataFolderView = (await api("datafolder/" + action, {})).view;
|
||||
} catch (e) {
|
||||
statusErr(e);
|
||||
}
|
||||
renderSync();
|
||||
}
|
||||
|
||||
// dataFolderAsk says what a move does before the folder is picked (or,
|
||||
// back, before it is made): magpie restarts for it.
|
||||
function dataFolderAsk(d, back) {
|
||||
const ed = el("div", "editor restore-ask data-folder-ask");
|
||||
const head = el("div", "ehead");
|
||||
head.append(el("b", "", back ? t("Move magpie's files back to this computer?") : t("Move magpie's files to another disk?")));
|
||||
ed.append(head);
|
||||
if (back) ed.append(el("p", "lib-confirm", t("They go back to {dir}, and the folder on the other disk is removed. magpie restarts to move them.", { dir: d.config })));
|
||||
else {
|
||||
ed.append(el("p", "lib-confirm", t("Its files and cache go into a folder named magpie in the folder you pick, and a link is left where they were, so agents still find them. magpie restarts to move them.")));
|
||||
ed.append(el("p", "lib-confirm", t("Keep that disk connected: without it magpie won't open until it is back.")));
|
||||
}
|
||||
const err = el("p", "editor-error", "");
|
||||
ed.append(err);
|
||||
const bar = el("div", "bar");
|
||||
const go = el("button", "text primary", back ? t("Move back") : t("Choose a folder…"));
|
||||
go.onclick = async (e) => {
|
||||
e.stopPropagation();
|
||||
go.disabled = true;
|
||||
go.classList.add("busy");
|
||||
try {
|
||||
const r = await api(back ? "datafolder/home" : "datafolder/move", {});
|
||||
dataFolderView = r.view;
|
||||
if (r.restart) { go.textContent = t("Restarting…"); return; }
|
||||
closeConfirmAsk();
|
||||
renderSync();
|
||||
} catch (x) {
|
||||
go.disabled = false;
|
||||
go.classList.remove("busy");
|
||||
err.textContent = x.message;
|
||||
}
|
||||
};
|
||||
const cancel = el("button", "text", t("Cancel"));
|
||||
cancel.onclick = cancelAsk;
|
||||
bar.append(el("span", "grow"), cancel, go);
|
||||
ed.append(bar);
|
||||
confirmAsk = ed;
|
||||
openModal(ed);
|
||||
$("#modal").classList.add("lib");
|
||||
cancel.focus(NO_SCROLL);
|
||||
}
|
||||
|
||||
// autoBackupWhen names a version by when it was made, as its row does
|
||||
const autoBackupWhen = (made) => new Date(made).toLocaleString(intlLang(), { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
|
||||
@@ -3044,6 +3044,19 @@ const I18N = {
|
||||
"6 hours": "6 小时",
|
||||
"Back up now": "立即备份",
|
||||
"Backup folder": "备份文件夹",
|
||||
"Data folder": "数据文件夹",
|
||||
"Move…": "移动…",
|
||||
"Move back": "移回",
|
||||
"Moves back to this computer when magpie starts again": "magpie 重新打开时移回本机",
|
||||
"Moves to {dir} when magpie starts again": "magpie 重新打开时移到 {dir}",
|
||||
"Another magpie serves the gateway (magpie serve): stop it, then open magpie again to move them": "另一个 magpie 正在提供网关(magpie serve):先停掉它,再重新打开 magpie 才会移动",
|
||||
"The last move wasn't made: {error}": "上次没有移动成功:{error}",
|
||||
"Move magpie's files back to this computer?": "把 magpie 的文件移回本机?",
|
||||
"Move magpie's files to another disk?": "把 magpie 的文件移到另一个磁盘?",
|
||||
"They go back to {dir}, and the folder on the other disk is removed. magpie restarts to move them.": "文件会移回 {dir},另一个磁盘上的文件夹会被删除。magpie 会重启来完成移动。",
|
||||
"Its files and cache go into a folder named magpie in the folder you pick, and a link is left where they were, so agents still find them. magpie restarts to move them.": "文件和缓存会移到你所选文件夹里的 magpie 文件夹,原位置留下一个链接,agent 仍然能找到它们。magpie 会重启来完成移动。",
|
||||
"Keep that disk connected: without it magpie won't open until it is back.": "请保持该磁盘连接:断开时 magpie 打不开,重新连上即可。",
|
||||
"Choose a folder…": "选择文件夹…",
|
||||
"In magpie's own folder: a reinstalled system or a lost disk takes these backups too. Pick a folder on another disk, or one a cloud drive syncs": "在 magpie 自己的文件夹里:重装系统或硬盘损坏时,这些备份会一起丢失。请选择另一块磁盘上的文件夹,或网盘同步的文件夹",
|
||||
"Change…": "更改…",
|
||||
"Couldn't back up: {error}": "无法备份:{error}",
|
||||
@@ -7880,6 +7893,19 @@ const I18N = {
|
||||
"6 hours": "6 小時",
|
||||
"Back up now": "立即備份",
|
||||
"Backup folder": "備份資料夾",
|
||||
"Data folder": "資料資料夾",
|
||||
"Move…": "移動…",
|
||||
"Move back": "移回",
|
||||
"Moves back to this computer when magpie starts again": "magpie 重新開啟時移回本機",
|
||||
"Moves to {dir} when magpie starts again": "magpie 重新開啟時移到 {dir}",
|
||||
"Another magpie serves the gateway (magpie serve): stop it, then open magpie again to move them": "另一個 magpie 正在提供閘道(magpie serve):先停止它,再重新開啟 magpie 才會移動",
|
||||
"The last move wasn't made: {error}": "上次沒有移動成功:{error}",
|
||||
"Move magpie's files back to this computer?": "把 magpie 的檔案移回本機?",
|
||||
"Move magpie's files to another disk?": "把 magpie 的檔案移到另一個磁碟?",
|
||||
"They go back to {dir}, and the folder on the other disk is removed. magpie restarts to move them.": "檔案會移回 {dir},另一個磁碟上的資料夾會被刪除。magpie 會重新啟動來完成移動。",
|
||||
"Its files and cache go into a folder named magpie in the folder you pick, and a link is left where they were, so agents still find them. magpie restarts to move them.": "檔案和快取會移到你所選資料夾裡的 magpie 資料夾,原位置留下一個連結,agent 仍然能找到它們。magpie 會重新啟動來完成移動。",
|
||||
"Keep that disk connected: without it magpie won't open until it is back.": "請保持該磁碟連線:中斷時 magpie 打不開,重新連上即可。",
|
||||
"Choose a folder…": "選擇資料夾…",
|
||||
"In magpie's own folder: a reinstalled system or a lost disk takes these backups too. Pick a folder on another disk, or one a cloud drive syncs": "在 magpie 自己的資料夾裡:重灌系統或硬碟損壞時,這些備份會一起遺失。請選擇另一顆磁碟上的資料夾,或雲端硬碟同步的資料夾",
|
||||
"Change…": "更改…",
|
||||
"Couldn't back up: {error}": "無法備份:{error}",
|
||||
@@ -12726,6 +12752,19 @@ const I18N = {
|
||||
"6 hours": "6 時間",
|
||||
"Back up now": "今すぐバックアップ",
|
||||
"Backup folder": "バックアップフォルダ",
|
||||
"Data folder": "データフォルダ",
|
||||
"Move…": "移動…",
|
||||
"Move back": "元に戻す",
|
||||
"Moves back to this computer when magpie starts again": "magpie を次に開いたときにこのコンピュータへ戻します",
|
||||
"Moves to {dir} when magpie starts again": "magpie を次に開いたときに {dir} へ移動します",
|
||||
"Another magpie serves the gateway (magpie serve): stop it, then open magpie again to move them": "別の magpie がゲートウェイを提供しています(magpie serve)。それを止めてから magpie を開き直すと移動します",
|
||||
"The last move wasn't made: {error}": "前回の移動はできませんでした:{error}",
|
||||
"Move magpie's files back to this computer?": "magpie のファイルをこのコンピュータに戻しますか?",
|
||||
"Move magpie's files to another disk?": "magpie のファイルを別のディスクに移動しますか?",
|
||||
"They go back to {dir}, and the folder on the other disk is removed. magpie restarts to move them.": "{dir} に戻し、別のディスク上のフォルダは削除します。移動のため magpie が再起動します。",
|
||||
"Its files and cache go into a folder named magpie in the folder you pick, and a link is left where they were, so agents still find them. magpie restarts to move them.": "ファイルとキャッシュは選んだフォルダ内の magpie フォルダに移り、元の場所にはリンクが残るので、エージェントからも見つかります。移動のため magpie が再起動します。",
|
||||
"Keep that disk connected: without it magpie won't open until it is back.": "そのディスクは接続したままにしてください。外れている間は magpie を開けません。",
|
||||
"Choose a folder…": "フォルダを選択…",
|
||||
"In magpie's own folder: a reinstalled system or a lost disk takes these backups too. Pick a folder on another disk, or one a cloud drive syncs": "magpie 自身のフォルダ内です:システムの再インストールやディスクの故障で、これらのバックアップも一緒に失われます。別のディスク上のフォルダか、クラウドドライブが同期するフォルダを選んでください",
|
||||
"Change…": "変更…",
|
||||
"Couldn't back up: {error}": "バックアップできませんでした:{error}",
|
||||
@@ -17583,6 +17622,19 @@ const I18N = {
|
||||
"6 hours": "6 Stunden",
|
||||
"Back up now": "Jetzt sichern",
|
||||
"Backup folder": "Sicherungsordner",
|
||||
"Data folder": "Datenordner",
|
||||
"Move…": "Verschieben…",
|
||||
"Move back": "Zurückverschieben",
|
||||
"Moves back to this computer when magpie starts again": "Wird beim nächsten Start von magpie zurück auf diesen Computer verschoben",
|
||||
"Moves to {dir} when magpie starts again": "Wird beim nächsten Start von magpie nach {dir} verschoben",
|
||||
"Another magpie serves the gateway (magpie serve): stop it, then open magpie again to move them": "Ein anderes magpie stellt das Gateway bereit (magpie serve): Beende es und öffne magpie erneut, um sie zu verschieben",
|
||||
"The last move wasn't made: {error}": "Das letzte Verschieben ist fehlgeschlagen: {error}",
|
||||
"Move magpie's files back to this computer?": "magpies Dateien zurück auf diesen Computer verschieben?",
|
||||
"Move magpie's files to another disk?": "magpies Dateien auf ein anderes Laufwerk verschieben?",
|
||||
"They go back to {dir}, and the folder on the other disk is removed. magpie restarts to move them.": "Sie kommen zurück nach {dir}, und der Ordner auf dem anderen Laufwerk wird entfernt. magpie startet neu, um sie zu verschieben.",
|
||||
"Its files and cache go into a folder named magpie in the folder you pick, and a link is left where they were, so agents still find them. magpie restarts to move them.": "Dateien und Cache kommen in einen Ordner namens magpie im gewählten Ordner, und an ihrem alten Ort bleibt ein Link, damit Agents sie weiter finden. magpie startet neu, um sie zu verschieben.",
|
||||
"Keep that disk connected: without it magpie won't open until it is back.": "Lass das Laufwerk verbunden: Ohne es öffnet magpie erst wieder, wenn es zurück ist.",
|
||||
"Choose a folder…": "Ordner wählen…",
|
||||
"In magpie's own folder: a reinstalled system or a lost disk takes these backups too. Pick a folder on another disk, or one a cloud drive syncs": "Im eigenen Ordner von magpie: Eine Neuinstallation des Systems oder eine verlorene Festplatte nimmt diese Sicherungen mit. Wähle einen Ordner auf einer anderen Festplatte oder einen, den ein Cloud-Laufwerk synchronisiert",
|
||||
"Change…": "Ändern…",
|
||||
"Couldn't back up: {error}": "Sichern fehlgeschlagen: {error}",
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
)
|
||||
|
||||
// Settings › Sync's Data folder (CHENGJIAHEGOXIS on X: magpie's files on
|
||||
// an external SSD rather than the Mac's own disk; buhaodeshiyehao on X):
|
||||
// where magpie keeps its files and cache, and moving them to a folder on
|
||||
// another disk, or back. The move is appdir's (move.go). It is never made
|
||||
// under this magpie: it is asked for, magpie starts itself again, and the
|
||||
// new one makes it before it reads anything.
|
||||
|
||||
type dataFolderView struct {
|
||||
appdir.Place
|
||||
// Other is a magpie other than this one serving the gateway (magpie
|
||||
// serve, a launch agent): the move waits for a start without it.
|
||||
Other bool `json:"other,omitempty"`
|
||||
}
|
||||
|
||||
func dataFolder() dataFolderView {
|
||||
p := appdir.Where()
|
||||
for _, s := range []*string{&p.Config, &p.Cache, &p.ConfigAt, &p.CacheAt, &p.Moved} {
|
||||
if *s != "" {
|
||||
*s = tilde(*s)
|
||||
}
|
||||
}
|
||||
if p.Pending != "" && p.Pending != "home" {
|
||||
p.Pending = tilde(p.Pending)
|
||||
}
|
||||
v := dataFolderView{Place: p}
|
||||
if s := servedBy(); s.Running && s.Pid != os.Getpid() {
|
||||
v.Other = true
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// servedBy is gateway.ServedBy; tests stand in for it.
|
||||
var servedBy = gateway.ServedBy
|
||||
|
||||
// restartSelf starts this magpie again once it has exited, with its window
|
||||
// up: the new one makes the move asked for, then opens as before. Tests
|
||||
// stand in for it.
|
||||
var restartSelf = func() error {
|
||||
if b := bundleOf(); b != "" {
|
||||
return update.Relaunch(b, true, false)
|
||||
}
|
||||
exe, err := executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return relaunchBinary(exe, "", true, "")
|
||||
}
|
||||
|
||||
func dataFolderRoutes(mux *http.ServeMux, w Windows) {
|
||||
mux.HandleFunc("GET /api/datafolder", func(rw http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(rw, dataFolder())
|
||||
})
|
||||
mux.HandleFunc("POST /api/datafolder/{action}", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Dir string } // move: the folder picked; "" asks with the system's picker
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil && !errors.Is(err, io.EOF) {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
app := w
|
||||
if a, ok := w.(appWebHost); ok { // a browser on the app's page: the app restarts
|
||||
app = a.app
|
||||
}
|
||||
var err error
|
||||
switch r.PathValue("action") {
|
||||
case "move", "home":
|
||||
dir := ""
|
||||
if r.PathValue("action") == "move" {
|
||||
if dir = in.Dir; dir == "" {
|
||||
if dir, err = w.ChooseFolder("Choose a folder for magpie's files"); err != nil || dir == "" {
|
||||
break // cancelled: nothing asked
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err = appdir.AskMove(dir); err != nil {
|
||||
break
|
||||
}
|
||||
v := dataFolder()
|
||||
// magpie web, or another magpie serving: the user starts it
|
||||
// again; the app starts itself again now
|
||||
restart := !ownWeb(app) && !v.Other
|
||||
if restart {
|
||||
if err = restartSelf(); err != nil {
|
||||
appdir.CancelMove()
|
||||
break
|
||||
}
|
||||
}
|
||||
writeJSON(rw, map[string]any{"view": v, "restart": restart})
|
||||
if restart {
|
||||
go leave(app.Quit)
|
||||
}
|
||||
return
|
||||
case "cancel":
|
||||
err = appdir.CancelMove()
|
||||
case "reveal":
|
||||
p := appdir.Where()
|
||||
dir := p.Config
|
||||
if p.ConfigAt != "" {
|
||||
dir = p.ConfigAt
|
||||
}
|
||||
err = w.OpenFolder(dir)
|
||||
default:
|
||||
http.NotFound(rw, r)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, map[string]any{"view": dataFolder()})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
)
|
||||
|
||||
// pickAndQuit is the app's windows with the picker answering dir, and Quit
|
||||
// said on quit.
|
||||
type pickAndQuit struct {
|
||||
pickFolder
|
||||
quit chan struct{}
|
||||
}
|
||||
|
||||
func (p pickAndQuit) Quit() { p.quit <- struct{}{} }
|
||||
|
||||
// Settings' Data folder (CHENGJIAHEGOXIS and buhaodeshiyehao on X): Move…
|
||||
// takes a folder from the picker, asks for the move and starts magpie again
|
||||
// to make it, as the app quits; nothing is moved under the running one.
|
||||
// With another magpie serving the gateway, it is asked for and nothing
|
||||
// restarts. Cancel forgets it.
|
||||
func TestDataFolderMoveRestarts(t *testing.T) {
|
||||
h := sandboxHome(t)
|
||||
os.MkdirAll(appdir.Config(), 0o700)
|
||||
os.WriteFile(filepath.Join(appdir.Config(), "settings.json"), []byte("{}"), 0o600)
|
||||
disk := filepath.Join(h, "ssd")
|
||||
os.MkdirAll(disk, 0o755)
|
||||
restarts := 0
|
||||
oldRestart, oldServes := restartSelf, servedBy
|
||||
t.Cleanup(func() { restartSelf, servedBy = oldRestart, oldServes })
|
||||
restartSelf = func() error { restarts++; return nil }
|
||||
other := false
|
||||
servedBy = func() gateway.Served {
|
||||
if other {
|
||||
return gateway.Served{Running: true, Pid: os.Getpid() + 1}
|
||||
}
|
||||
return gateway.Served{Running: true, Pid: os.Getpid()} // this magpie's own
|
||||
}
|
||||
win := pickAndQuit{pickFolder{dir: disk}, make(chan struct{}, 1)}
|
||||
mux := http.NewServeMux()
|
||||
dataFolderRoutes(mux, win)
|
||||
call := func(path, body string, code int) map[string]any {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
method := "POST"
|
||||
if body == "-" {
|
||||
method, body = "GET", ""
|
||||
}
|
||||
mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
|
||||
if w.Code != code {
|
||||
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
|
||||
}
|
||||
var out map[string]any
|
||||
json.Unmarshal(w.Body.Bytes(), &out)
|
||||
return out
|
||||
}
|
||||
if v := call("/api/datafolder", "-", 200); v["config"] != tilde(appdir.Config()) || v["moved"] != nil || v["pending"] != nil {
|
||||
t.Fatalf("at home: %v", v)
|
||||
}
|
||||
out := call("/api/datafolder/move", "", 200)
|
||||
view, _ := out["view"].(map[string]any)
|
||||
if out["restart"] != true || view["pending"] != tilde(filepath.Join(disk, appdir.MoveName)) || restarts != 1 {
|
||||
t.Fatalf("move: %v, %d restarts", out, restarts)
|
||||
}
|
||||
select {
|
||||
case <-win.quit:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the app didn't quit for the restart")
|
||||
}
|
||||
if _, ok := os.Readlink(appdir.Config()); ok == nil {
|
||||
t.Fatal("moved under the running magpie")
|
||||
}
|
||||
if !appdir.MoveAsked() {
|
||||
t.Fatal("no move asked for")
|
||||
}
|
||||
call("/api/datafolder/cancel", "", 200)
|
||||
if appdir.MoveAsked() {
|
||||
t.Fatal("cancel left the move asked for")
|
||||
}
|
||||
|
||||
// another magpie serves: asked for, no restart, said
|
||||
other = true
|
||||
out = call("/api/datafolder/move", `{"dir":`+jsonString(disk)+`}`, 200)
|
||||
view, _ = out["view"].(map[string]any)
|
||||
if out["restart"] != false || view["other"] != true || restarts != 1 {
|
||||
t.Fatalf("with another magpie serving: %v, %d restarts", out, restarts)
|
||||
}
|
||||
call("/api/datafolder/cancel", "", 200)
|
||||
|
||||
// a folder with files in it is refused, before anything quits
|
||||
other = false
|
||||
os.MkdirAll(filepath.Join(disk, appdir.MoveName), 0o755)
|
||||
os.WriteFile(filepath.Join(disk, appdir.MoveName, "x"), []byte("x"), 0o600)
|
||||
call("/api/datafolder/move", "", 400)
|
||||
if appdir.MoveAsked() || restarts != 1 {
|
||||
t.Fatal("a refused folder asked for a move or restarted")
|
||||
}
|
||||
// a restart that can't start leaves nothing asked for
|
||||
os.RemoveAll(filepath.Join(disk, appdir.MoveName))
|
||||
restartSelf = func() error { return errors.New("can't start") }
|
||||
call("/api/datafolder/move", "", 400)
|
||||
if appdir.MoveAsked() {
|
||||
t.Fatal("a move is asked for with no restart to make it")
|
||||
}
|
||||
// home when home: refused
|
||||
call("/api/datafolder/home", "", 400)
|
||||
}
|
||||
|
||||
func jsonString(s string) string { b, _ := json.Marshal(s); return string(b) }
|
||||
@@ -0,0 +1,169 @@
|
||||
// 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, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,12 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"unicode/utf16"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
)
|
||||
|
||||
// dirLink makes link a link to the folder target. Windows lets a user make
|
||||
@@ -28,54 +27,5 @@ func dirLink(target, link string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// junction makes link a junction to the folder target: an empty folder
|
||||
// given a mount-point reparse point. Nothing is left at link when it fails.
|
||||
func junction(target, link string) error {
|
||||
abs, err := filepath.Abs(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if v := filepath.VolumeName(abs); len(v) != 2 || v[1] != ':' {
|
||||
return errors.New("a junction needs a local drive path: " + abs)
|
||||
}
|
||||
if err := os.Mkdir(link, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := setMountPoint(link, abs); err != nil {
|
||||
os.Remove(link)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func setMountPoint(dir, target string) error {
|
||||
p, err := windows.UTF16PtrFromString(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h, err := windows.CreateFile(p, windows.GENERIC_WRITE, 0, nil, windows.OPEN_EXISTING,
|
||||
windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer windows.CloseHandle(h)
|
||||
sub := utf16.Encode([]rune(`\??\` + target))
|
||||
shown := utf16.Encode([]rune(target))
|
||||
// REPARSE_DATA_BUFFER, MountPointReparseBuffer: both names end in a NUL
|
||||
path := make([]uint16, 0, len(sub)+len(shown)+2)
|
||||
path = append(append(append(append(path, sub...), 0), shown...), 0)
|
||||
data := make([]byte, 8+2*len(path))
|
||||
binary.LittleEndian.PutUint16(data[0:], 0)
|
||||
binary.LittleEndian.PutUint16(data[2:], uint16(2*len(sub)))
|
||||
binary.LittleEndian.PutUint16(data[4:], uint16(2*(len(sub)+1)))
|
||||
binary.LittleEndian.PutUint16(data[6:], uint16(2*len(shown)))
|
||||
for i, c := range path {
|
||||
binary.LittleEndian.PutUint16(data[8+2*i:], c)
|
||||
}
|
||||
buf := make([]byte, 8+len(data))
|
||||
binary.LittleEndian.PutUint32(buf[0:], windows.IO_REPARSE_TAG_MOUNT_POINT)
|
||||
binary.LittleEndian.PutUint16(buf[4:], uint16(len(data)))
|
||||
copy(buf[8:], data)
|
||||
var n uint32
|
||||
return windows.DeviceIoControl(h, windows.FSCTL_SET_REPARSE_POINT, &buf[0], uint32(len(buf)), nil, 0, &n, nil)
|
||||
}
|
||||
// junction is appdir.Junction: a junction to the folder target.
|
||||
func junction(target, link string) error { return appdir.Junction(target, link) }
|
||||
|
||||
@@ -312,6 +312,7 @@ magpie claude group/opus-anywhere <span class="c"># これを使う</span></p
|
||||
|
||||
<h3 id="data-folder"><a class="anchor" href="#data-folder">magpie のファイルを別のディスクに置いて、システムを再インストールしても失わないようにできますか?</a></h3>
|
||||
<p>インストール版の magpie は、設定・プロバイダ・使用量・ライブラリを <code>~/.config/magpie</code>(Windows では <code>C:\Users\<ユーザー>\.config\magpie</code>)に保存します。1 日 1 回自動でバックアップしますが、その保存先は同じフォルダ内の <code>auto-backups</code> なので、システムを再インストールするとバックアップも一緒に失われます。<span class="ui">設定</span> → <span class="ui">同期とバックアップ</span> の <span class="ui">バックアップフォルダ</span> の下にもそう表示されます。そこで <span class="ui">変更…</span> を押し、別のディスク上のフォルダ(<code>D:\magpie-backups</code> など)か、クラウドドライブが同期するフォルダを選んでください。再インストール後は magpie を入れ、同じ場所で同じフォルダを選び、最新の版を <span class="ui">復元…</span> します。バックアップに API キーは含まれません。<span class="ui">バックアップにサインインを含める</span> を有効にすると、サブスクリプションのアカウントとプラグインのサインインもパスフレーズで暗号化して含めます。キーも持ち出すには、同じ場所で WebDAV フォルダ、S3 バケット、GitHub リポジトリへの同期をパスフレーズ付きで設定してください。</p>
|
||||
<p>magpie 自身のファイルをそのディスク(外付け SSD など)に置くなら、同じ場所の <span class="ui">データフォルダ</span> の <span class="ui">移動…</span> を押し、そのディスク上のフォルダを選びます。magpie は再起動し、ファイルとキャッシュをその中の <code>magpie</code> フォルダに移し、元の場所にリンクを残すので、ほかは何も変わりません。ディスクはつないだままにしてください。外すと、戻すまで magpie は開きません。<span class="ui">元に戻す</span> で元の場所に戻ります。ターミナルでは <code>magpie data move <フォルダ></code> で同じことができます。</p>
|
||||
<p>すべてをそのディスクに置くなら、ポータブルで使います。<code>magpie.exe</code> をそのディスク上のフォルダに置き、隣に <code>data</code> という空のフォルダを作ります(<code>D:\magpie\magpie.exe</code> と <code>D:\magpie\data</code>)。magpie はキャッシュやログも含めてすべてを <code>data</code> に保存し、ユーザーフォルダには自分のファイルを書きません。<span class="ui">設定</span> → <span class="ui">情報</span> → <span class="ui">設定フォルダ</span> にポータブルと表示されます。それを開き、上の手順でバックアップを復元します。再インストール後は <code>D:\magpie\magpie.exe</code> をもう一度開くだけです。各エージェント自身の設定(<code>~/.claude</code>、<code>~/.codex</code>…)は、それぞれが読む場所に残ります。</p>
|
||||
|
||||
<h3 id="log">magpie のログはどこにありますか?</h3>
|
||||
|
||||
@@ -312,6 +312,7 @@ magpie claude group/opus-anywhere <span class="c"># use it</span></pre>
|
||||
|
||||
<h3 id="data-folder"><a class="anchor" href="#data-folder">Can magpie keep its files on another disk, so reinstalling the system doesn’t lose them?</a></h3>
|
||||
<p>Installed, magpie keeps its settings, providers, usage and library in <code>~/.config/magpie</code> (<code>C:\Users\<you>\.config\magpie</code> on Windows). It backs them up by itself once a day, into <code>auto-backups</code> in that same folder, so a reinstalled system loses the backups too; <span class="ui">Settings</span> → <span class="ui">Sync and backup</span> says so under <span class="ui">Backup folder</span>. Click <span class="ui">Change…</span> there and pick a folder on another disk (<code>D:\magpie-backups</code>) or one a cloud drive syncs. After a reinstall, install magpie, pick the same folder there and <span class="ui">Restore…</span> the newest version. Backups hold no API keys; <span class="ui">Sign-ins in backups</span> adds subscription accounts and plugin sign-ins, sealed with a passphrase. To carry the keys too, sync to a WebDAV folder, an S3 bucket or a GitHub repository, sealed with a passphrase, in the same place.</p>
|
||||
<p>To keep magpie’s own files on that disk (an external SSD, say), click <span class="ui">Move…</span> beside <span class="ui">Data folder</span> in the same place and pick a folder there. magpie restarts, moves its files and cache into a folder named <code>magpie</code> inside it, and leaves a link where they were, so nothing else changes. Keep the disk connected: without it magpie won’t open until it is back. <span class="ui">Move back</span> brings them home. <code>magpie data move <folder></code> does the same from a terminal.</p>
|
||||
<p>To keep everything on that disk, run magpie portable: put <code>magpie.exe</code> in a folder there with an empty folder named <code>data</code> beside it (<code>D:\magpie\magpie.exe</code> and <code>D:\magpie\data</code>). magpie then keeps everything in <code>data</code>, its caches and log too, and writes nothing of its own to your user folder; <span class="ui">Settings</span> → <span class="ui">About</span> → <span class="ui">Config folder</span> says Portable. Open it, and restore a backup into it as above. After a reinstall, open <code>D:\magpie\magpie.exe</code> again. The agents’ own configs (<code>~/.claude</code>, <code>~/.codex</code>…) stay where each agent reads them.</p>
|
||||
|
||||
<h3 id="log">Where is magpie’s log?</h3>
|
||||
|
||||
@@ -312,6 +312,7 @@ magpie claude group/opus-anywhere <span class="c"># 使用它</span></pre>
|
||||
|
||||
<h3 id="data-folder"><a class="anchor" href="#data-folder">magpie 的文件能放到另一块磁盘上,重装系统也不丢吗?</a></h3>
|
||||
<p>安装版的 magpie 把设置、provider、用量和库放在 <code>~/.config/magpie</code>(Windows 上是 <code>C:\Users\<你>\.config\magpie</code>)。它每天自动备份一次,备份放在同一个文件夹的 <code>auto-backups</code> 里,所以重装系统时备份也会一起丢;<span class="ui">设置</span> → <span class="ui">同步与备份</span> 的 <span class="ui">备份文件夹</span> 下面会提示这一点。在那里点 <span class="ui">更改…</span>,选另一块磁盘上的文件夹(如 <code>D:\magpie-backups</code>)或网盘同步的文件夹。重装后装好 magpie,在同一处选回这个文件夹,再对最新的版本点 <span class="ui">恢复…</span>。备份里没有 API Key;打开 <span class="ui">备份登录信息</span> 会把订阅账号和插件登录也放进去,用口令加密。要连 Key 一起带走,在同一处设置同步到 WebDAV 文件夹、S3 存储桶或 GitHub 仓库,用口令加密。</p>
|
||||
<p>想把 magpie 自己的文件放到那块磁盘(比如移动固态硬盘)上,就在同一处 <span class="ui">数据文件夹</span> 旁点 <span class="ui">移动…</span>,选那块盘上的一个文件夹。magpie 会重启,把文件和缓存移到其中名为 <code>magpie</code> 的文件夹里,并在原处留一个链接,其他都不用改。请保持那块盘连着:拔掉后 magpie 打不开,插回即可。点 <span class="ui">移回</span> 可移回本机。在终端里用 <code>magpie data move <文件夹></code> 也一样。</p>
|
||||
<p>想把所有东西都放在那块磁盘上,就用便携模式:把 <code>magpie.exe</code> 放进那里的一个文件夹,旁边建一个名为 <code>data</code> 的空文件夹(<code>D:\magpie\magpie.exe</code> 和 <code>D:\magpie\data</code>)。这样 magpie 的一切,包括缓存和日志,都放在 <code>data</code> 里,不在你的用户文件夹里写任何自己的文件;<span class="ui">设置</span> → <span class="ui">关于</span> → <span class="ui">配置目录</span> 会显示便携模式。打开它,按上面的方法恢复一个备份。重装系统后,再打开 <code>D:\magpie\magpie.exe</code> 即可。各 Agent 自己的配置(<code>~/.claude</code>、<code>~/.codex</code>…)仍留在各自读取的位置。</p>
|
||||
|
||||
<h3 id="log">magpie 的日志在哪里?</h3>
|
||||
|
||||
Reference in New Issue
Block a user