TestPluginToldWhereTheAgentWorks was red on any machine with an empty .git above its temp folder. GitOnDisk took the first .git it met going up as a repository, and on this box /tmp/.git is an empty folder (owned by nobody), so every folder under /tmp read "yes". git passes such a folder over and goes on up: git rev-parse under it says "not a git repository". GitOnDisk now reads each .git on the way as git's own search does (repo_discovery_find_dir in git 2.56's setup.c), through GitAt: - A folder counts when git takes it for a repository (is_git_directory): a HEAD git takes (a link into refs/, "ref: refs/...", or a commit's id), and objects and refs folders, in the folder its commondir names for a linked worktree. Any other folder, an empty one say, is passed over and the walk goes on up. - A file counts when it is "gitdir: <folder>" naming such a folder, relative to the .git's own folder (a linked worktree's, a submodule's). Any other file, one over git's 1 MB, or one that is neither file nor folder is "no": git stops there with "not a git repository" (a worktree whose repository has gone) or "invalid gitfile format". (git 2.34 passed a .git that is neither file nor folder over; 2.55 and 2.56, CI's, stop at it.) - A .git it can't read is unknown, and the header is left off. git passes such a folder over and stops at such a file, but either way it can't tell an empty .git from a repository it isn't let into (another user's, through a shared magpie), and a failed read is unknown here. A bare repository kept as a folder's .git (git init --bare .git) is still "yes": git finds one there, though no work tree. Not mirrored: the filesystem boundary, GIT_CEILING_DIRECTORIES and safe.directory's ownership check. Cost: the same one stat per folder on the way up; at a .git, a read of HEAD (255 bytes at most) and stats of commondir, objects and refs. What a user sees: a request to a plugin provider from an agent that doesn't say whether its folder is a repository (Codex, Pi) was told "yes" for a project under a stray empty .git, under a worktree whose repository was deleted, or under a .git file that names nothing. The community ZCode plugin then tells the model "- <git label>: yes" and Command Code's sends isGitRepo: true, so the model may run git commands that fail with "not a git repository". They are now told "no", and with a .git on the way magpie can't read, nothing (ZCode's plugin leaves the line out, Command Code's sends false). Claude Code's and OpenCode's requests say it themselves and are passed on as they say it, so nothing changes for them; Claude Code 2.1.310's own check takes any .git, an empty one too. The only caller of GitOnDisk is tellWorkPlace (workdir.go), which needs no change. The library's skill groups had the same first-.git walk: gitRepoOf took the first .git within four folders of a linked skill for its checkout, so an empty one between a skill and its clone left the skill in no group, and gave one imported from there no From. gitRepoOf now asks provider.GitAt, passes such a .git over to the clone's, and reads the origin from the folder GitAt names (a linked worktree's common one), which replaces gitdirConfig. gitdirConfig also took "gitdir:" with no space after it, or with spaces around the line, which git doesn't take; such a .git now traces to nothing, as git finds nothing there. Checkouts git made are traced as before; the test's fake ones had only a config and now have a HEAD, objects and refs. Every other .git folder in the Go code is one a walk skips when it copies, hashes or checks a skill (carry.go, skillcheck.go, skills.go, skill_edits.go), or the one magpie removes from its own fetch of a skill (skillgit.go), not a decision about a repository. The Claude bridge's claudeWorkDir takes the temp folder for one in no repository; Claude Code decides that for itself, and its git status is off for every run (CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS), so it stays. TestPluginToldWhereTheAgentWorks gets a real repository for "in a repository" (HEAD, objects, refs; an empty .git was all it had) and a case under an empty .git in its own temp folder, so it fails without this on any machine. Its "not in one" cases, and the new provider tests' "no" ones, still need no repository above the temp folder, as the test did before. TestGitOnDiskIsWhatGitFinds lays out each kind of .git by hand; TestGitOnDiskAgreesWithGit asks git rev-parse --git-common-dir in each of those folders and in ones git made (init, worktree add, a worktree whose record was removed, --separate-git-dir, init --bare .git), for yes or no and where; TestGitOnDiskUnreadIsUnknown locks a .git folder and a worktree's .git file. provider-plugins.md and library.md say the same. What was run (tree 9a4504d9, on origin/main56602426, go1.26.8, linux/amd64, Linux 5.15), outside graftcp, umask 077, git 2.34.1, with the box's empty /tmp/.git above the tests' temp folders: - TestPluginToldWhereTheAgentWorks -count=5, Bun 1.4.2: 5 of 5 ok. TestGitOnDisk* and TestSkillRepo*, -count=3: 15 of 15 ok. The same and TestPluginToldWhereTheAgentWorks, -race -count=2: 12 of 12, no race. internal/library and internal/provider whole: ok. - 56602426's workplace.go and skill_from.go put back under the new tests: TestPluginToldWhereTheAgentWorks red 5 of 5, at plugin_workdir_test.go:125 both "not in one" and "not in one, under an empty .git": the plugin was told git "yes", want "no"; TestSkillRepoTraced red, "write-a-prd: repo "", want "mattpocock/skills"". - gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go vet for windows, go build -tags nogui for linux and darwin and go build for windows: exit 0 each. go vet and go build without the tag on linux: exit 1 (no libsoup-3.0 or gio-unix-2.0 here). - go test -tags nogui -count=1 -timeout 45m ./... (Bun 1.4.2, log kept; 8m37s, load 32 at its start): 73 packages ok, and 14 tests red in 4 packages, none of them this commit's tests or what they cover. internal/gateway ran to its end (504s), so TestPluginToldWhereTheAgentWorks passed in it; internal/library and internal/provider ok. The reds: agent TestCodexDriftReached and TestCodexBehindReverseProxy (#3398); TestInstalledVersion, TestCursorFolderFromTheEditorIsNotTheCLI, TestCopilotFolderFromAnIDEPluginIsNotTheCLI, TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir and TestZedAppPath (#3141); TestReasonixCLIRequiresSupportedNativeVersion and TestReasonixCLIRecoversAfterProbeTimeout (#3641: go build's own VCS stamping meets the same /tmp/.git, which this doesn't change); edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask 077, #3640); gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie (#3649). This commit is 595b361c rebased: the same internal/ patch-id, and the same row in docs/subsystems/library.md, put in by git's 3-way merge, as main's33ccc618(#2794) rewrote the Skills row, a line of its context three rows above. The rest is what was run for 595b361c, at tree d56bed31 on origin/main098ac969, the same code (not this tree): - main's GitOnDisk and gitRepoOf under the new tests (098ac969's workplace.go and skill_from.go put back): TestPluginToldWhereTheAgentWorks -count=5, Bun 1.4.2: red 5 of 5, "not in one" and "not in one, under an empty .git" told git "yes". With TMPDIR=/var/tmp/3675-clean, no .git above it: red 5 of 5 on the new case alone. TestSkillRepoTraced: red, write-a-prd: repo "", want "mattpocock/skills". - Broken by hand, one at a time in workplace.go, each red in the GitOnDisk tests on what it breaks, and green again restored: any .git folder taken, main's rule for folders: "yes" under an empty .git, a zeroed HEAD and a HEAD alone, and for a locked .git a gitfile naming no repository, or not a gitfile, walked past: "yes" from the repository above it HEAD's content not read: "yes" for the zeroed HEAD; objects and refs not looked for: "yes" for a HEAD alone a HEAD at a commit not taken, or commondir not read: "no" for both linked worktrees; a worktree's own folder named, not its common one: the repository at .../worktrees/wt where git finds .../.git a HEAD linked into refs/ refused: "no"; a relative gitdir read from magpie's folder: "no" for the submodule; no 1 MB cap: "yes" ENOTDIR taken for a failed read: unknown for a gitfile naming a file; a .git it can't read walked past: "no" for both locked ones Not tried: CI's git 2.55.0 (ubuntu) and 2.56.0 (macOS, Windows) under TestGitOnDiskAgreesWithGit, which met git 2.34.1 alone; macOS and Windows at all (Windows CI only compiles the tests); a real ZCode or Command Code plugin end to end; a shared magpie told another user's folder; the Library page itself. Landed by yetone in a batch of Coffemon's patches from the issues. What was run, go1.26.8, on origin/maincc81ad4ea, then again at70a0c387c(gofmt, the three vets, the changed tests, umask 077): - mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask 077; agent, provider, library and gateway with an empty .git above TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the changed tests in agent, provider, gateway and gui; the timing tests -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok. TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js 1,312,975 of 1,315,316, no budget raised. - Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink at umask 077 and two Reasonix tests under an empty .git; on Linux (wsl-run) TestProgram at umask 077 with the old program.go. With each fix's code taken back to main's, the Gemini imageConfig tests, TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced, TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto, plugin-github-hooks, plugins-more-discover, plugin-namesake were red. Broken by hand: claudeKeyed always true (both OwnEndpointNeverAsked tests red), claudeAsk a no-op (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder (the three TestGitOnDisk tests red). - GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n, gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on Linux (wsl-run). 11 files had reds (click-scroll, panel-fold, plugin-card-update, plugin-github, plugin-move*, segs-glide, tray-totals, update-*), and run again side by side they fail the same on origin/maind80d75f30(79 pass, 26 fail here; 78 and 27 there). They are click-scroll guards ("the click must not scroll the page"), varying by language from run to run (#4385). copilot-ghe's route-after-close red is #1949, seen on main244d80e23too. In Chromium on mote, Chromium segfaulted partway through files (#4125): context-map, context-scroll-end and context-tune fail the same on origin/main0911a65e7, so the batch's own files (plugin-namesake, update-auto, plugins-more-discover, plugin-github-hooks) ran in Chromium on Linux: 62 of 62. - Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote) at 472a0608f (on70a0c387c): every package ok but internal/gateway, whose five reds were #4362's (Antigravity turned-away and TestCodexSpentGrokFailingIsTold), fixed on main ind80d75f30. After the rebase on244d80e23the five pass, and gofmt, the three vets and the targeted runs above were run again: ok. In Linux the sign-in, copilot, plugin-github*, plugins-more-discover, plugin-namesake, plugin-gateway, update-auto, quota-refresh-order and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe #1949, plugin-github's click scroll, both red on main too). - Rebased again onc7171a256, over its budget fixe94bf7a08: gofmt, vet of gui, gateway, provider and plugin, TestCoreScriptBudget (core 1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini, GitOnDisk and plugin tests, and in Linux both engines i18n-keys, update-mirror, plugin-namesake, plugins-more-discover, plugin-github-hooks and update-auto (138 of 138): ok. Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its Chromium segfaulted, #4125); macOS WebKit; the real app's window.
151 lines
6.2 KiB
Go
151 lines
6.2 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
// A plugin's fetch is told the folder the agent works in, as the agent says
|
|
// it in its request, and whether it is a git repository, so a plugin that
|
|
// tells its vendor the user's environment says the agent's and not
|
|
// magpie's own (magpie-community/plugins#86: ZCode's Start Plan said
|
|
// magpie's ~/.config/magpie as the working directory, and the model went
|
|
// looking there). The headers reach the plugin and never the vendor; a
|
|
// request that says no folder has neither.
|
|
func TestPluginToldWhereTheAgentWorks(t *testing.T) {
|
|
var mu sync.Mutex
|
|
var got []http.Header
|
|
pid := besideFake(t, "fakeco", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
io.Copy(io.Discard, r.Body)
|
|
mu.Lock()
|
|
got = append(got, r.Header.Clone())
|
|
mu.Unlock()
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
if r.URL.Path == "/v1/messages" {
|
|
for _, e := range []string{
|
|
`{"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"fake-claude","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`,
|
|
`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
|
|
`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}`,
|
|
`{"type":"content_block_stop","index":0}`,
|
|
`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`,
|
|
`{"type":"message_stop"}`,
|
|
} {
|
|
io.WriteString(w, "data: "+e+"\n\n")
|
|
}
|
|
return
|
|
}
|
|
io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"hi"},"finish_reason":null}]}`+"\n\n")
|
|
io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
|
|
}))
|
|
// the agent's own request, sent unstreamed to the model named
|
|
asAgent := func(file, model string) string {
|
|
var b map[string]any
|
|
if err := json.Unmarshal(fixture(t, file), &b); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
b["model"], b["stream"] = pid+"/"+model, false
|
|
out, _ := json.Marshal(b)
|
|
return string(out)
|
|
}
|
|
// a repository as git init lays one out, what git looks for in it
|
|
repo := filepath.Join(t.TempDir(), "My Repo 中文")
|
|
for _, d := range []string{"objects", "refs/heads"} {
|
|
if err := os.MkdirAll(filepath.Join(repo, ".git", d), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if err := os.WriteFile(filepath.Join(repo, ".git", "HEAD"), []byte("ref: refs/heads/main\n"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
inRepo := filepath.Join(repo, "sub")
|
|
if err := os.MkdirAll(inRepo, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
plain := t.TempDir()
|
|
// under an empty .git, which git passes over (#3675)
|
|
underEmpty := filepath.Join(t.TempDir(), "sub")
|
|
if err := os.MkdirAll(filepath.Join(filepath.Dir(underEmpty), ".git"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.MkdirAll(underEmpty, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
piAsks := func(dir string) string {
|
|
b, _ := json.Marshal(map[string]any{"model": pid + "/fake-1", "messages": []map[string]any{
|
|
{"role": "system", "content": "You are pi.\n<cwd>\n" + filepath.ToSlash(dir) + "\n</cwd>"},
|
|
{"role": "user", "content": "hi"},
|
|
}})
|
|
return string(b)
|
|
}
|
|
for _, tc := range []struct {
|
|
name, path, body string
|
|
dir, git string // "" for not told
|
|
}{
|
|
// Claude Code says its folder and that it isn't a git repository;
|
|
// to a model on Anthropic Messages and to one on Chat
|
|
{"claude code, messages", "/v1/messages", asAgent("claude-code-2.1.296.json", "fake-claude"), "/Users/me/work/proj/a&b <c> 中文", "no"},
|
|
{"claude code, chat", "/v1/messages", asAgent("claude-code-2.1.296.json", "fake-1"), "/Users/me/work/proj/a&b <c> 中文", "no"},
|
|
// Codex says its folder only; not a folder on this computer, so
|
|
// whether it is a git repository isn't known
|
|
{"codex", "/v1/responses", asAgent("codex-0.162.0.json", "fake-1"), "/Users/me/work/proj/a&b <c> 中文", ""},
|
|
// a folder here: looked at on disk, the repository above it too
|
|
{"in a repository", "/v1/chat/completions", piAsks(inRepo), filepath.ToSlash(inRepo), "yes"},
|
|
{"not in one", "/v1/chat/completions", piAsks(plain), filepath.ToSlash(plain), "no"},
|
|
{"not in one, under an empty .git", "/v1/chat/completions", piAsks(underEmpty), filepath.ToSlash(underEmpty), "no"},
|
|
{"no folder said", "/v1/chat/completions", `{"model":"` + pid + `/fake-1","messages":[{"role":"user","content":"hi"}]}`, "", ""},
|
|
} {
|
|
mu.Lock()
|
|
got = nil
|
|
mu.Unlock()
|
|
rt := postProto(t, New(), tc.path, tc.body)
|
|
mu.Lock()
|
|
sent := slices.Clone(got)
|
|
mu.Unlock()
|
|
// the requests this case is about are its tries: one, or more when
|
|
// a try failed and the lone account was asked again after a moment
|
|
// (TestLastOneLeftIsTriedAgain), each told the same. A request with
|
|
// no try of its own would be a duplicate, and fails (#3347)
|
|
for _, x := range rt.Tries[:max(len(rt.Tries)-1, 0)] {
|
|
if x.Status == http.StatusOK {
|
|
t.Fatalf("%s: a try that answered was tried again: %+v", tc.name, rt.Tries)
|
|
}
|
|
t.Logf("%s: tried again after %d %s", tc.name, x.Status, x.Error)
|
|
}
|
|
if len(sent) == 0 || len(sent) > len(rt.Tries) {
|
|
t.Fatalf("%s: the vendor got %d requests in %d tries: %+v", tc.name, len(sent), len(rt.Tries), rt.Tries)
|
|
}
|
|
for _, h := range sent {
|
|
sawWorkPlace(t, tc.name, h, tc.dir, tc.git)
|
|
}
|
|
}
|
|
}
|
|
|
|
// sawWorkPlace checks what one request told the plugin (X-Saw-Work-*, as
|
|
// the fake plugin echoes it) and that none of it reached the vendor.
|
|
func sawWorkPlace(t *testing.T, name string, h http.Header, wantDir, wantGit string) {
|
|
t.Helper()
|
|
for _, k := range []string{"X-Magpie-Work-Dir", "X-Magpie-Work-Git"} {
|
|
if v := h.Values(k); len(v) > 0 {
|
|
t.Errorf("%s: the vendor got %s: %q", name, k, v)
|
|
}
|
|
}
|
|
dir := h.Get("X-Saw-Work-Dir")
|
|
if dir != "" {
|
|
d, err := url.PathUnescape(dir)
|
|
if err != nil {
|
|
t.Fatalf("%s: %q isn't percent-encoded: %v", name, dir, err)
|
|
}
|
|
dir = d
|
|
}
|
|
if dir != wantDir || h.Get("X-Saw-Work-Git") != wantGit {
|
|
t.Errorf("%s: the plugin was told %q, git %q; want %q, %q", name, dir, h.Get("X-Saw-Work-Git"), wantDir, wantGit)
|
|
}
|
|
}
|