From 223b900b48ea99e9e523df3883a8dfe9384be34e Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 18 Nov 2026 01:19:01 +0800 Subject: [PATCH] library: a skill from GitHub or git syncs as its source, and what a sync leaves out is said (#5715) JJasonsun (Discord #help, #5715): a skill over a sync's 64 MiB budget was left out of the server's file while Settings > Sync said the sync worked, so the other computer silently didn't have it. A library skill from GitHub or another git repository whose folder is still what was fetched (editState known and unedited, or Pending) now goes as its source, as a plugin does (plugin_carry.go): CarriedSkill gets Fetch, Hash and Commit, and the receiving computer fetches it itself after Put lets go of the library lock (fetchSkills, through updateSkills). Its files still go as far as the room the skills carried as files leave, so a magpie from before this, which ignores Fetch, writes the skill as it did. On the receiving side (fromSourceHere): same version is kept; one changed here is kept and, when the other computer has another version, said as a problem ("Update replaces them"); another version or a skill new here is fetched, unless the carried files are already the whole of it. A skill that can't be fetched stays Pending, shows "Not fetched yet" on its Library row, and is said as a problem until Update fetches it (library.Unsettled drops a settled one). A skill changed here, one from a folder, and one from a link holding a token (whose link must not be synced) go as their files, as before. What a sync still leaves out is said: state.LibraryLeft names skills and plugins whose files were too big (or that this computer never got, Skill.Missing, carried on as Left so a third computer isn't told it has them), state.LibraryProblems what the last sync bringing the library in couldn't put here. Status gives them as libraryLeft and libraryProblems, and Settings > Sync shows them in red under the status (askPreviewRows). Strings in every language. Run at this head (rebased on origin/main 7b552eef3): - gofmt -l: clean. go vet darwin, GOOS=linux, GOOS=windows: ok. - mica: go test -count=1 -timeout 45m ./internal/library ./internal/davsync ./internal/backup ./internal/gui: ok. - mote: node --test in Chromium and WebKit of sync-*, i18n-*, gui-zh-tw, gui-ja, gui-de, skill-*, library-items, library-all, library-plugins and the new sync-library-left (16/16 in both engines). Red, and red the same in a fresh origin/main 7b552eef3 worktree, each filed: skill-fold-all (#6667), skill-manual (#6668), skill-group-shared (#6687), skill-where's zh 900px under concurrency (#5859). - The first package run at this head had TestSkillCarriedBySource and ...NotFetched red: InstallSkills took another test's cached probe of owner/repo (SKILL.md only). carrySource now forgets the probes before and after; ./internal/library ok again, once more with -shuffle=on. Broken by hand, each red: bySource always false (5 library tests), fetchSkills removed (library + davsync), changedHere removed, Missing not carried on, Unsettled removed, Pending not set in Put, signedIn check removed from Collect and from Put (TestSkillSignedInLinkGoesAsFiles), leftOut returning nil, Fetch not excluded from leftOut. Not tried: a real sync between two computers with a real >64 MiB skill from GitHub; the tests use a local git repository as the source. A restore (backup.Restore through the restore and plan paths) carries skills by source too but doesn't record LibraryLeft/LibraryProblems yet (said in sync-backup.md). --- docs/subsystems/library.md | 2 +- docs/subsystems/sync-backup.md | 15 + internal/davsync/davsync.go | 81 ++++- internal/davsync/skill_source_test.go | 132 ++++++++ internal/gui/assets/i18n.js | 4 + internal/gui/assets/plugins/library/client.js | 2 + internal/gui/assets/plugins/library/i18n.js | 4 + internal/gui/assets/syncfiles.js | 8 + internal/gui/tests/sync-library-left.test.cjs | 136 ++++++++ internal/library/carry.go | 84 ++++- internal/library/skill_carry.go | 178 ++++++++++ internal/library/skill_carry_test.go | 304 ++++++++++++++++++ internal/library/skill_changed.go | 4 +- internal/library/skills.go | 20 +- internal/library/sync.go | 5 +- 15 files changed, 965 insertions(+), 14 deletions(-) create mode 100644 internal/davsync/skill_source_test.go create mode 100644 internal/gui/tests/sync-library-left.test.cjs create mode 100644 internal/library/skill_carry.go create mode 100644 internal/library/skill_carry_test.go diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 55f07b0b8..b4f365fc8 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -87,7 +87,7 @@ Pi's extensions and packages. - Magpie Sessions (`magpie-sessions`, `sessionsServer` in [`market.go`](../../internal/library/market.go)) is the opt-in server that searches and reads what was said in every agent's sessions on this computer (cryingLiu on X): `magpie mcp sessions` (`RunSessions`) passes each stdio message to the gateway's `/mcp/magpie/sessions`, which answers this computer's agents alone, as Magpie Memory's does (`hereOnly`). No agent is ticked until picked (`library-sessions-mcp.test.cjs`, `TestSessionsServerInDiscover`). See [gateway-sessions.md](gateway-sessions.md#what-was-said-in-every-agents-sessions). - Magpie Image Recognition (`magpie-vision`, `visionServer` in [`market.go`](../../internal/library/market.go)) is the featured, opt-in server for image recognition, beside Magpie Image and Magpie Web Search (matrix0487 on Discord: Discover had two of magpie's three): `magpie mcp vision` (`RunVision` in [`browsermcp.go`](../../internal/browsermcp/browsermcp.go)) passes each stdio message to the gateway's `/mcp/magpie/vision`, and makes `analyze_image`'s relative `image` path one in the agent's own folder on the way (`imageFrom`), since the gateway can't know where the agent runs; an absolute path, `~`, a URL or a drive goes as written. Its sheet says each image goes to Settings › Models › Images › Image recognition's model. That row has Give agents Magpie Image Recognition… (`libWay` in app.js, shared with Images' and Web search's links), Turn on the Library with the Library off, and nothing with recognition off or in gateway mode (`vision-mcp-library.test.cjs`). It gets the same 120-second tool timeout and the same WSL rule as Magpie Web Search. - Discover's featured list is the same with nothing set up: one of magpie's own whose model or search isn't there yet, or which Settings turned off, carries `unready` (`gateway.OwnUnready`, set by the GUI's `/api/library/market/servers`), shown as a Not set up yet badge on its card and the full reason in its sheet. It can still be added, since it answers once that is set up, and until then its tools answer with the same reason, so no agent is given a tool that fails without a word. -- A carried library (`Collect`) has every file of each skill, its templates and other binaries included, up to `maxCarried` (16 MiB) a file and `maxCarriedAll` (32 MiB) in all, chosen smallest first across the skills (`readSkills`), so every skill's text goes before any big file. The total keeps a sealed backup under the 64 MiB a sync reads: the files are base64 twice in it. What is left out is named in `Left`, and `Put` keeps this computer's copy of such a file in the skill it puts (`keepLeft`). [`carry.go`](../../internal/library/carry.go) +- A carried library (`Collect`) has every file of each skill, its templates and other binaries included, up to `maxCarried` (16 MiB) a file and `maxCarriedAll` (32 MiB) in all, chosen smallest first across the skills (`readSkills`), so every skill's text goes before any big file. The total keeps a sealed backup under the 64 MiB a sync reads: the files are base64 twice in it. What is left out is named in `Left`, and `Put` keeps this computer's copy of such a file in the skill it puts (`keepLeft`). A computer that was brought a skill without such files keeps their names in `Skill.Missing`, and its own `Collect` carries them on as `Left` while they aren't there (`missing`), so its sync never takes them from the computer that has them (`TestSkillMissingFilesCarriedOnAsLeft`). A skill from GitHub or another git repository whose folder is still what was fetched (`Hash` known, not changed here) goes as its source (#5715, JJasonsun on Discord: 12 skills, 146 MiB; [`skill_carry.go`](../../internal/library/skill_carry.go)), as a plugin does: `CarriedSkill.Fetch` with its `Hash` and `Commit`, and its files only in the room the skills carried as files leave, so its size never counts and a magpie before this still writes the skill from them. `Put` keeps the folder here when it is that version or was changed here (an update asks before replacing a change; another version there is a problem saying the changes here are kept), and otherwise marks it `Pending` and fetches it after the lock as `UpdateSkills` does, unless the files carried are already the whole of it. One it can't fetch stays `Pending` with a problem, its row is tagged Not fetched yet, and Update or the next sync tries again. A skill from a folder, one changed here, and one whose link holds a sign-in (never synced) go as their files (`TestSkillCarriedBySource`, `TestSkillCarriedBySourceNotFetched`, `TestSkillCarriedBySourceKeepsChangesHere`, `TestSkillCarriedBySourceNewerThere`, `TestSkillOldBundleKeepsHash`, `TestSkillSignedInLinkGoesAsFiles`, `sync-library-left.test.cjs`). [`carry.go`](../../internal/library/carry.go) - A skill can be turned off on this computer alone (`OffHere`, `SkillHere`; the row's power button, `magpie library skill off-here ` and `on-here`; hanslin1666 on Discord). No agent here gets it, whatever its `Agents` say (`gives`, which every reader of `Agents` for giving goes through: `syncSkills`, `desktop_skills.go`, `skill_changed.go`, `skill_edits.go`, `behind`, `Targets`). `Agents` stays what a sync carries, and the page leaves its chips as they are, faded. `Collect` never carries `OffHere`, so turning it off changes no part a sync uploads, and `Put` keeps this computer's `OffHere` for a skill it puts, so a sync from a computer that has it on, or gives it to more agents, never turns it on here. A library.json from before has no `offHere` and every skill stays on. Not covered: a project's skills; a library skill kept in `~/.agents/skills`, which agents read in place, until it is handed over (below); and a skill another computer removes, which takes the flag with it. [`skills.go`](../../internal/library/skills.go), [`carry.go`](../../internal/library/carry.go) - A skill's group (its repository, `tracer.repoOf`) is traced from files that are one computer's own: the skills CLI's lock, a git checkout, CC Switch's record. `Collect` carries the result as `CarriedSkill.From` for a skill with no source of its own (ConatusMoon2222 on X: skills grouped by library on one computer sat in "this computer" on the next after a sync, and Group again had nothing to start from), and `Put` writes it as `Skill.From`. A bundle from before has none: `Put` then keeps the `From` this computer found for the same skill (a Group again, or an earlier sync), and `Skill.Gone` for one with the same source, which are this computer's. Group again fetches each GitHub repository some skill is traced to, so skills synced before still need one skill of the pack that carries its source (or an updated computer's next sync); a pack with no skill traced to it here has nothing to start from. Not covered: `Put` still writes a skill with a bundle's source, so a copy Group again bound to its repository here is unbound by a sync from a computer that has it unbound (`TestSyncedSkillKeepsItsRepo`, `TestSyncKeepsRepoFoundHere`, `TestRegroupAfterOldSync`). [`carry.go`](../../internal/library/carry.go), [`skill_from.go`](../../internal/library/skill_from.go) - An MCP server can be kept to this computer (`Server.Local`; the editor's "Sync to your other computers" switch, off for a local one (it said "This computer only", which bin.90 on Discord read as sharing), the row tagged "Not synced", `magpie library mcp add --local`, `magpie library mcp local on|off`; huhuy72219405 on X). `Collect` never carries it (`carriedServers`), so a sync or a backup file never takes it to another computer, and turning a shared server local takes it out of what is carried: the other computers drop it at their next sync. `Put` (sync, join, Restore, Undo, a backup file) keeps every local server here, with its agents, and clears `Local` on what comes in (`putServers`). Another computer's server by the name of a local one doesn't take its place: it goes to `Library.Away`, given to no agent, not in the router, not checked, and carried on as it came, so a push from here never takes it from the computers that have it. `settleAway` runs on every change: while the name is local here the away copy stays; once no server of that name is left here (removed or renamed) it comes in as a sync would bring it; once a shared server has the name (local turned off) this computer's is the one carried. The router serves local servers like any other, since it runs on this computer. A carried subagent names its servers, a local one too; a computer without that server leaves it out of the agents' files, as any server the library hasn't. The TUI keeps the flag on edit and marks the row. (`TestLocalServerNotCarried`, `TestPutKeepsLocalServer`, `TestPutSameNameAsLocal`, `TestRestoreKeepsLocalServer`, `TestLocalServerThroughSync`, `mcp-local-server.test.cjs`) [`mcp_local.go`](../../internal/library/mcp_local.go), [`carry.go`](../../internal/library/carry.go) diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index 856f362fa..bc7caf5f9 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -639,6 +639,21 @@ plugins were carried, and a bundle without the list leaves this computer's plugins alone. The preview names each plugin, its files as one digest (`TestSyncLibraryPlugins`, `TestNoPluginsHashAsBefore`). +A library skill from GitHub or a git repository goes in the library part as +its source too (#5715, [`skill_carry.go`](../../internal/library/skill_carry.go)), +and the other computer fetches it itself, so a big skill no longer counts +against the 64 MiB. What a sync still leaves out is said, never a silent +success: `state.LibraryLeft` names the skills and plugins whose files were +too big to go (or that this computer never had, `Skill.Missing`), and +`state.LibraryProblems` what the last sync that brought the library in +couldn't put here (a skill not fetched from its source yet, one kept as it +was changed here). `Status` gives them as the view's `libraryLeft` and +`libraryProblems`, dropping a problem settled since (`library.Unsettled`: +Update fetched the skill), and Settings › Sync shows them in red under the +status (`askPreviewRows` in syncfiles.js; `TestSyncSkillsBySourceAndLeftOut`, +`sync-library-left.test.cjs`). A restore (`backup.Restore` through the +restore and plan paths) doesn't record them yet. + ## Verification ```sh diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index 26d119411..eb712712c 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -296,6 +296,13 @@ type state struct { Off []string `json:"off,omitempty"` // Applied is the last sync that brought parts in here, for UndoSync. Applied *applied `json:"applied,omitempty"` + // LibraryLeft is the library's skills and plugins whose files the + // last sync left out of the server's file, too big for it (#5715); + // LibraryProblems what of the library the last sync that brought it + // in couldn't put here, such as a skill not fetched from its source + // yet. Both are said on the Settings page, never a silent success. + LibraryLeft []string `json:"libraryLeft,omitempty"` + LibraryProblems []library.Problem `json:"libraryProblems,omitempty"` } // blind is a write the server didn't check: the file it wrote (Sum), and @@ -587,6 +594,9 @@ type View struct { // Own is the agent fields picked on this computer after a sync set // them, which sync leaves as they are here (own.go) Own []OwnField `json:"own,omitempty"` + // LibraryLeft and LibraryProblems are the last sync's (state) + LibraryLeft []string `json:"libraryLeft,omitempty"` + LibraryProblems []string `json:"libraryProblems,omitempty"` } // OtherView is the other kind's server as the Settings page shows it. @@ -625,6 +635,10 @@ func Status() View { if c.Usage && st.Usage != nil { v.UsageError = st.Usage.Error } + if c.library() { + // one settled since (Update fetched the skill) isn't said + v.LibraryLeft, v.LibraryProblems = st.LibraryLeft, said(library.Unsettled(st.LibraryProblems)) + } if !st.Last.IsZero() { if ps, err := provider.Stored(); err == nil { v.SignIn = provider.NotSignedIn(ps) @@ -1265,12 +1279,57 @@ func bring(b backup.Bundle, part string) error { _, err := backup.Restore(b, backup.Parts{Agents: true}) return err case "library": - _, err := backup.Restore(b, backup.Parts{Library: true}) + _, err := bringLibrary(b) return err } return nil } +// bringLibrary puts the library b carries here, and says what of it +// couldn't be: a skill not fetched from its source yet, one kept as it was +// changed here (library.Put). +func bringLibrary(b backup.Bundle) ([]library.Problem, error) { + r, err := backup.Restore(b, backup.Parts{Library: true}) + return r.LibraryProblems, err +} + +// said is library problems as the Settings page says them: "pdf: why". +func said(probs []library.Problem) []string { + var out []string + for _, p := range probs { + _, name, ok := strings.Cut(p.What, ":") + if !ok { + name = p.What + } + out = append(out, name+": "+p.Error) + } + return out +} + +// leftOut is the skills and plugins whose files this computer's library +// leaves out of a sync, too big for it (library.Collect), or doesn't have +// as another computer left them out (library.Skill's Missing). A skill +// carried as its source isn't: each computer fetches it from there. +func leftOut(l *library.Bundle) []string { + if l == nil { + return nil + } + var names []string + for _, s := range l.Skills { + if len(s.Left) > 0 && !s.Fetch { + names = append(names, s.Name) + } + } + if l.Plugins != nil { + for _, p := range *l.Plugins { + if len(p.Left) > 0 { + names = append(names, p.Name) + } + } + } + return names +} + // keepUnseenGatewayKeys puts the gateway keys this computer holds that the // folder's store has never seen into the store a first sync is about to // bring in (#1714, 8ugMak1r). The store rides the settings part, so a @@ -1441,6 +1500,10 @@ func syncOnce(ctx context.Context, c Config, st *state, pv *Plan) error { st.Plugins = pluginNames(local.Plugins) } st.Off = c.left() + st.LibraryLeft = nil + if c.library() { + st.LibraryLeft = leftOut(local.Library) + } return nil } if sum(data) == st.Sum && maps.Equal(L, st.Local) && !follow && !moved && len(rejoin) == 0 { @@ -1625,6 +1688,7 @@ func syncOnce(ctx context.Context, c Config, st *state, pv *Plan) error { log.Printf("sync: keeping this computer's setup before bringing in %v: %v", bringIn, err) } } + broughtLib := false for _, p := range bringIn { if p == "agents" { got, err := bringAgents(remote.Agents, afterW) @@ -1634,6 +1698,14 @@ func syncOnce(ctx context.Context, c Config, st *state, pv *Plan) error { } continue } + if p == "library" { + probs, err := bringLibrary(remote) + st.LibraryProblems, broughtLib = probs, true + if err != nil { + return fmt.Errorf("bringing in the %s: %w", p, err) + } + continue + } if err := bring(remote, p); err != nil { return fmt.Errorf("bringing in the %s: %w", p, err) } @@ -1740,6 +1812,13 @@ func syncOnce(ctx context.Context, c Config, st *state, pv *Plan) error { } st.Local = now st.Off = c.left() + if !broughtLib { + st.LibraryProblems = library.Unsettled(st.LibraryProblems) + } + st.LibraryLeft = nil + if c.library() { + st.LibraryLeft = leftOut(local.Library) + } if before != "" { st.Applied = &applied{At: time.Now(), Parts: bringIn, File: before, After: now} } diff --git a/internal/davsync/skill_source_test.go b/internal/davsync/skill_source_test.go new file mode 100644 index 000000000..00d121d35 --- /dev/null +++ b/internal/davsync/skill_source_test.go @@ -0,0 +1,132 @@ +package davsync + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/library" +) + +// #5715 (JJasonsun on Discord): a library past a sync's size limit is +// said, never a silent success. A skill from a git repository goes as its +// source, and the other computer fetches it itself: its size doesn't +// count, and one that can't be fetched there is said until Update fetches +// it. A skill of the user's own too big to go is named. +func TestSyncSkillsBySourceAndLeftOut(t *testing.T) { + git, err := exec.LookPath("git") + if err != nil { + t.Skip("git isn't installed") + } + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(t.TempDir(), "gitconfig")) + big := strings.Repeat("x", 17<<20) // past a file's 16 MiB + repo := t.TempDir() + work := filepath.Join(repo, "work") + run := func(dir string, args ...string) { + t.Helper() + cmd := exec.Command(git, append([]string{"-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "init.defaultBranch=main", "-c", "commit.gpgsign=false"}, args...)...) + cmd.Dir = dir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + run(repo, "init", "-q", "--bare", "skills.git") + run(repo, "init", "-q", work) + for p, body := range map[string]string{ + "skills/pdf/SKILL.md": "---\nname: pdf\ndescription: PDFs\n---\n", + "skills/pdf/big.txt": big, + } { + p = filepath.Join(work, filepath.FromSlash(p)) + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + run(work, "add", "-A") + run(work, "commit", "-q", "-m", "skills") + run(work, "push", "-q", filepath.Join(repo, "skills.git"), "HEAD:refs/heads/main") + addr := "file://" + filepath.ToSlash(filepath.Join(repo, "skills.git")) + if !strings.HasPrefix(addr, "file:///") { + addr = "file:///" + strings.TrimPrefix(addr, "file://") // C:/… on Windows + } + withGit := func(c computer) { + t.Helper() + if err := os.Symlink(git, filepath.Join(string(c), "bin", "git")); err != nil { + t.Fatal(err) + } + } + + f, srv := newFakeS3(t) + cfg := f.config(srv) + cfg.Keys, cfg.Agents = false, false + ctx := context.Background() + a, b := newComputer(t), newComputer(t) + + // A: pdf from the repository, and a skill of its own too big to go + a.use(t) + withGit(a) + if _, err := library.InstallSkills(addr, []string{"skills/pdf"}, []string{"claude"}); err != nil { + t.Fatal(err) + } + if _, err := library.CreateSkill("mine", "my own", []string{"claude"}); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(library.Dir(), "skills", "mine", "big.txt"), []byte(big), 0o644); err != nil { + t.Fatal(err) + } + if err := Configure(cfg); err != nil { + t.Fatal(err) + } + if err := Now(ctx); err != nil { + t.Fatal(err) + } + if v := Status(); v.Error != "" || !slices.Equal(v.LibraryLeft, []string{"mine"}) { + t.Fatalf("A's sync: error %q, left out %v, want mine said", v.Error, v.LibraryLeft) + } + + // B, with no git: pdf can't be fetched, and that is said + b.use(t) + if err := Configure(cfg); err != nil { + t.Fatal(err) + } + if err := Now(ctx); err != nil { + t.Fatal(err) + } + v := Status() + if v.Error != "" || len(v.LibraryProblems) != 1 || !strings.HasPrefix(v.LibraryProblems[0], "pdf: not fetched") { + t.Fatalf("B's sync: error %q, problems %q", v.Error, v.LibraryProblems) + } + // git here now: Update fetches it, the whole of it, and nothing is said + withGit(b) + if _, err := library.UpdateSkill("pdf", false); err != nil { + t.Fatal(err) + } + if got, err := os.ReadFile(filepath.Join(library.Dir(), "skills", "pdf", "big.txt")); err != nil || len(got) != len(big) { + t.Fatalf("pdf's big.txt on B: %d bytes, %v", len(got), err) + } + if v := Status(); len(v.LibraryProblems) != 0 { + t.Errorf("fetched, still said: %q", v.LibraryProblems) + } + if err := Now(ctx); err != nil { + t.Fatal(err) + } + if v := Status(); v.Error != "" || len(v.LibraryProblems) != 0 || !slices.Equal(v.LibraryLeft, []string{"mine"}) { + t.Errorf("B's next sync: error %q, problems %q, left %v", v.Error, v.LibraryProblems, v.LibraryLeft) + } + // what B never had of mine isn't taken from A by B's sync + a.use(t) + if err := Now(ctx); err != nil { + t.Fatal(err) + } + if got, err := os.ReadFile(filepath.Join(library.Dir(), "skills", "mine", "big.txt")); err != nil || len(got) != len(big) { + t.Errorf("A's mine/big.txt after B's sync: %d bytes, %v", len(got), err) + } + if v := Status(); v.Error != "" || !slices.Equal(v.LibraryLeft, []string{"mine"}) { + t.Errorf("A's next sync: error %q, left %v", v.Error, v.LibraryLeft) + } +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 86d9c2eaf..e97435d9d 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3419,6 +3419,7 @@ const I18N = { "Nothing to sync: this computer and the server are the same.": "无需同步:这台电脑与服务器一致。", "Already the same: {parts}": "已经一致:{parts}", "Stays as it is on each computer: {parts}": "每台电脑各自保留:{parts}", + "Files too big to sync stay on this computer only, in: {names}": "太大无法同步的文件只留在这台电脑上,位于:{names}", "Undo the last sync?": "撤销上次同步?", "This computer's {parts} go back to how they were before the sync {when}. The server and your other computers keep theirs.": "这台电脑的{parts}会恢复到{when}同步之前的样子。服务器和你的其他电脑保持不变。", "What is here now is kept in the sync folder first.": "当前这里的内容会先保存在同步文件夹中。", @@ -8841,6 +8842,7 @@ const I18N = { "Nothing to sync: this computer and the server are the same.": "無需同步:這臺電腦與伺服器一致。", "Already the same: {parts}": "已經一致:{parts}", "Stays as it is on each computer: {parts}": "每臺電腦各自保留:{parts}", + "Files too big to sync stay on this computer only, in: {names}": "太大無法同步的檔案只留在這台電腦上,位於:{names}", "Undo the last sync?": "復原上次同步?", "This computer's {parts} go back to how they were before the sync {when}. The server and your other computers keep theirs.": "這臺電腦的{parts}會恢復到{when}同步之前的樣子。伺服器和你的其他電腦保持不變。", "What is here now is kept in the sync folder first.": "目前這裡的內容會先保存在同步資料夾中。", @@ -14279,6 +14281,7 @@ const I18N = { "Nothing to sync: this computer and the server are the same.": "同期するものはありません。このコンピューターとサーバーは同じです。", "Already the same: {parts}": "すでに同じ:{parts}", "Stays as it is on each computer: {parts}": "各コンピューターでそのまま:{parts}", + "Files too big to sync stay on this computer only, in: {names}": "大きすぎて同期できないファイルはこのコンピューターにだけ残ります:{names}", "Undo the last sync?": "前回の同期を取り消しますか?", "This computer's {parts} go back to how they were before the sync {when}. The server and your other computers keep theirs.": "このコンピューターの{parts}が、{when}の同期の前の状態に戻ります。サーバーとほかのコンピューターはそのままです。", "What is here now is kept in the sync folder first.": "いまここにあるものは、先に同期フォルダーに保存されます。", @@ -19730,6 +19733,7 @@ const I18N = { "Nothing to sync: this computer and the server are the same.": "Nichts zu synchronisieren: Dieser Computer und der Server sind gleich.", "Already the same: {parts}": "Schon gleich: {parts}", "Stays as it is on each computer: {parts}": "Bleibt auf jedem Computer, wie es ist: {parts}", + "Files too big to sync stay on this computer only, in: {names}": "Zu große Dateien zum Synchronisieren bleiben nur auf diesem Computer, in: {names}", "Undo the last sync?": "Letzte Synchronisierung rückgängig machen?", "This computer's {parts} go back to how they were before the sync {when}. The server and your other computers keep theirs.": "Die {parts} dieses Computers werden wieder so, wie sie vor der Synchronisierung {when} waren. Der Server und deine anderen Computer behalten ihre.", "What is here now is kept in the sync folder first.": "Was jetzt hier ist, wird zuerst im Sync-Ordner aufbewahrt.", diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index b04710a2f..da86de6ca 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -7904,6 +7904,8 @@ magpie.plugin("library", (ctx) => { }; nm.append(b); } + // synced in by its source and not fetched here yet (#5715) + if (s.pending) nm.append(tag(t("Not fetched yet"), "warn lib-pending", t("Not fetched on this computer yet: Update tries again"))); if (s.manual) nm.append(manualTag(s.name)); if (lib.skillRouter && s.router === "direct" && !s.manual) nm.append(tag(t("Not through the router"), "lib-direct", t("Each agent is given it as its own skill, as with the skill router off."))); // turned off on this computer alone: no agent here gets it, the ticks diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 4e9c751d7..596e5c9ac 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -1063,6 +1063,7 @@ magpie.strings({ "billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "这是 billion-context 自己的统计,已扣除折叠后的重建和摘要的开销(扣除前 {gross}):包括这台电脑上它运行过的所有会话,不分 Agent。", "As of {time}: billion-context isn't running now.": "截至 {time}:billion-context 现在没有运行。", "Not fetched on this computer yet: Update tries again": "尚未在这台电脑上获取:点「更新」重试", + "Not fetched yet": "尚未获取", "A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Claude Code 插件把技能、MCP 服务器、hooks 和子代理装成一个包。装一次,magpie 就把每一部分交给你选的智能体;插件可以整体开启、关闭或移除。它的各部分也会出现在各自的标签页里。", "No Claude plugins in the library yet": "资源库里还没有 Claude 插件", "Install one from a folder, a git address or a marketplace.json.": "从文件夹、git 地址或 marketplace.json 安装。", @@ -2157,6 +2158,7 @@ magpie.strings({ "billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "這是 billion-context 自己的統計,已扣除摺疊後的重建和摘要的開銷(扣除前 {gross}):包括這台電腦上它執行過的所有工作階段,不分 Agent。", "As of {time}: billion-context isn't running now.": "截至 {time}:billion-context 現在沒有執行。", "Not fetched on this computer yet: Update tries again": "尚未在這台電腦上取得:按「更新」重試", + "Not fetched yet": "尚未取得", "A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Claude Code 外掛把技能、MCP 伺服器、hooks 和子代理裝成一個包。裝一次,magpie 就把每一部分交給你選的代理;外掛可以整體開啟、關閉或移除。它的各部分也會出現在各自的分頁裡。", "No Claude plugins in the library yet": "資源庫裡還沒有 Claude 外掛", "Install one from a folder, a git address or a marketplace.json.": "從資料夾、git 位址或 marketplace.json 安裝。", @@ -3251,6 +3253,7 @@ magpie.strings({ "billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "billion-context 自身の集計で、折りたたみ後の再構築と要約のコストを差し引いた値です(差し引く前は {gross})。このコンピューターで動いたすべてのセッションが対象で、エージェントは問いません。", "As of {time}: billion-context isn't running now.": "{time} 時点:billion-context は現在動いていません。", "Not fetched on this computer yet: Update tries again": "このコンピューターではまだ取得していません:「アップデート」で再試行", + "Not fetched yet": "未取得", "A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Claude Code プラグインは、スキル、MCP サーバー、フック、サブエージェントを 1 つにまとめたパッケージです。一度インストールすると、magpie が選んだエージェントに各パーツを渡し、プラグイン全体をオン、オフ、削除できます。各パーツはそれぞれのタブにも表示されます。", "No Claude plugins in the library yet": "ライブラリにはまだ Claude プラグインがありません", "Install one from a folder, a git address or a marketplace.json.": "フォルダ、git アドレス、marketplace.json からインストールします。", @@ -4345,6 +4348,7 @@ magpie.strings({ "billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "Die eigene Zählung von billion-context, abzüglich der Neuaufbauten nach einer Faltung und der Kosten der Zusammenfassungen ({gross} davor): jede Sitzung, in der es auf diesem Computer lief, von jedem Agenten.", "As of {time}: billion-context isn't running now.": "Stand {time}: billion-context läuft gerade nicht.", "Not fetched on this computer yet: Update tries again": "Auf diesem Computer noch nicht geladen: „Aktualisieren“ versucht es erneut", + "Not fetched yet": "Noch nicht geladen", "A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Ein Claude-Code-Plugin bündelt Skills, MCP-Server, Hooks und Subagenten in einem Paket. Einmal installieren: magpie gibt jeden Teil den gewählten Agenten, und das Plugin lässt sich als Ganzes ein-, ausschalten oder entfernen. Die Teile erscheinen auch in ihren eigenen Tabs.", "No Claude plugins in the library yet": "Noch keine Claude-Plugins in der Bibliothek", "Install one from a folder, a git address or a marketplace.json.": "Aus einem Ordner, einer Git-Adresse oder einer marketplace.json installieren.", diff --git a/internal/gui/assets/syncfiles.js b/internal/gui/assets/syncfiles.js index 7e92e19a5..85c800f72 100644 --- a/internal/gui/assets/syncfiles.js +++ b/internal/gui/assets/syncfiles.js @@ -554,6 +554,14 @@ window.askUndoSync = function (v) { window.askPreviewRows = function (at, v, sub) { const left = ["providers", "settings", "profiles", "agents", "library", "memory"].filter((p) => v[p] === false); if (left.length) sub.after(el("div", "sub wraps sync-left", t("Stays as it is on each computer: {parts}", { parts: syncParts(left) }))); + // the library's files too big to sync, and skills a sync couldn't fetch + // from their source here: said, never a silent success (#5715) + const lib = [v.libraryLeft?.length && t("Files too big to sync stay on this computer only, in: {names}", { names: v.libraryLeft.join(t(", ")) }), ...v.libraryProblems || []].filter(Boolean); + if (!v.error && lib.length) { + const d = el("div", "sub bad wraps sync-lib"); + for (const l of lib) d.append(el("div", "", l)); + sub.after(d); + } const row = (name, sub, b, cls) => { const r = el("div", "row pref wraps " + cls), who = el("div", "who"), val = el("div", "val"); who.append(el("div", "name", name), el("div", "sub", sub)); diff --git a/internal/gui/tests/sync-library-left.test.cjs b/internal/gui/tests/sync-library-left.test.cjs new file mode 100644 index 000000000..d155a09a4 --- /dev/null +++ b/internal/gui/tests/sync-library-left.test.cjs @@ -0,0 +1,136 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #5715 (JJasonsun on Discord): a library past a sync's size limit synced +// "fine" while its big skills never reached the other computer. Settings › +// Sync now says it in red under the status: the files too big to go, and +// the skills a sync couldn't fetch from their source here, each on a line +// of its own, wrapped whole. A sync that failed says only that, and one +// with nothing left out has no such line. Library › Skills tags a skill +// not fetched yet "Not fetched yet", its tip saying Update tries again. In +// English, Chinese, Japanese and German, Chromium and WebKit, at 900 and +// 440px. The API is faked; nothing is synced. +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 assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/jason"; +const FETCH = "pdf: not fetched from its source on this computer yet (Update tries again): git isn't installed"; + +const library = { + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [{ id: "claude", name: "Claude Code", icon: "", skills: `${HOME}/.claude/skills` }], + instructions: { agents: [] }, servers: [], foundServers: [], projects: [], foundSkills: [], newSkills: [], checkDue: false, + skills: [ + { name: "pdf", description: "PDFs", kind: "github", source: "https://github.com/anthropics/skills/tree/HEAD/skills/pdf", agents: ["claude"], pending: true }, + { name: "docx", description: "Word files", kind: "github", source: "https://github.com/anthropics/skills/tree/HEAD/skills/docx", agents: ["claude"] }, + ], +}; + +function serve(lang, sync) { + 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 pathname = new URL(route.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/providers") return json({ providers: [], gateway: { running: true } }); + if (pathname === "/api/davsync") return json(sync); + if (pathname === "/api/library") return json(library); + 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 }); + }; +} + +const words = { + en: { left: "Files too big to sync stay on this computer only, in: mine, big-notes", tag: "Not fetched yet", tip: "Not fetched on this computer yet: Update tries again" }, + zh: { left: "太大无法同步的文件只留在这台电脑上,位于:mine、big-notes", tag: "尚未获取", tip: "尚未在这台电脑上获取:点「更新」重试" }, + ja: { left: "大きすぎて同期できないファイルはこのコンピューターにだけ残ります:mine、big-notes", tag: "未取得", tip: "このコンピューターではまだ取得していません:「アップデート」で再試行" }, + de: { left: "Zu große Dateien zum Synchronisieren bleiben nur auf diesem Computer, in: mine, big-notes", tag: "Noch nicht geladen", tip: "Auf diesem Computer noch nicht geladen: „Aktualisieren“ versucht es erneut" }, +}; + +const base = { on: true, kind: "webdav", url: "https://dav.jianguoyun.com/dav/", user: "me", passwordSet: true, passphraseSet: true, keys: true, agents: true, library: true, usage: true }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [900, 440]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: what a sync left out of the library is said`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const last = new Date(Date.now() - 60000).toISOString(); + for (const c of [ + { name: "left out", sync: { ...base, last, libraryLeft: ["mine", "big-notes"], libraryProblems: [FETCH] }, want: [w.left, FETCH] }, + { name: "not fetched", sync: { ...base, last, libraryProblems: [FETCH] }, want: [FETCH] }, + { name: "all synced", sync: { ...base, last }, want: [] }, + { name: "sync failed", sync: { ...base, error: "the WebDAV server refused the user name or password (HTTP 401)", libraryLeft: ["mine"] }, want: [] }, + ]) { + const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage(); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, c.sync)); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + await page.goto("http://magpie.test/"); + await page.locator("#prefs").click(); + await openPart(page, "sync"); + await page.locator("#syncList .sync-preview-row").waitFor({ state: "visible" }); + const line = page.locator("#syncList .sync-lib"); + if (!c.want.length) { + assert.equal(await line.count(), 0, `${c.name}: no library line`); + } else { + assert.equal(await line.count(), 1, `${c.name}: one library line`); + assert.deepEqual(await line.locator(":scope > div").allTextContents(), c.want, c.name); + const [color, red] = await page.evaluate(() => { + const probe = document.createElement("i"); + probe.style.color = "var(--red)"; + document.body.append(probe); + const r = getComputedStyle(probe).color; + probe.remove(); + return [getComputedStyle(document.querySelector("#syncList .sync-lib")).color, r]; + }); + assert.equal(color, red, `${c.name}: the line is red`); + const fit = await line.evaluate((e) => ({ sw: e.scrollWidth, cw: e.clientWidth, right: e.getBoundingClientRect().right })); + assert.ok(fit.sw <= fit.cw + 1, `${c.name}: not cut off: ${JSON.stringify(fit)}`); + assert.ok(fit.right <= width, `${c.name}: inside the window: ${JSON.stringify(fit)}`); + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(over <= 0, `no sideways scroll: ${over}`); + if (process.env.ARTIFACT_DIR && c.name === "left out") { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.locator("#syncList").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-sync-library-left.png`) }); + } + } + if (c.name === "left out") { + // the skill not fetched yet is tagged in Library › Skills + await page.evaluate(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} }); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const v = page.locator("#view-library"); + const tag = v.locator(".lib-skill .lib-tag.lib-pending"); + await tag.first().waitFor(); + assert.equal(await tag.count(), 1, "only pdf is tagged"); + const row = v.locator(".lib-skill", { has: page.locator(".lib-tag.lib-pending") }); + assert.match(await row.locator(".name").first().textContent(), /^pdf/); + assert.equal((await tag.textContent()).trim(), w.tag); + assert.equal(await tag.getAttribute("title"), w.tip); + } + assert.deepEqual(errors, []); + await page.close(); + } + }); + } + } +} diff --git a/internal/library/carry.go b/internal/library/carry.go index 21b4e354e..f6588d3ad 100644 --- a/internal/library/carry.go +++ b/internal/library/carry.go @@ -84,6 +84,14 @@ type CarriedSkill struct { // so without this the other computer groups the skill under "this // computer". Bundles from before this have none. From string `json:"from,omitempty"` + // Fetch is a skill carried as its source (skill_carry.go): the other + // computer fetches it from there, at the version Hash names (Commit + // too, for a git repository's), and Files are only what fit, standing + // in until then. A magpie from before this leaves it out and writes + // the files, as it did. + Fetch bool `json:"fetch,omitempty"` + Hash string `json:"hash,omitempty"` + Commit string `json:"commit,omitempty"` } // A skill's file bigger than maxCarried is left out, and so are the @@ -143,22 +151,47 @@ func Collect() (*Bundle, error) { } skills := sorted(slices.DeleteFunc(slices.Clone(l.Skills), func(s *Skill) bool { return l.ownedPart(s.Bundle) }), func(s *Skill) string { return s.Name }) - dirs := []string{} + // a skill carried as its source (skill_carry.go) takes only the room + // the ones carried as their files leave + var asFiles, asSource []*Skill + dirs, sdirs := []string{}, []string{} for _, s := range skills { - dirs = append(dirs, realDir(skillDir(s.Name))) + if l.bySource(s) { + asSource, sdirs = append(asSource, s), append(sdirs, realDir(skillDir(s.Name))) + } else { + asFiles, dirs = append(asFiles, s), append(dirs, realDir(skillDir(s.Name))) + } } // a plugin's files from a folder are read with the skills', in one // budget plugins, pdirs, at := l.carriedPlugins() read := readSkills(append(dirs, pdirs...)) - for i, f := range read[len(skills):] { + for i, f := range read[len(asFiles):] { c := plugins[at[i]] c.Files, c.Exec, c.Left = f.Files, f.Exec, f.Left } b.Plugins = &plugins + used := int64(0) + for _, c := range read { + for _, f := range c.Files { + used += int64(len(f)) + } + } + carried := map[string]*CarriedSkill{} + for i, c := range readSkillsMax(sdirs, maxCarried, max(maxCarriedAll-used, 0)) { + s := asSource[i] + c.Fetch, c.Hash, c.Commit = true, s.Hash, s.Commit + carried[s.Name] = c + } + for i, c := range read[:len(asFiles)] { + carried[asFiles[i].Name] = c + } + for _, s := range skills { + missing(carried[s.Name], s) + } tr := &tracer{} - for i, c := range read[:len(skills)] { - s := skills[i] + for _, s := range skills { + c := carried[s.Name] if s.Source == nil || s.Source.Kind == "folder" { c.From = tr.repoOf(s) } @@ -562,10 +595,10 @@ func Put(b *Bundle) (*Result, error) { } biliWrote := false var fetch []*CarriedPlugin - var gone []string - var plProblems []Problem + var gone, fetchS []string + var plProblems, skProblems []Problem res, err := change(func(l *Library) error { - fetch, gone, plProblems = nil, nil, nil + fetch, gone, fetchS, plProblems, skProblems = nil, nil, nil, nil, nil if err := os.MkdirAll(skillsDir(), 0o755); err != nil { return err } @@ -586,7 +619,17 @@ func Put(b *Bundle) (*Result, error) { } keep, link := map[string]bool{}, map[string]string{} + // a skill carried as its source (skill_carry.go) + bySrc := map[string]*fromSource{} for _, s := range b.Skills { + p := l.fromSourceHere(s) + if p != nil { + bySrc[s.Name] = p + if p.keep { + keep[s.Name] = true + continue + } + } if cur := l.skill(s.Name); cur != nil && sameSource(cur.Source, s.Source) { if have := readSkills([]string{realDir(skillDir(s.Name))})[0]; sameFiles(have, s) { keep[s.Name] = true @@ -607,6 +650,9 @@ func Put(b *Bundle) (*Result, error) { if err := keepLeft(filepath.Join(stage, s.Name), realDir(skillDir(s.Name)), s); err != nil { return fmt.Errorf("skill %s: %w", s.Name, err) } + if p != nil { + p.whole(filepath.Join(stage, s.Name), s) + } } // every skill's files are ready: out with the old ones @@ -647,6 +693,26 @@ func Put(b *Bundle) (*Result, error) { } n.Gone = cur.Gone // kept on this computer only n.Home = cur.Home // where it was in this computer's agents + if keep[s.Name] { + // the same files: what was fetched is still known + n.Hash, n.Own, n.Commit = cur.Hash, cur.Own, cur.Commit + } + } + if len(s.Left) > 0 { + dir := filepath.Join(stage, s.Name) + if keep[s.Name] { + dir = realDir(skillDir(s.Name)) + } + n.Missing = notIn(dir, s.Left) + } + if p := bySrc[s.Name]; p != nil { + n.Hash, n.Own, n.Commit, n.Pending = p.hash, p.own, p.commit, p.pending + if p.fetch { + fetchS = append(fetchS, s.Name) + } + if p.changed { + skProblems = append(skProblems, changedHere(s.Name)) + } } skills = append(skills, n) if keep[s.Name] { @@ -795,7 +861,9 @@ func Put(b *Bundle) (*Result, error) { if err == nil { removePluginDirs(gone) res.Problems = append(res.Problems, plProblems...) + res.Problems = append(res.Problems, skProblems...) fetchPlugins(fetch, res) + fetchSkills(fetchS, res) } return res, err } diff --git a/internal/library/skill_carry.go b/internal/library/skill_carry.go new file mode 100644 index 000000000..1f69f9dbd --- /dev/null +++ b/internal/library/skill_carry.go @@ -0,0 +1,178 @@ +package library + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "strings" +) + +// A skill from GitHub or another git repository whose folder is still +// the files fetched from there goes to the other computers as its source +// (#5715, JJasonsun on Discord), as a plugin does (plugin_carry.go): each +// computer fetches it itself, so a skill's size never counts against a +// sync's (a sync reads at most 64 MiB, maxCarriedAll). It still carries +// what of its files fit in the room the skills carried as files leave, so +// a magpie from before this, which knows nothing of Fetch, writes the +// skill as it did; on this one they only stand in until it is fetched. +// +// A skill changed here since it was fetched, one from a folder, and one +// from a link holding a token (whose link must not be synced) go as their +// files, as before. + +// bySource reports whether Collect carries s as its source. +func (l *Library) bySource(s *Skill) bool { + if !s.Source.remote() || s.Hash == "" || signedIn(s.Source.String()) { + return false + } + if s.Pending { // still the version the other computer has, to fetch + return true + } + edited, known := l.editState(s, nil) + return known && !edited +} + +// fromSource is what Put does with a skill carried as its source. +type fromSource struct { + keep bool // the folder here stays as it is + hash, own, commit string + pending, fetch bool + changed bool // edited here while the other computer's is another version +} + +// fromSourceHere decides how a skill carried as its source is put here: +// nil for one carried as its files. The folder here stays when it is the +// same version, or changed here (an update asks before replacing that), +// or the same source at another version, which is fetched after. One new +// here is written from the files carried and fetched after, unless they +// are the whole of it already. +func (l *Library) fromSourceHere(c *CarriedSkill) *fromSource { + if !c.Fetch || !c.Source.remote() || c.Hash == "" || signedIn(c.Source.String()) { + return nil + } + cur := l.skill(c.Name) + if cur == nil || !sameSource(cur.Source, c.Source) { + return &fromSource{hash: c.Hash, commit: c.Commit, pending: true, fetch: true} + } + if cur.Pending { + return &fromSource{keep: true, hash: c.Hash, commit: c.Commit, pending: true, fetch: true} + } + edited, known := l.editState(cur, nil) + switch { + case edited: + // this computer's changes stay; a skill the other computer has + // at the version this one was fetched at is no conflict + return &fromSource{keep: true, hash: cur.Hash, own: cur.Own, commit: cur.Commit, changed: cur.Hash != c.Hash} + case known && cur.Hash == c.Hash: + return &fromSource{keep: true, hash: cur.Hash, own: cur.Own, commit: cur.Commit} + } + // another version, or one not known unchanged: fetched, what is here + // now kept with the backups as an update keeps it + return &fromSource{keep: true, hash: c.Hash, commit: c.Commit, pending: true, fetch: true} +} + +// whole is whether the files carried for a skill new here, written at +// dir, are all of the version it was carried at: then nothing is fetched. +func (p *fromSource) whole(dir string, c *CarriedSkill) { + if len(c.Left) == 0 && hashDir(dir) == c.Hash { + p.pending, p.fetch, p.own = false, false, ownHash(dir) + } +} + +// fetchSkills fetches from their sources the skills Put brought by them, +// after the library's lock is let go, as UpdateSomeSkills does. One that +// can't be fetched stays Pending with a problem; the next sync, or +// Update, tries again. +func fetchSkills(names []string, res *Result) { + if len(names) == 0 { + return + } + r, err := updateSkills(names) + if err != nil { + for _, n := range names { + res.Problems = append(res.Problems, notFetched(n, err.Error())) + } + return + } + for _, p := range r.Unupdated { + res.Problems = append(res.Problems, notFetched(strings.TrimPrefix(p.What, "skill:"), p.Error)) + } + for _, n := range r.Gone { + res.Problems = append(res.Problems, notFetched(n, "its source doesn't have it any more")) + } + for _, a := range r.Changed { + if !slices.Contains(res.Changed, a) { + res.Changed = append(res.Changed, a) + } + } + res.Problems = append(res.Problems, r.Problems...) +} + +func notFetched(name, why string) Problem { + return Problem{What: "skill:" + name, Error: "not fetched from its source on this computer yet (Update tries again): " + why} +} + +// changedHere is the problem of a skill kept as it was changed here while +// the other computer has another version of it. +func changedHere(name string) Problem { + return Problem{What: "skill:" + name, Error: fmt.Sprintf("%s was changed on this computer, and another computer has another version from its source: "+ + "the changes here are kept; Update replaces them with its source's version", name)} +} + +// Unsettled is the problems a sync's Put said that still hold: a skill's +// while it is still to be fetched (Pending) or changed here, and none +// else (a plugin's is said on its row). A library that can't be read +// keeps them all. +func Unsettled(probs []Problem) []Problem { + if len(probs) == 0 { + return nil + } + mu.Lock() + defer mu.Unlock() + l, err := load() + if err != nil { + return probs + } + var out []Problem + for _, p := range probs { + name, ok := strings.CutPrefix(p.What, "skill:") + if !ok { + continue + } + s := l.skill(name) + if s == nil { + continue + } + if edited, _ := l.editState(s, nil); s.Pending || edited { + out = append(out, p) + } + } + return out +} + +// notIn is the files of rels that the folder dir doesn't have. +func notIn(dir string, rels []string) []string { + var out []string + for _, rel := range rels { + if fi, err := os.Lstat(filepath.Join(dir, filepath.FromSlash(rel))); err != nil || !fi.Mode().IsRegular() { + out = append(out, rel) + } + } + return out +} + +// missing adds to what Collect carries of s the files a sync brought it +// without that are still not here (Skill.Missing): left out, as on the +// computer that has them. +func missing(c *CarriedSkill, s *Skill) { + if c == nil || len(s.Missing) == 0 { + return + } + for _, rel := range notIn(realDir(skillDir(s.Name)), s.Missing) { + if _, ok := c.Files[rel]; !ok && !slices.Contains(c.Left, rel) { + c.Left = append(c.Left, rel) + } + } + slices.Sort(c.Left) +} diff --git a/internal/library/skill_carry_test.go b/internal/library/skill_carry_test.go new file mode 100644 index 000000000..beff13c1d --- /dev/null +++ b/internal/library/skill_carry_test.go @@ -0,0 +1,304 @@ +package library + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" +) + +// carrySource serves owner/repo, whose skills/pdf says version, and counts +// the downloads; down makes it refuse them. +func carrySource(t *testing.T, version *string) (hits *atomic.Int32, down *atomic.Bool) { + t.Helper() + // another test's download of owner/repo, kept for an install, isn't + // this server's + forgetProbes() + t.Cleanup(forgetProbes) + hits, down = &atomic.Int32{}, &atomic.Bool{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if down.Load() { + http.Error(w, "no", http.StatusServiceUnavailable) + return + } + hits.Add(1) + w.Write(tarball(t, map[string]string{ + "skills/pdf/SKILL.md": "---\nname: pdf\ndescription: PDFs " + *version + "\n---\n", + "skills/pdf/forms.md": "forms " + *version, + })) + })) + t.Cleanup(srv.Close) + old := tarballURL + tarballURL = func(repo, ref string) string { return srv.URL + "/" + repo + "/" + ref } + t.Cleanup(func() { tarballURL = old }) + return hits, down +} + +func carriedSkill(t *testing.T, b *Bundle, name string) *CarriedSkill { + t.Helper() + for _, s := range b.Skills { + if s.Name == name { + return s + } + } + t.Fatalf("no skill %s carried", name) + return nil +} + +func librarySkill(t *testing.T, name string) *Skill { + t.Helper() + mu.Lock() + l, err := load() + mu.Unlock() + if err != nil { + t.Fatal(err) + } + s := l.skill(name) + if s == nil { + t.Fatalf("no skill %s in the library", name) + } + return s +} + +// leaveOut is j with the named file of a skill left out of what it +// carries, as the size limit leaves a big one out. +func leaveOut(t *testing.T, j, name, file string) string { + t.Helper() + var b Bundle + if err := json.Unmarshal([]byte(j), &b); err != nil { + t.Fatal(err) + } + c := carriedSkill(t, &b, name) + delete(c.Files, file) + c.Left = append(c.Left, file) + return mustJSON(t, &b) +} + +// #5715 (JJasonsun on Discord): a skill fetched from GitHub goes to the +// other computers as its source, which each fetches itself; what of its +// files the size limit left out is fetched, never missing silently. One +// of the user's own goes as its files, as before. The second computer +// carries back the same library. +func TestSkillCarriedBySource(t *testing.T) { + sandbox(t) + version := "one" + hits, _ := carrySource(t, &version) + ok(t)(InstallSkills("owner/repo", []string{"skills/pdf"}, []string{"claude"})) + ok(t)(CreateSkill("mine", "my own", []string{"claude"})) + b := must(Collect()) + pdf, mine := carriedSkill(t, b, "pdf"), carriedSkill(t, b, "mine") + if !pdf.Fetch || pdf.Hash == "" || pdf.Hash != librarySkill(t, "pdf").Hash { + t.Fatalf("pdf isn't carried as its source: %s", mustJSON(t, pdf)) + } + // for a magpie before this, its files as they fit + if len(pdf.Files) != 2 { + t.Errorf("pdf's files aren't carried for an older magpie: %v", pdf.Files) + } + if mine.Fetch || mine.Hash != "" || len(mine.Files) == 0 { + t.Errorf("a skill of the user's own isn't carried as its files: %s", mustJSON(t, mine)) + } + carried := mustJSON(t, b) + + // the whole of it carried: nothing to fetch + sandbox(t) + before := hits.Load() + r := putJSON(t, carried) + if len(r.Problems) != 0 || hits.Load() != before { + t.Errorf("a skill carried whole was fetched (%d) or has problems: %+v", hits.Load()-before, r.Problems) + } + if s := librarySkill(t, "pdf"); s.Pending || s.Hash != pdf.Hash { + t.Errorf("pdf here: %+v", s) + } + if back := mustJSON(t, must(Collect())); back != carried { + t.Errorf("the second computer carries back another library:\n%s\nwas\n%s", back, carried) + } + + // forms.md left out by the size limit: fetched from GitHub here + sandbox(t) + before = hits.Load() + r = putJSON(t, leaveOut(t, carried, "pdf", "forms.md")) + if len(r.Problems) != 0 || hits.Load() == before { + t.Fatalf("pdf wasn't fetched (%d): %+v", hits.Load()-before, r.Problems) + } + if got := read(t, filepath.Join(skillDir("pdf"), "forms.md")); got != "forms one" { + t.Errorf("forms.md here: %q", got) + } + if s := librarySkill(t, "pdf"); s.Pending || s.Hash != pdf.Hash { + t.Errorf("pdf here: %+v", s) + } + if back := mustJSON(t, must(Collect())); back != carried { + t.Errorf("the fetched skill carries back another library:\n%s\nwas\n%s", back, carried) + } +} + +// A computer that can't reach the source keeps the skill Pending, with +// what came standing in, says so, and carries it on as its source at the +// other computer's version; Update fetches it once it can. +func TestSkillCarriedBySourceNotFetched(t *testing.T) { + sandbox(t) + version := "one" + _, down := carrySource(t, &version) + ok(t)(InstallSkills("owner/repo", []string{"skills/pdf"}, []string{"claude"})) + carried := mustJSON(t, must(Collect())) + hash := librarySkill(t, "pdf").Hash + + sandbox(t) + down.Store(true) + r := putJSON(t, leaveOut(t, carried, "pdf", "forms.md")) + if len(r.Problems) != 1 || r.Problems[0].What != "skill:pdf" || !strings.Contains(r.Problems[0].Error, "Update tries again") { + t.Fatalf("problems: %+v", r.Problems) + } + if v := skillView(t, "pdf"); !v.Pending || v.Edited { + t.Errorf("not shown pending: %+v", v) + } + if s := librarySkill(t, "pdf"); !s.Pending || s.Hash != hash { + t.Errorf("pdf here: %+v", s) + } + if c := carriedSkill(t, must(Collect()), "pdf"); !c.Fetch || c.Hash != hash { + t.Errorf("a pending skill isn't carried on as its source: %s", mustJSON(t, c)) + } + // the next sync tries again, and so does Update + down.Store(false) + ok(t)(UpdateSkill("pdf", false)) + if s := librarySkill(t, "pdf"); s.Pending || s.Hash != hash { + t.Errorf("pdf after Update: %+v", s) + } + if got := read(t, filepath.Join(skillDir("pdf"), "forms.md")); got != "forms one" { + t.Errorf("forms.md after Update: %q", got) + } +} + +// A skill changed on the receiving computer isn't written over by the +// other computer's version from its source: kept, and said, while the two +// versions differ. At the same version there is nothing to say. +func TestSkillCarriedBySourceKeepsChangesHere(t *testing.T) { + sandbox(t) + version := "one" + hits, _ := carrySource(t, &version) + ok(t)(InstallSkills("owner/repo", []string{"skills/pdf"}, []string{"claude"})) + carried := mustJSON(t, must(Collect())) + + write(t, filepath.Join(skillDir("pdf"), "forms.md"), "my forms") + if c := carriedSkill(t, must(Collect()), "pdf"); c.Fetch || string(c.Files["forms.md"]) != "my forms" { + t.Errorf("a skill changed here isn't carried as its files: %s", mustJSON(t, c)) + } + r := putJSON(t, carried) + if len(r.Problems) != 0 || read(t, filepath.Join(skillDir("pdf"), "forms.md")) != "my forms" { + t.Errorf("the same version: %+v, forms.md %q", r.Problems, read(t, filepath.Join(skillDir("pdf"), "forms.md"))) + } + + // the other computer has another version + var b Bundle + if err := json.Unmarshal([]byte(carried), &b); err != nil { + t.Fatal(err) + } + c := carriedSkill(t, &b, "pdf") + c.Hash, c.Files["forms.md"] = "another", []byte("forms two") + before := hits.Load() + r = putJSON(t, mustJSON(t, &b)) + if len(r.Problems) != 1 || r.Problems[0].What != "skill:pdf" || !strings.Contains(r.Problems[0].Error, "changed on this computer") { + t.Errorf("problems: %+v", r.Problems) + } + if got := read(t, filepath.Join(skillDir("pdf"), "forms.md")); got != "my forms" || hits.Load() != before { + t.Errorf("the change here was written over (%q), or fetched (%d)", got, hits.Load()-before) + } + if v := skillView(t, "pdf"); !v.Edited || v.Pending { + t.Errorf("pdf is no longer said to be changed here: %+v", v) + } +} + +// One at another version here, unchanged, is fetched: what was here is +// kept with the backups, as an update keeps it. +func TestSkillCarriedBySourceNewerThere(t *testing.T) { + sandbox(t) + version := "one" + carrySource(t, &version) + ok(t)(InstallSkills("owner/repo", []string{"skills/pdf"}, []string{"claude"})) + version = "two" + var b Bundle + if err := json.Unmarshal([]byte(mustJSON(t, must(Collect()))), &b); err != nil { + t.Fatal(err) + } + carriedSkill(t, &b, "pdf").Hash = "two's" + r := putJSON(t, mustJSON(t, &b)) + if len(r.Problems) != 0 { + t.Errorf("problems: %+v", r.Problems) + } + if got := read(t, filepath.Join(skillDir("pdf"), "forms.md")); got != "forms two" { + t.Errorf("forms.md here: %q", got) + } + if s := librarySkill(t, "pdf"); s.Pending || s.Hash == "two's" || s.Hash == "" { + t.Errorf("pdf here: %+v", s) + } +} + +// A bundle from a magpie before this carries no Fetch: the same files are +// kept, and so is the hash of what was fetched, so the skill still goes as +// its source from here. +func TestSkillOldBundleKeepsHash(t *testing.T) { + sandbox(t) + version := "one" + carrySource(t, &version) + ok(t)(InstallSkills("owner/repo", []string{"skills/pdf"}, []string{"claude"})) + hash := librarySkill(t, "pdf").Hash + b := must(Collect()) + c := carriedSkill(t, b, "pdf") + c.Fetch, c.Hash, c.Commit = false, "", "" + if j := mustJSON(t, c); strings.Contains(j, "fetch") || strings.Contains(j, "hash") { + t.Fatalf("not as an older magpie carries it: %s", j) + } + putJSON(t, mustJSON(t, b)) + if s := librarySkill(t, "pdf"); s.Hash != hash { + t.Errorf("the hash of what was fetched is lost: %+v", s) + } + if c := carriedSkill(t, must(Collect()), "pdf"); !c.Fetch { + t.Errorf("no longer carried as its source") + } +} + +// A link holding a token is never synced: such a skill goes as its files, +// and a bundle naming one is put from its files, not fetched. +func TestSkillSignedInLinkGoesAsFiles(t *testing.T) { + l := &Library{} + for _, repo := range []string{"https://me:ghp_secret@example.com/team/skills.git", "https://ghp_secret@example.com/team/skills.git"} { + // Pending: carried by its source whatever its folder holds, but for the link + s := &Skill{Name: "x", Source: &Source{Kind: "git", Repo: repo}, Hash: "h", Pending: true} + if l.bySource(s) { + t.Errorf("%s is carried as its source", repo) + } + if l.fromSourceHere(&CarriedSkill{Name: "x", Source: s.Source, Fetch: true, Hash: "h"}) != nil { + t.Errorf("%s is fetched", repo) + } + } + if l.fromSourceHere(&CarriedSkill{Name: "x", Source: &Source{Kind: "github", Repo: "o/r"}, Fetch: true, Hash: "h"}) == nil { + t.Errorf("a public GitHub source isn't fetched") + } +} + +// A file another computer left out as too big (Left) that this one +// doesn't have goes on as left out from here, until it is here: this +// computer's sync never takes it from the one that has it. +func TestSkillMissingFilesCarriedOnAsLeft(t *testing.T) { + sandbox(t) + ok(t)(CreateSkill("mine", "my own", []string{"claude"})) + j := leaveOut(t, mustJSON(t, must(Collect())), "mine", "big.bin") + sandbox(t) + if r := putJSON(t, j); len(r.Problems) != 0 { + t.Fatalf("problems: %+v", r.Problems) + } + if c := carriedSkill(t, must(Collect()), "mine"); !slices.Equal(c.Left, []string{"big.bin"}) { + t.Fatalf("not carried on as left out: %s", mustJSON(t, c)) + } + if back := mustJSON(t, must(Collect())); back != j { + t.Errorf("carries back another library:\n%s\nwas\n%s", back, j) + } + // here now: carried as any file + write(t, filepath.Join(skillDir("mine"), "big.bin"), "big") + if c := carriedSkill(t, must(Collect()), "mine"); len(c.Left) != 0 || string(c.Files["big.bin"]) != "big" { + t.Errorf("here now, still left out: %s", mustJSON(t, c)) + } +} diff --git a/internal/library/skill_changed.go b/internal/library/skill_changed.go index c01178da2..8facf520e 100644 --- a/internal/library/skill_changed.go +++ b/internal/library/skill_changed.go @@ -138,9 +138,9 @@ func libraryHash(name string) string { // an agent's copy of it was edited since magpie made it and isn't taken // in yet. known is false when that can't be told: magpie didn't keep the // hash of what it fetched (installed before it did), or the folder can't -// be read. +// be read, or it is Pending: its folder isn't the version Hash names. func (l *Library) editState(s *Skill, targets []*Target) (edited, known bool) { - if !s.Source.remote() || s.Hash == "" { + if !s.Source.remote() || s.Hash == "" || s.Pending { return false, false } lib := skillDir(s.Name) diff --git a/internal/library/skills.go b/internal/library/skills.go index 8468f5246..5ccc5f1b9 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -47,6 +47,17 @@ type Skill struct { // writes (ownHash): set as it is fetched, so a lock file the install // writes again isn't taken for a change of the user's Own string `json:"own,omitempty"` + // Pending is a skill a sync brought by its source (skill_carry.go) + // that isn't fetched from there on this computer yet: Hash and Commit + // are the version the other computer has, its folder what came with + // the sync or the older version here. The next sync, or Update, fetches + // it; an update clears it. + Pending bool `json:"pending,omitempty"` + // Missing are the files another computer has of the skill that a sync + // left out as too big to carry (CarriedSkill.Left), which this one + // doesn't have: it carries them on as left out, so its sync never + // takes them from the computer that has them (#5715), and says so. + Missing []string `json:"missing,omitempty"` // From is the repository one not installed from GitHub was found to // come from (skill_from.go), only to group it with the rest of it From string `json:"from,omitempty"` @@ -2150,8 +2161,15 @@ func (up *skillUpdate) apply(l *Library, targets []*Target) error { } // the commit it's at is known again once a check finds the files // GitHub has to be these; a git repository's is the one fetched - s.Hash, s.Own, s.Commit = hash, own, up.commit + commit := up.commit + if s.Pending && hash == s.Hash && commit == "" { + // the version the other computer has, whose check found the + // commit GitHub has it at (skill_carry.go) + commit = s.Commit + } + s.Hash, s.Own, s.Commit = hash, own, commit s.Gone = "" // its source has it again + s.Pending, s.Missing = false, nil } forgetCheck(name) if old == "" { diff --git a/internal/library/sync.go b/internal/library/sync.go index 7564ffa93..ab7124515 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -503,6 +503,9 @@ type SkillView struct { // in the library or in an agent's copy: an update replaces that, so // the page asks first (#1449) Edited bool `json:"edited,omitempty"` + // Pending is one a sync brought by its source and not yet fetched + // from there on this computer (Skill.Pending): Update tries again + Pending bool `json:"pending,omitempty"` // Gone is when its source was found without it: removed there, the // page offers to take it out (skill_gone.go) Gone string `json:"gone,omitempty"` @@ -769,7 +772,7 @@ func readView(problems []Problem, glance bool) (*View, error) { v.Plugins = l.pluginsView() tr := &tracer{} for _, s := range l.Skills { - sv := SkillView{Name: s.Name, Bundle: s.Bundle, Agents: append([]string{}, s.Agents...), Icon: skillIcon(s), Problems: of("skill:" + s.Name), Repo: tr.repoOf(s), OffHere: s.OffHere, Note: s.Note, Router: s.Router} + sv := SkillView{Name: s.Name, Bundle: s.Bundle, Agents: append([]string{}, s.Agents...), Icon: skillIcon(s), Problems: of("skill:" + s.Name), Repo: tr.repoOf(s), OffHere: s.OffHere, Note: s.Note, Router: s.Router, Pending: s.Pending} if s.Source != nil { sv.Source, sv.Kind = s.Source.String(), s.Source.Kind }