diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 056a5f989..4cd9c81b3 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -146,6 +146,7 @@ something else shows up as drift. - PenguinHarness's file is `$PENGUIN_HOME` (else `~/.penguin/data`, on Windows too) `//.project_config.toml`, the Project `$PENGUIN_PROJECT_ID` when it is a folder's name (`agentenv.NotPaths`, so a relative name isn't dropped as a path), else `default_project`; a WSL distro's is its `~/.penguin/data/default_project` ([`penguin.go`](../../internal/agent/penguin.go)). Magpie's models are `[[models]]` array entries with `provider = "magpie"`, replaced together where the first one was by `edit.SetTOMLArrayTables`, which leaves the user's entries, the blank lines between them and the file's time alone when nothing changed (Penguin's server reads the file again on every mtime change). `default_model` is spelled `{ provider = …, model_id = … }` as Penguin's own writer (smol-toml) spells it; that writer rewrites the whole file, so Disconnect takes out magpie's provider, entries and a vision model on them rather than putting back a copy. A default naming no entry is refused by Penguin, so entries go in before `default_model` and out after it. PenguinHarness's desktop app (`PenguinHarness.app`, bundle id `com.prismshadow.penguinharness`; on Windows `PenguinHarness\PenguinHarness.exe` under `%LOCALAPPDATA%\Programs` or the folder its installer registered, `desktopApps`) runs its server on the same root and needs no CLI, so with it installed the agent is detected before the app is first opened (`sign`) and never shown as gone; Connect then writes `default_project`, which the app's server adopts without overwriting (rankyurky_80676 on Discord, `TestPenguinDesktopAppDetected`, `TestPenguinDesktopOnlyConnects`). - CodeBuddy is one row for the CodeBuddy Code CLI and the CodeBuddy IDE (Tencent's VS Code fork; 4.12.2's `CodeBuddy.app`, `com.tencent.codebuddy`, from codebuddy.ai, and `CodeBuddy CN.app`, `com.tencent.codebuddycn`, from codebuddy.cn; both are `desktopApps["codebuddy"]`, the second as one of its `more` builds) ([`codebuddy.go`](../../internal/agent/codebuddy.go)). The IDE's genie extension (`CustomModelsProductProvider`, with `CustomModelsJSON` on in its `product.json`) reads `/.codebuddy/models.json`, the file magpie writes for the CLI, skips an entry without a string `id` and `url`, takes `availableModels` as a whitelist when it has one, and lists each model in its own picker; it ignores `$CODEBUDDY_CONFIG_DIR` and settings.json's `model`. With only the IDE installed the row is detected (`sign`), shows the IDE's version and is never "CLI not found" (bjzhangwn on X; `TestCodeBuddyIDEIsCodeBuddy`, `TestCodeBuddyIDEReadsMagpieModels`). The IDE's Windows and Linux install folders aren't known, so there it is found by `~/.codebuddy` alone (never gone on Windows, as every `desktopApps` agent). - Zoo Code's provider profiles are in VS Code's secret storage, so magpie writes a settings file for it (`magpie-import.json` in Zoo Code's `globalStorage/zoocodeorganization.zoo-code/settings`, not magpie's folder, so a sync keeps an address the user moved it to) and points Zoo Code's `zoo-code.autoImportSettingsPath` at it in VS Code's `settings.json` and each profile's, a user's own path stashed and put back ([`zoocode.go`](../../internal/agent/zoocode.go)). Zoo Code imports it on each start (`importSettingsFromPath`), merging it over the user's profiles and making `magpie` the current one. Disconnect stops the import and deletes the file; the profile already imported stays in Zoo Code, where magpie can't reach it. +- VS Code's, Insiders' and VSCodium's User and extensions folders come from one build (`vscodeDirs` in [`vscode.go`](../../internal/agent/vscode.go)), so its chat models, profiles, Disconnect and Zoo Code (which keeps its settings in that User folder and is found by its extension there) all use the same place. A portable build keeps both in its data folder, `user-data/User` and `extensions`, and is told as VS Code's own `configurePortable` (`src/bootstrap-node.ts`) tells it: its `product.json` has no `target` (an installer's build has one), and its data folder exists, `data` beside the program on Windows and Linux (`/data`, also for a build that updates into `/`), or on a Mac `product.json`'s `portable`, else `-portable-data`, beside the `.app` (`vscodePortableAt`). The build is the one the launcher on PATH is, through a Scoop shim and every symlink (`/usr/local/bin/code` into `/Applications/Code/Visual Studio Code.app`, #4151, faketrader; Scoop's `current` junction, #3260, #4009); a launcher whose `product.json` names another editor (a fork's `code`) is not the build's. A Mac with no launcher of the build's reads the app folders and Spotlight, and takes a portable bundle only when every bundle found is that one; beside an installed one, which the user runs is unknown and nothing moves. An installed build keeps the OS's folder (`~/Library/Application Support/Code/User`, `%APPDATA%\Code\User`, `$XDG_CONFIG_HOME/Code/User`) and `~/.vscode/extensions`. `VSCODE_PORTABLE` is not read: it is the editor's environment, not magpie's. A group an older magpie wrote in the OS's folder for a portable build stays there; connecting again writes the portable one. Disconnect's preview is refused for a file in a portable data folder: its process keeps the PATH, whose launcher would find the build's own files, not the copy (`TestVSCodeMacPortable*`, `TestVSCodePortableUserDir`, `TestVSCodePortableScoopShim`, `TestVSCodePortableProduct`). - An agent is detected by its config file, its folder, or its command on magpie's PATH (`Detected`). That PATH is the login shell's plus the folders users' tools go in (`proc.UserPath`: `~/.local/bin`, npm's prefixes, the Node nvm's default alias resolves to (the highest installed when it names none), bun, Homebrew, ...; on Windows the registry's PATH plus the Node fnm's default alias names, `%APPDATA%\fnm\aliases\default` or under `FNM_DIR`, which fnm puts on a terminal's PATH from the shell profile and never in the registry, #2685), so a CLI a terminal doesn't find can still be found and listed: an npm install under a Node the terminal no longer uses. `/api/agents/cli` then gives where it is (`path`) and `offPath` when the login shell's PATH (`proc.LoginPath`) lacks its folder, and the Agents row says "Not on your terminal's PATH", its tip naming the file (悠悠哥 on Discord: Codex 0.162.1 listed with no codex on PATH and no `~/.codex`). An unknown login PATH says nothing. A folder another tool writes too doesn't count (`dirShared`): Pi's for omp, `~/.copilot` for the Copilot CLI, which GitHub Copilot's JetBrains and VS Code plugins also write, and Qoder's and Qoder CN's, which Qoder's JetBrains plugin fills, and `~/.cursor` for Cursor CLI, which the Cursor editor makes on its own (`TestCursorFolderFromTheEditorIsNotTheCLI`, @G_Z_Y on X); only `cli-config.json` or `cursor-agent` finds Cursor CLI. A command another app ships under the agent's name doesn't count either: VS Code forks put a `code` launcher in their own bin folder (Cursor; Qoder IDE beside `qoder`), which their Windows installers put on PATH, so a `code`, `code-insiders` or `codium` counts as VS Code, Insiders or VSCodium only when the `product.json` beside it names that build (`applicationName`), or names none (`vscodeCodeBinary`; ggbr on Discord: Qoder IDE listed as VS Code too, `TestVSCodeDetected`, `TestVSCodeBuildLauncher`). A config file another tool writes first counts only when `pathOwn` says it is the agent's: Qoder's `settings.json` holding `enabledPlugins` alone is the plugin's (`qoderPluginOnly`; #1495, `TestCopilotFolderFromAnIDEPluginIsNotTheCLI`, `TestQoderSettingsFromAnIDEPluginIsNotTheCLI`). The Qoder app (the desktop app, which runs Qoder's CLI as its agent with the same folder) is found by the `.qoder-app-status.json` it writes there (`sign`, `qoderApp`; #2138, `TestQoderAppIsQoder`), as its `settings.json` can be its bundled plugin's `enabledPlugins` alone. Only the GUI and `daemon install` widen the PATH so; `magpie serve`, `web`, `tui` and the CLI keep the one they were started with, so an agent's CLI (`cliBin`, which its version and `omp`'s max effort are read from) is looked for in those folders (`proc.FindTool`) on every system when it isn't on the PATH, not only on Windows (whqtian on Discord: omp under `~/.bun/bin` on Ubuntu read as no version and offered xhigh in place of max; `TestOmpVersionOffPath`). - Detection goes by an agent's folder, which an uninstall leaves behind, so an agent found by that alone is shown as gone (`CLIMissing`; #843, #2177, #2173): its CLI is on no PATH and in none of `proc.FindTool`'s folders nor where its own installer puts it (`~/.claude/local`, `~/.codex/packages/standalone`, `~/.opencode/bin`, Hermes' `hermes-agent` checkout), and nothing else that reads the folder is here (`cliHeld`): its desktop app (`HasApp`), an editor's extension (`~/./extensions/-*`: `anthropic.claude-code`, `openai.chatgpt`, `saoudrizwan.claude-dev`), Claude.app, OpenCode.app and Goose.app on a Mac, a JetBrains IDE's settings (its AI Assistant's agents and Cline's plugin) or Zed's `external_agents` (its Claude Code and Codex adapters). Where magpie can't tell (every shared folder, `cliShared`, on Windows, whose readers can be a Store app, a portable editor or a PATH only a shell profile sets, #1482, and there too one a desktop app of the agent's reads, `desktopApps`: DeepSeek Harness Desktop installs to any folder and puts its `dsh.cmd` in one the user picks, #2300, #2304; OpenCode and Goose off a Mac, Gemini, an agent detected its own way or by a command name other tools share, one with no install command but `cliOnly`'s Hermes), it is never gone. A gone row in the GUI shows "CLI not found" and none of its settings, nor Apply again; while connected it keeps its switch and Disconnect, and it folds under Not set up once not. Get started never offers it (`connectKind` is "no"). The TUI leaves it out and `magpie ls` says "CLI not found" (`TestCLIMissing*`, `agent-cli-missing.test.cjs`, `getting-started.test.cjs`). - An agent's folder variable (`agentenv.Vars`: `PI_CODING_AGENT_DIR`, `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, …) is read through `appdir.LookupEnv`, never `os.Getenv`. On Windows one that came from the registry is read there again, at most once a second, as a process started now would get it (the user's value over the machine's, `%…%` expanded), and set in magpie's environment so what magpie starts gets it too ([`follow.go`](../../internal/appdir/follow.go)): Windows never passes a changed User variable to a running process, and a magpie in the tray kept writing Pi's files into the AgentDir the user had moved and deleted (bm_rabbit on Discord). A value the launcher set itself, unlike the registry's, or one set inside magpie since, stands. `edit`'s writes make the folder such a variable names when the folder above it is there, as mkdir would, but never a missing tree above it (`appdir.Gone`): bm_rabbit's whole F:\piData was gone, and such a write fails with a `GoneError` naming the variable. An agent's default folder is made as before. Writes that call `os.MkdirAll` themselves (the library's skills and hooks, some agents' own files) don't ask yet (#4634). @@ -155,6 +156,7 @@ something else shows up as drift. ## Verification ```sh +go test -tags nogui ./internal/agent -run 'TestVSCode|TestZooCode' go test -tags nogui ./internal/agent -run '^TestStepCode' go test -tags nogui ./internal/agent ./internal/update ./internal/cli -run 'TestAgy|TestShellFunction|TestWithFnBlock|TestShellProfiles' node --test internal/gui/tests/agy-launch.test.cjs diff --git a/internal/agent/preview.go b/internal/agent/preview.go index fa8edd1d1..6f2a20930 100644 --- a/internal/agent/preview.go +++ b/internal/agent/preview.go @@ -102,6 +102,12 @@ func DisconnectPreview(a *Agent, exe string) ([]FileChange, error) { if appdir.Portable() != "" { return nil, errors.New("no preview for a portable magpie") } + // A portable VS Code's folder is found through its launcher, on the + // PATH the preview's process keeps, not through home: that process + // would disconnect the build's own files, not the copy (#4151). + if vscodePortableFile(a.Path) { + return nil, errors.New("no preview for a portable VS Code") + } home, err := os.UserHomeDir() if err != nil { return nil, err diff --git a/internal/agent/vscode.go b/internal/agent/vscode.go index 1a64527b7..7a9a69b22 100644 --- a/internal/agent/vscode.go +++ b/internal/agent/vscode.go @@ -122,21 +122,27 @@ func vscodeInsidersAgent(home, cfg string) *Agent { return vscodeOf(vscodeInside func vscodium(home, cfg string) *Agent { return vscodeOf(vscodiumKind, home, cfg) } func vscodeOf(k vscodeKind, home, cfg string) *Agent { + dir, exts := vscodeDirs(k, home, cfg) if k.exts != "" { - k.extDir = filepath.Join(home, k.exts, "extensions") + k.extDir = exts } - return vscodeKindAt(k, vscodeUserDir(k, home, cfg)) + return vscodeKindAt(k, dir) } -// vscodeUserDir is the User folder of the VS Code k, where its settings.json -// is: its extensions' (Zoo Code's) settings too. A portable build's is in -// its data folder (vscodePortableUserDir); the OS's place is an installed -// build's. -func vscodeUserDir(k vscodeKind, home, cfg string) string { - if dir := vscodePortableUserDir(k); dir != "" { - return dir +// vscodeOS is the system whose VS Code layout is read; a var so a test can +// lay out a Mac's portable build on any machine. +var vscodeOS = runtime.GOOS + +// vscodeDirs are the User folder of the VS Code k, where its settings.json +// is (its extensions', Zoo Code's, too), and its extensions folder, both of +// the same build. A portable build keeps both in its data folder +// (vscodePortableData); an installed build's are the OS's place and the +// home folder's. +func vscodeDirs(k vscodeKind, home, cfg string) (user, exts string) { + if data := vscodePortableData(k); data != "" { + return filepath.Join(data, "user-data", "User"), filepath.Join(data, "extensions") } - switch runtime.GOOS { + switch vscodeOS { case "darwin": cfg = filepath.Join(home, "Library", "Application Support") case "windows": @@ -145,36 +151,154 @@ func vscodeUserDir(k vscodeKind, home, cfg string) string { cfg = filepath.Join(home, "AppData", "Roaming") } } - return filepath.Join(cfg, k.folder, "User") + return filepath.Join(cfg, k.folder, "User"), filepath.Join(home, k.extFolder(), "extensions") } -// vscodePortableUserDir is the User folder of a portable VS Code k: a build -// that keeps a data folder beside its program keeps its user data in -// data\user-data there, not in %APPDATA% — a zip's own data folder, and -// Scoop's, whose apps\vscode\current\data is the persisted one, current a -// junction into apps\vscode (#3260). "" for an installed build, whose -// launcher has no data folder beside it: as VS Code itself takes a build -// for portable by that folder alone. -func vscodePortableUserDir(k vscodeKind) string { - bin := binAt(k.bin) - if bin == "" { +// extFolder is the folder in home an installed build keeps its extensions +// in: .vscode, .vscode-insiders, .vscode-oss. +func (k vscodeKind) extFolder() string { + switch { + case k.exts != "": + return k.exts + case k.id == vscodeInsiders.id: + return ".vscode-insiders" + } + return ".vscode" +} + +// vscodeBundles are where a Mac keeps each build's app, by bundle id and +// name. +var vscodeBundles = map[string]desktopApp{ + vscodeStable.id: {id: "com.microsoft.VSCode", names: []string{"Visual Studio Code.app"}}, + vscodeInsiders.id: {id: "com.microsoft.VSCodeInsiders", names: []string{"Visual Studio Code - Insiders.app"}}, + vscodiumKind.id: {id: "com.vscodium", names: []string{"VSCodium.app"}}, +} + +// vscodePortableData is the data folder of a portable VS Code k, "" for an +// installed build. The build is the one k's launcher is, followed through +// a Scoop shim and every symlink (macOS: /usr/local/bin/code into +// /Applications/Code/Visual Studio Code.app, #4151; Windows: Scoop's +// current junction, #3260). On a Mac whose launcher isn't a build's, the +// app folders' and Spotlight's bundles are read, and taken only when every +// one found is the same portable build: a launcher, or no doubt, decides +// which of two installs the user runs. +func vscodePortableData(k vscodeKind) string { + if bin := binAt(k.bin); bin != "" { + if at := scoopShim(bin); at != "" { + bin = at + } + if resolved, err := filepath.EvalSymlinks(bin); err == nil { + bin = resolved + } + if appRoot, appPath := vscodeAppRoot(k, bin); appRoot != "" { + // a fork's launcher called code (Cursor's) is not k's + if data, ours := vscodePortableAt(k, appRoot, appPath); ours { + return data + } + } + } + app, ok := vscodeBundles[k.id] + if vscodeOS != "darwin" || !ok { return "" } - if at := scoopShim(bin); at != "" { - bin = at + found := "" + for _, bundle := range macBundles(app) { + if !isDir(bundle) { + continue + } + data, _ := vscodePortableAt(k, filepath.Join(bundle, "Contents", "Resources", "app"), bundle) + if data == "" || (found != "" && data != found) { + return "" + } + found = data } - if resolved, err := filepath.EvalSymlinks(bin); err == nil { - bin = resolved + return found +} + +// vscodePortableFile reports whether path is in a portable VS Code's data +// folder: VS Code's own files there, or Zoo Code's beside them. +func vscodePortableFile(path string) bool { + for _, k := range []vscodeKind{vscodeStable, vscodeInsiders, vscodiumKind} { + if data := vscodePortableData(k); data != "" { + if r, err := filepath.Rel(data, path); err == nil && r != ".." && !strings.HasPrefix(r, ".."+string(filepath.Separator)) { + return true + } + } } + return false +} + +// vscodeAppRoot is the app folder (resources/app, where product.json is) +// of the build whose launcher is bin, and the build's own folder (VS +// Code's getApplicationPath): .app/Contents/Resources/app/bin and the +// .app on a Mac; elsewhere /bin beside /resources/app, +// or //resources/app for a build that updates into a +// versioned folder (win32VersionedUpdate), and . "" for a +// launcher outside any build's bin folder. +func vscodeAppRoot(k vscodeKind, bin string) (appRoot, appPath string) { dir := filepath.Dir(bin) if !strings.EqualFold(filepath.Base(dir), "bin") { - return "" + return "", "" + } + if vscodeOS != "darwin" { + install := filepath.Dir(dir) + appRoot = filepath.Join(install, "resources", "app") + if _, err := os.Stat(filepath.Join(appRoot, "product.json")); err != nil { + if m, _ := filepath.Glob(filepath.Join(install, "*", "resources", "app", "product.json")); len(m) > 0 { + appRoot = filepath.Dir(m[len(m)-1]) + } + } + return appRoot, install + } + appRoot = filepath.Dir(dir) + bundle := filepath.Dir(filepath.Dir(filepath.Dir(appRoot))) + if filepath.Base(bin) != k.bin || !strings.HasSuffix(bundle, ".app") || + appRoot != filepath.Join(bundle, "Contents", "Resources", "app") { + return "", "" + } + return appRoot, bundle +} + +// vscodePortableAt is the data folder of the build at appRoot when it is +// portable, as VS Code's own configurePortable (src/bootstrap-node.ts) +// decides it: its product.json has no target (an installer's build has +// one) and its portable data folder exists. That folder is data beside the +// program on Windows and Linux; on a Mac it is beside the .app, named by +// product.json's portable, else -portable-data. A Mac +// build's product.json must be read, and name k, to name it; elsewhere one +// that can't be read leaves the data folder alone to decide. ours is false +// when product.json names another editor (a fork's launcher called code): +// the build is not k at all. +func vscodePortableAt(k vscodeKind, appRoot, appPath string) (data string, ours bool) { + var product struct { + ApplicationName string `json:"applicationName"` + Portable string `json:"portable"` + Target json.RawMessage `json:"target"` + } + b, err := os.ReadFile(filepath.Join(appRoot, "product.json")) + read := err == nil && json.Unmarshal(b, &product) == nil + if read && product.ApplicationName != "" && product.ApplicationName != k.bin { + return "", false + } + if read && product.Target != nil { + return "", true + } + if vscodeOS == "darwin" { + if !read || product.ApplicationName == "" { + return "", true + } + name := product.Portable + if name == "" { + name = product.ApplicationName + "-portable-data" + } + data = filepath.Join(filepath.Dir(appPath), name) + } else { + data = filepath.Join(appPath, "data") } - data := filepath.Join(filepath.Dir(dir), "data") if !isDir(data) { - return "" + return "", true } - return filepath.Join(data, "user-data", "User") + return data, true } // scoopShim is the launcher a Scoop shim stands for: the path = line of the diff --git a/internal/agent/vscode_portable_test.go b/internal/agent/vscode_portable_test.go index f5ff4183b..b057b039d 100644 --- a/internal/agent/vscode_portable_test.go +++ b/internal/agent/vscode_portable_test.go @@ -4,6 +4,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "testing" "github.com/tidwall/gjson" @@ -40,6 +41,11 @@ func portableVSCode(t *testing.T, home string, portable, shims bool) (user strin } writeAt(t, filepath.Join(binDir, "code.shim"), "path = "+filepath.Join(app, "bin", name)+"\n") } + // a Mac's VS Code is never laid out so (macPortableVSCode); this is + // Windows' and Linux's, read as Linux's on a Mac + if runtime.GOOS == "darwin" { + useVSCodeOS(t, "linux") + } if portable { if err := os.MkdirAll(filepath.Join(app, "data"), 0o755); err != nil { t.Fatal(err) @@ -53,7 +59,7 @@ func portableVSCode(t *testing.T, home string, portable, shims bool) (user strin // installedUserDir is the User folder of an installed VS Code, where the OS // puts it. func installedUserDir(home string) string { - switch runtime.GOOS { + switch vscodeOS { case "windows": return filepath.Join(os.Getenv("APPDATA"), "Code", "User") case "darwin": @@ -124,3 +130,302 @@ func TestVSCodePortableScoopShim(t *testing.T) { t.Fatalf("Scoop's portable VS Code reads %s, want %s", a.Dir, user) } } + +// useVSCodeOS reads VS Code's layout as goos's for the test. +func useVSCodeOS(t *testing.T, goos string) { + t.Helper() + was := vscodeOS + vscodeOS = goos + t.Cleanup(func() { vscodeOS = was }) +} + +// noMacApps is a Mac with no app in its app folders or Spotlight but those +// in apps. +func noMacApps(t *testing.T, apps ...string) { + t.Helper() + wasFolders, wasSpot := appFolders, spotlightApps + appFolders = func() []string { return apps } + spotlightApps = func(string) []string { return nil } + t.Cleanup(func() { appFolders, spotlightApps = wasFolders, wasSpot }) +} + +// macVSCodeApp lays a Mac's VS Code bundle out as the app is: its +// launcher at Contents/Resources/app/bin/ beside product.json. It +// returns the launcher. +func macVSCodeApp(t *testing.T, bundle, bin, product string) string { + t.Helper() + app := filepath.Join(bundle, "Contents", "Resources", "app") + writeAt(t, filepath.Join(app, "product.json"), product) + launcher := filepath.Join(app, "bin", bin) + writeAt(t, launcher, "#!/bin/sh\nexit 1\n") + if err := os.Chmod(launcher, 0o755); err != nil { + t.Fatal(err) + } + return launcher +} + +// macPortableVSCode is faketrader's Mac (#4151): /Applications/Code holding +// Visual Studio Code.app beside code-portable-data, and the code on PATH +// /usr/local/bin/code, a symlink into the bundle. All of it is under root, +// a folder with a space in its name, read as a Mac's on any machine. +func macPortableVSCode(t *testing.T, k vscodeKind, product, dataName string) (root, data string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("a Mac's symlinked launcher") + } + useVSCodeOS(t, "darwin") + noMacApps(t) + root = filepath.Join(t.TempDir(), "Macintosh HD") + if resolved, err := filepath.EvalSymlinks(filepath.Dir(root)); err == nil { + root = filepath.Join(resolved, "Macintosh HD") + } + name := "Visual Studio Code.app" + if k.id == vscodeInsiders.id { + name = "Visual Studio Code - Insiders.app" + } + bundle := filepath.Join(root, "Applications", "Code", name) + launcher := macVSCodeApp(t, bundle, k.bin, product) + if dataName != "" { + data = filepath.Join(root, "Applications", "Code", dataName) + mkdirT(t, data) + } + path := filepath.Join(root, "usr", "local", "bin") + mkdirT(t, path) + if err := os.Symlink(launcher, filepath.Join(path, k.bin)); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", path) + return root, data +} + +// VS Code's configurePortable (src/bootstrap-node.ts) on a Mac: a build +// with no target in its product.json is portable when the folder its +// product.json's portable names, else -portable-data, +// is beside the .app. Its User folder is user-data/User there, and its +// extensions extensions; else the User folder is Application Support's. +func TestVSCodeMacPortableDirs(t *testing.T) { + for _, tt := range []struct { + name, product, data string + kind vscodeKind + portable bool + }{ + {"stable", `{"applicationName":"code","nameShort":"Code"}`, "code-portable-data", vscodeStable, true}, + {"insiders", `{"applicationName":"code-insiders"}`, "code-insiders-portable-data", vscodeInsiders, true}, + {"product's portable", `{"applicationName":"code","portable":"my data"}`, "my data", vscodeStable, true}, + {"no data folder", `{"applicationName":"code"}`, "", vscodeStable, false}, + {"Windows' name for it", `{"applicationName":"code"}`, "data", vscodeStable, false}, + {"another editor", `{"applicationName":"cursor"}`, "code-portable-data", vscodeStable, false}, + {"another channel's folder", `{"applicationName":"code-insiders"}`, "code-portable-data", vscodeInsiders, false}, + {"unreadable product", `{"applicationName":"code",`, "code-portable-data", vscodeStable, false}, + {"an installer's build", `{"applicationName":"code","target":"user"}`, "code-portable-data", vscodeStable, false}, + } { + t.Run(tt.name, func(t *testing.T) { + root, data := macPortableVSCode(t, tt.kind, tt.product, tt.data) + home := filepath.Join(root, "Users", "me") + user, exts := vscodeDirs(tt.kind, home, "unused") + wantUser := filepath.Join(home, "Library", "Application Support", tt.kind.folder, "User") + wantExts := filepath.Join(home, tt.kind.extFolder(), "extensions") + if tt.portable { + wantUser, wantExts = filepath.Join(data, "user-data", "User"), filepath.Join(data, "extensions") + } + if user != wantUser || exts != wantExts { + t.Fatalf("folders %q, %q, want %q, %q", user, exts, wantUser, wantExts) + } + if _, err := os.Stat(user); !os.IsNotExist(err) { + t.Fatalf("finding the User folder made it: %v", err) + } + }) + } +} + +// /usr/local/bin/code may be a symlink to a symlink (Homebrew's, a +// user's): each is followed to the bundle. +func TestVSCodeMacPortableLinkChain(t *testing.T) { + root, data := macPortableVSCode(t, vscodeStable, `{"applicationName":"code"}`, "code-portable-data") + path := filepath.Join(root, "usr", "local", "bin") + other := filepath.Join(root, "opt", "homebrew bin") + mkdirT(t, other) + if err := os.Rename(filepath.Join(path, "code"), filepath.Join(other, "code")); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(other, "code"), filepath.Join(path, "code-link")); err != nil { + t.Fatal(err) + } + if err := os.Symlink("code-link", filepath.Join(path, "code")); err != nil { + t.Fatal(err) + } + if user, _ := vscodeDirs(vscodeStable, filepath.Join(root, "home"), "unused"); user != filepath.Join(data, "user-data", "User") { + t.Fatalf("through three links the User folder is %q", user) + } +} + +// The reporter's case end to end: connecting, a profile's sync and +// disconnecting all write the portable build's files, Application +// Support's are left as they were, Zoo Code reads the same User folder +// and extensions, and no preview runs a process that would find the +// build's own files through the launcher on PATH. +func TestVSCodeMacPortableWiring(t *testing.T) { + home := syncHome(t) + _, data := macPortableVSCode(t, vscodeStable, `{"applicationName":"code"}`, "code-portable-data") + dir := filepath.Join(data, "user-data", "User") + settings := filepath.Join(dir, "settings.json") + writeFile(t, settings, `{"chat.defaultModel":"auto","editor.fontSize":17}`) + profile := filepath.Join(dir, "profiles", "work") + writeFile(t, filepath.Join(profile, "settings.json"), `{"chat.defaultModel":"auto"}`) + writeFile(t, filepath.Join(dir, "globalStorage", "storage.json"), `{"userDataProfiles":[{"location":"work"}]}`) + standard := filepath.Join(home, "Library", "Application Support", "Code", "User", "settings.json") + writeFile(t, standard, `{"editor.fontSize":99}`) + a := vscode(home, "unused") + if a.Path != settings || !a.Detected() { + t.Fatalf("VS Code at %q, detected %v", a.Path, a.Detected()) + } + if err := a.Connect(); err != nil { + t.Fatal(err) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + for _, at := range []string{dir, profile} { + if _, ok := edit.GetJSONItem(filepath.Join(at, "chatLanguageModels.json"), vscodeGroup); !ok { + t.Errorf("no magpie group in %s", at) + } + } + if _, err := DisconnectPreview(a, "no-such-magpie"); err == nil || !strings.Contains(err.Error(), "portable VS Code") { + t.Fatalf("a preview of the portable build: %v", err) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + for _, at := range []string{dir, profile} { + if v, _ := edit.GetJSON(filepath.Join(at, "settings.json"), vscodeDefault); v != "auto" { + t.Errorf("%s's default model %q, want auto back", at, v) + } + if _, ok := edit.GetJSONItem(filepath.Join(at, "chatLanguageModels.json"), vscodeGroup); ok { + t.Errorf("magpie's group kept in %s", at) + } + } + if got := readFile(standard); got != `{"editor.fontSize":99}` { + t.Fatalf("Application Support's settings changed: %s", got) + } + if _, err := os.Stat(filepath.Join(filepath.Dir(standard), "chatLanguageModels.json")); !os.IsNotExist(err) { + t.Fatalf("Application Support got a chatLanguageModels.json: %v", err) + } + writeFile(t, filepath.Join(data, "extensions", zooExtension+"-3.90.0", "package.json"), `{"name":"zoo-code","version":"3.90.0"}`) + zoo := zooCode(home, "unused") + if zoo.Path != settings || !zoo.Detected() { + t.Fatalf("Zoo Code at %q, detected %v", zoo.Path, zoo.Detected()) + } + if _, err := DisconnectPreview(zoo, "no-such-magpie"); err == nil || !strings.Contains(err.Error(), "portable VS Code") { + t.Fatalf("a preview of Zoo Code in the portable build: %v", err) + } +} + +// With no launcher on PATH, the Mac's app folders say: a portable bundle +// one folder down (/Applications/Code) is found, and when another +// install is there too, which the user runs is unknown, so nothing moves. +func TestVSCodeMacPortableWithoutLauncher(t *testing.T) { + root, data := macPortableVSCode(t, vscodeStable, `{"applicationName":"code"}`, "code-portable-data") + home := filepath.Join(root, "home") + t.Setenv("PATH", t.TempDir()) + apps := filepath.Join(root, "Applications") + noMacApps(t, apps) + if user, _ := vscodeDirs(vscodeStable, home, "unused"); user != filepath.Join(data, "user-data", "User") { + t.Fatalf("a portable bundle without a launcher: %q", user) + } + macVSCodeApp(t, filepath.Join(apps, "Visual Studio Code.app"), "code", `{"applicationName":"code"}`) + want := filepath.Join(home, "Library", "Application Support", "Code", "User") + if user, _ := vscodeDirs(vscodeStable, home, "unused"); user != want { + t.Fatalf("beside an installed bundle, with no launcher to tell them apart: %q", user) + } +} + +// The launcher picks the install: one into an installed bundle keeps +// Application Support's folder though a portable copy is in the app +// folders, and Insiders' portable build doesn't move Stable's. +func TestVSCodeMacPortableLauncherPicks(t *testing.T) { + root, _ := macPortableVSCode(t, vscodeStable, `{"applicationName":"code"}`, "") + home := filepath.Join(root, "home") + apps := filepath.Join(root, "Other Apps") + macVSCodeApp(t, filepath.Join(apps, "Portable", "Visual Studio Code.app"), "code", `{"applicationName":"code"}`) + mkdirT(t, filepath.Join(apps, "Portable", "code-portable-data")) + macVSCodeApp(t, filepath.Join(apps, "Visual Studio Code - Insiders.app"), "code-insiders", `{"applicationName":"code-insiders"}`) + mkdirT(t, filepath.Join(apps, "code-insiders-portable-data")) + noMacApps(t, apps) + if user, _ := vscodeDirs(vscodeStable, home, "unused"); user != filepath.Join(home, "Library", "Application Support", "Code", "User") { + t.Fatalf("another portable copy took the launcher's install: %q", user) + } + if user, _ := vscodeDirs(vscodeInsiders, home, "unused"); user != filepath.Join(apps, "code-insiders-portable-data", "user-data", "User") { + t.Fatalf("Insiders' portable bundle: %q", user) + } +} + +// A fork's bin has a launcher named code too (Cursor's); one on PATH is +// not VS Code's, so VS Code's own bundle is still looked for. +func TestVSCodeMacPortableForkLauncher(t *testing.T) { + root, _ := macPortableVSCode(t, vscodeStable, `{"applicationName":"code"}`, "") + home := filepath.Join(root, "home") + path := filepath.Join(root, "fork bin") + mkdirT(t, path) + fork := macVSCodeApp(t, filepath.Join(root, "Applications", "Cursor.app"), "code", `{"applicationName":"cursor"}`) + if err := os.Symlink(fork, filepath.Join(path, "code")); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", path) + apps := filepath.Join(root, "Applications") + noMacApps(t, apps) + mkdirT(t, filepath.Join(apps, "Code", "code-portable-data")) + if user, _ := vscodeDirs(vscodeStable, home, "unused"); user != filepath.Join(apps, "Code", "code-portable-data", "user-data", "User") { + t.Fatalf("past Cursor's code, VS Code's portable bundle: %q", user) + } +} + +// Windows and Linux follow the same rule: an installer's build (target in +// its product.json) is never portable, nor is a fork whose bin has a code, +// and a portable build's extensions (Zoo Code's) are in its data folder. +func TestVSCodePortableProduct(t *testing.T) { + home, cfg := syncHome(t), os.Getenv("XDG_CONFIG_HOME") + if resolved, err := filepath.EvalSymlinks(home); err == nil { + home = resolved + } + user := portableVSCode(t, home, true, false) + app := filepath.Join(home, "Editor With Spaces") + data := filepath.Join(app, "data") + product := filepath.Join(app, "resources", "app", "product.json") + for _, tt := range []struct{ product, want string }{ + {`{"applicationName":"code"}`, user}, + {`{"applicationName":"code","target":"user"}`, installedUserDir(home)}, + {`{"applicationName":"cursor"}`, installedUserDir(home)}, + {`{"applicationName":`, user}, + } { + writeAt(t, product, tt.product) + if got, _ := vscodeDirs(vscodeStable, home, cfg); got != tt.want { + t.Errorf("with product.json %s the User folder is %q, want %q", tt.product, got, tt.want) + } + } + // an Insiders-style build that updates into / + // keeps its product.json there; the data folder is 's still + if err := os.Remove(product); err != nil { + t.Fatal(err) + } + versioned := filepath.Join(app, "4f2a1c9", "resources", "app", "product.json") + for _, tt := range []struct{ product, want string }{ + {`{"applicationName":"code","win32VersionedUpdate":true,"target":"user"}`, installedUserDir(home)}, + {`{"applicationName":"code","win32VersionedUpdate":true}`, user}, + } { + writeAt(t, versioned, tt.product) + if got, _ := vscodeDirs(vscodeStable, home, cfg); got != tt.want { + t.Errorf("with a versioned product.json %s the User folder is %q, want %q", tt.product, got, tt.want) + } + } + writeAt(t, product, `{"applicationName":"code"}`) + writeFile(t, filepath.Join(data, "extensions", zooExtension+"-3.90.0", "package.json"), `{"name":"zoo-code","version":"3.90.0"}`) + zoo := zooCode(home, cfg) + if zoo.Path != filepath.Join(user, "settings.json") || !zoo.Detected() { + t.Fatalf("Zoo Code at %q, detected %v", zoo.Path, zoo.Detected()) + } + // Scoop's data folder is under home, which a preview copies; the + // process it starts would still find the real one through PATH + if _, err := DisconnectPreview(vscode(home, cfg), "no-such-magpie"); err == nil || !strings.Contains(err.Error(), "portable VS Code") { + t.Fatalf("a preview of the portable build: %v", err) + } +} diff --git a/internal/agent/zoocode.go b/internal/agent/zoocode.go index f3de4f52f..71ae9c1db 100644 --- a/internal/agent/zoocode.go +++ b/internal/agent/zoocode.go @@ -58,7 +58,9 @@ const zooExtension = "zoocodeorganization.zoo-code" var noticeZoo = newNotice("Zoo Code reads magpie's profile when it starts — run Developer: Reload Window in VS Code to use this.") func zooCode(home, cfg string) *Agent { - return zooCodeAt(vscodeUserDir(vscodeStable, home, cfg), filepath.Join(home, ".vscode", "extensions")) + // VS Code's own User and extensions folders: a portable build's are + // both in its data folder + return zooCodeAt(vscodeDirs(vscodeStable, home, cfg)) } // zooCodeImportPath is the file magpie has Zoo Code import, in the VS Code