From d044f44d91a55d11ac81b060a47b6fdbcf364e34 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:04:11 +0800 Subject: [PATCH] feat(setup): inspect, refresh and remove five mcp-add-only clients (#10694) * feat(setup): give five mcp-add clients one client-table row Cline VS Code extension, Kiro, Mastra Code, Zed and Amp move from registration-only catalog entries to rows in the client table. rea mcp add projects those rows, so doctor, update and uninstall now inspect, refresh and remove what it wrote, and setup offers each client when detected. Refs #7181 * refactor(setup): keep FreeBuff's comment on its declaration The client helpers added for the folded mcp-add clients were inserted between FreeBuff's profile-directory comment and its declaration. Move them above it, and drop an import the folded locations no longer use. * test(setup): refresh an older mcp-add registration through setup Address review: seed each folded client with an older REA-owned package runner launcher, then check that doctor reports it stale, update selects it, setup plans and applies the update, and doctor then reads the current launcher. * fix(setup): register Amp in settings.jsonc when that is its settings file (#10717) Amp reads ~/.config/amp/settings.json or settings.jsonc. REA always used settings.json, creating a second file beside an existing settings.jsonc. Use settings.jsonc when it is the only file, and refuse when both exist because Amp does not document which one it reads. * feat(setup): manage Cline in VS Code Insiders, VSCodium, Cursor and Windsurf (#10729) * feat(setup): manage Cline in VS Code Insiders, VSCodium, Cursor and Windsurf The Cline extension keeps its MCP settings in the global storage of whichever editor runs it. REA resolved only VS Code's, so a Cline in another editor was never configured, inspected or cleaned. Add one client-table row per editor, resolved through the shared Code-OSS user data rule, and detected where that editor's Cline settings exist. * test(setup): cover VSCODE_PORTABLE for Cline's editor hosts Address review: VSCODE_PORTABLE moves only VS Code's own storage, so the other editors keep their settings path; and the older-release note now says which hosts mcp add could register before. * fix(setup): find a Linux Flatpak Zed's configuration (#10721) * fix(setup): find a Linux Flatpak Zed's configuration Zed's config_dir honors FLATPAK_XDG_CONFIG_HOME first, and a Flathub Zed reads ~/.var/app/dev.zed.Zed/config/zed inside its sandbox. REA always wrote ~/.config/zed, which that Zed never reads. Honor the override, use the sandbox folder when it is the only one, and refuse when both a native and a Flatpak configuration exist. * fix(setup): treat an XDG_CONFIG_HOME naming the Flatpak folder as one Zed folder * fix(setup): treat linked native and Flatpak Zed folders as one configuration * test(setup): expect doctor to report the Amp registration mcp add wrote --- .../references/connection-and-recovery.md | 4 +- .../references/connection-and-recovery.md | 4 +- docs/getting-started/client-configuration.md | 32 +++ docs/getting-started/installation.md | 83 ++++-- src/application/ClientConfigRoots.ts | 39 +-- .../ClientConfigurationDocument.ts | 2 - src/application/McpRegistrationCatalog.ts | 70 +---- src/application/McpRegistrationLocations.ts | 48 ---- src/application/SupportedClients.ts | 255 ++++++++++++++++- .../cli/packageRunnerRegistration.test.ts | 8 +- .../filesystem/clientLifecycle.test.ts | 9 + .../filesystem/mcpAddClientLifecycle.test.ts | 269 ++++++++++++++++++ tests/fixtures/clientEnvironment.ts | 1 + 13 files changed, 656 insertions(+), 168 deletions(-) create mode 100644 tests/boundary/filesystem/mcpAddClientLifecycle.test.ts diff --git a/.agents/skills/reverse-engineer-anything/references/connection-and-recovery.md b/.agents/skills/reverse-engineer-anything/references/connection-and-recovery.md index 232de1c167..f3a31b0214 100644 --- a/.agents/skills/reverse-engineer-anything/references/connection-and-recovery.md +++ b/.agents/skills/reverse-engineer-anything/references/connection-and-recovery.md @@ -160,7 +160,9 @@ Use the current supported client's ID: `claude_code`, `claude_desktop`, `codex`, `cursor`, `codebuddy`, `cline`, `gemini_cli`, `windsurf`, `devin`, `opencode`, `antigravity`, `copilot_cli`, `commandcode`, `qwen_code`, `kimi`, `vscode`, `trae`, `workbuddy`, `lm_studio`, `grok_build`, `omp`, `pi`, `hermes`, `qoder`, `droid`, -`zcode`, `dsh`, `freebuff`, or `grok_bot`. If unknown, inspect `doctor --json` before choosing a +`zcode`, `dsh`, `freebuff`, `cline_vscode`, `cline_vscode_insiders`, `cline_vscodium`, +`cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`, +or `grok_bot`. If unknown, inspect `doctor --json` before choosing a scope. `grok_bot` uses a chat registration step rather than local `mcp.json`. For unsupported clients, use manual stdio registration with the selected installation’s absolute runtime and entry script, or continue through the CLI. diff --git a/.cursor-plugin/skills/reverse-engineer-anything/references/connection-and-recovery.md b/.cursor-plugin/skills/reverse-engineer-anything/references/connection-and-recovery.md index 232de1c167..f3a31b0214 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/references/connection-and-recovery.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/references/connection-and-recovery.md @@ -160,7 +160,9 @@ Use the current supported client's ID: `claude_code`, `claude_desktop`, `codex`, `cursor`, `codebuddy`, `cline`, `gemini_cli`, `windsurf`, `devin`, `opencode`, `antigravity`, `copilot_cli`, `commandcode`, `qwen_code`, `kimi`, `vscode`, `trae`, `workbuddy`, `lm_studio`, `grok_build`, `omp`, `pi`, `hermes`, `qoder`, `droid`, -`zcode`, `dsh`, `freebuff`, or `grok_bot`. If unknown, inspect `doctor --json` before choosing a +`zcode`, `dsh`, `freebuff`, `cline_vscode`, `cline_vscode_insiders`, `cline_vscodium`, +`cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`, +or `grok_bot`. If unknown, inspect `doctor --json` before choosing a scope. `grok_bot` uses a chat registration step rather than local `mcp.json`. For unsupported clients, use manual stdio registration with the selected installation’s absolute runtime and entry script, or continue through the CLI. diff --git a/docs/getting-started/client-configuration.md b/docs/getting-started/client-configuration.md index bb05075eb3..cb172f5377 100644 --- a/docs/getting-started/client-configuration.md +++ b/docs/getting-started/client-configuration.md @@ -824,6 +824,38 @@ MCP settings for long native investigations. Setup, doctor's alignment report, foreign-registration refusal, and uninstall removal are covered by `tests/acceptance/setup/clineClientSetup.test.ts`. +## Cline VS Code extension, Kiro, Mastra Code, Zed and Amp + +Setup, doctor, update, uninstall and `rea mcp add` share one definition for each +of these clients. Setup offers a client when its directory exists. + +| Client | `--client` | User configuration | Server table | +| ----------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| Cline VS Code extension | `cline_vscode` | `/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json` | `mcpServers` | +| Kiro | `kiro` | `~/.kiro/settings/mcp.json`, shared by the IDE and CLI | `mcpServers` | +| Mastra Code | `mastracode` | `~/.mastracode/mcp.json` | `mcpServers` | +| Zed | `zed` | `~/.config/zed/settings.json` on macOS, `%APPDATA%\Zed\settings.json` on Windows, `$XDG_CONFIG_HOME/zed/settings.json` on Linux | `context_servers` | +| Amp | `amp` | `~/.config/amp/settings.json`, or `settings.jsonc` when that is the only one | `amp.mcpServers` | + +The Cline extension keeps a separate settings file in each editor that runs +it. `cline_vscode_insiders`, `cline_vscodium`, `cline_cursor` and +`cline_windsurf` manage the same file under that editor's user directory +(`Code - Insiders`, `VSCodium`, `Cursor` or `Windsurf` in place of `Code`), and +setup offers each where that editor's Cline settings folder exists. +`VSCODE_APPDATA` applies to all of them; `VSCODE_PORTABLE` only to VS Code. +`rea mcp add --agent cline` keeps add-mcp's meaning, VS Code. A same-named server in a Kiro, +Mastra Code, Zed or Amp project file overrides the user registration; doctor +reports the user file. Mastra Code keeps enabled state outside `mcp.json`, and +Amp's managed settings and `amp.mcpPermissions` can block a server; doctor +cannot observe either. When both Amp settings files exist, Amp does not +document which it reads, so REA refuses to choose; merge them into one file. +On Linux, `FLATPAK_XDG_CONFIG_HOME` selects Zed's folder as Zed itself does, +and a Flathub Zed's `~/.var/app/dev.zed.Zed/config/zed` is used when only that +folder exists; with both it and the native folder present, REA cannot tell which +Zed you use and refuses. Zed's comments and formatting are preserved. These +locations follow each client's documentation and source; no installed client +was run to verify loading. + ## WorkBuddy For [WorkBuddy](https://www.workbuddy.cn/docs/workbuddy/From-Beginner-to-Expert-Guide/Function-Description/MCP-Guide), setup writes `mcpServers.rea` into the diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 8a169e5bd4..5b0ae31674 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -682,36 +682,45 @@ readiness for one task instead of auditing every integration, see Setup can configure these clients for REA's local MCP server. Grok Bot uses a manual hosted connector; see [its configuration](client-configuration.md#other-client-settings). -| Client | `--client` value | -| ------------------ | ---------------- | -| Claude Code | `claude_code` | -| Claude Desktop | `claude_desktop` | -| Codex | `codex` | -| Cursor | `cursor` | -| CodeBuddy | `codebuddy` | -| Cline CLI | `cline` | -| Gemini CLI | `gemini_cli` | -| Windsurf | `windsurf` | -| Devin | `devin` | -| OpenCode | `opencode` | -| Antigravity | `antigravity` | -| GitHub Copilot CLI | `copilot_cli` | -| Command Code | `commandcode` | -| Qwen Code | `qwen_code` | -| Kimi Code | `kimi` | -| VS Code | `vscode` | -| Grok Build | `grok_build` | -| OMP | `omp` | -| Pi | `pi` | -| Hermes | `hermes` | -| Qoder | `qoder` | -| Factory Droid | `droid` | -| Trae | `trae` | -| WorkBuddy | `workbuddy` | -| LM Studio | `lm_studio` | -| ZCode | `zcode` | -| DeepSeek Harness | `dsh` | -| FreeBuff | `freebuff` | +| Client | `--client` value | +| ------------------------- | ----------------------- | +| Claude Code | `claude_code` | +| Claude Desktop | `claude_desktop` | +| Codex | `codex` | +| Cursor | `cursor` | +| CodeBuddy | `codebuddy` | +| Cline CLI | `cline` | +| Gemini CLI | `gemini_cli` | +| Windsurf | `windsurf` | +| Devin | `devin` | +| OpenCode | `opencode` | +| Antigravity | `antigravity` | +| GitHub Copilot CLI | `copilot_cli` | +| Command Code | `commandcode` | +| Qwen Code | `qwen_code` | +| Kimi Code | `kimi` | +| VS Code | `vscode` | +| Grok Build | `grok_build` | +| OMP | `omp` | +| Pi | `pi` | +| Hermes | `hermes` | +| Qoder | `qoder` | +| Factory Droid | `droid` | +| Trae | `trae` | +| WorkBuddy | `workbuddy` | +| LM Studio | `lm_studio` | +| ZCode | `zcode` | +| DeepSeek Harness | `dsh` | +| FreeBuff | `freebuff` | +| Cline VS Code extension | `cline_vscode` | +| Cline in VS Code Insiders | `cline_vscode_insiders` | +| Cline in VSCodium | `cline_vscodium` | +| Cline in Cursor | `cline_cursor` | +| Cline in Windsurf | `cline_windsurf` | +| Kiro | `kiro` | +| Mastra Code | `mastracode` | +| Zed | `zed` | +| Amp | `amp` | `droid`, `dsh`, `kimi`, `qoder`, `trae`, `workbuddy`, and `zcode` require `rea-agents@6.5.0` or later. The 6.4.0 registry check above does not cover them. @@ -720,6 +729,14 @@ hosted connector; see [its configuration](client-configuration.md#other-client-s `lm_studio` requires a release after 6.8.0. +`cline_vscode`, `cline_vscode_insiders`, `cline_vscodium`, `cline_cursor`, +`cline_windsurf`, `kiro`, `mastracode`, `zed` and `amp` require a release after +6.9.0. Earlier releases could register Cline in VS Code, Kiro, Mastra Code, Zed +and Amp only through `rea mcp add`, and could not register Cline in VS Code +Insiders, VSCodium, Cursor or Windsurf at all; doctor, update and uninstall did +not see those registrations. Current releases inspect, refresh and remove them +like any other setup client. + See [client configuration and troubleshooting](client-configuration.md) for configuration paths, profiles, trust policies, and schema-limit workarounds. @@ -1280,7 +1297,11 @@ unchanged, failed or not-started outcomes. A partial failure returns a nonzero status while retaining successful client outcomes and recovery paths. User-level registration for a client that `rea setup` also supports uses that -client's setup definition, so the same native read rules apply. Gemini CLI +client's setup definition, so the same native read rules apply, and doctor, +update and uninstall inspect, refresh and remove what it wrote. Goose, Junie, +fx, MCPorter and Kilo Code are registered only by `rea mcp add` until their +native layers and path overrides are modeled; doctor, update and uninstall do +not yet see those registrations. Gemini CLI registration fails without writing when Gemini's system, defaults or trusted workspace settings exclude `rea`, leave it off a nonempty allowlist, or define a different `rea` entry with higher precedence. On Windows, registration refuses diff --git a/src/application/ClientConfigRoots.ts b/src/application/ClientConfigRoots.ts index 99f576075a..d298a5cebd 100644 --- a/src/application/ClientConfigRoots.ts +++ b/src/application/ClientConfigRoots.ts @@ -43,25 +43,28 @@ export const absoluteXdgConfigHome = ({ }; /** - * VS Code's `getUserDataPath`: non-empty `VSCODE_PORTABLE` selects portable - * storage, then non-empty `VSCODE_APPDATA`, then the platform default. A - * relative result resolves against `VSCODE_CWD`. Extensions such as Cline - * keep their global storage under this directory. + * Code-OSS's `getUserDataPath` for one product's data folder (`Code` for VS + * Code; `Cursor`, `Windsurf`, `VSCodium` or `Code - Insiders` for builds that + * share it): non-empty `VSCODE_PORTABLE` selects portable storage, then + * non-empty `VSCODE_APPDATA`, then the platform default. A relative result + * resolves against `VSCODE_CWD`. Extensions such as Cline keep their global + * storage under this directory. `VSCODE_PORTABLE` describes the portable + * build that set it, which REA attributes only to VS Code itself. */ -export const vscodeUserDirectory = ({ - home, - platform, - env, -}: ClientRootContext): string => { - const userData = env.VSCODE_PORTABLE - ? join(env.VSCODE_PORTABLE, "user-data") - : env.VSCODE_APPDATA - ? join(env.VSCODE_APPDATA, "Code") - : platform === "win32" - ? join(windowsAppDataRoots(home, env).roaming, "Code") - : platform === "darwin" - ? join(home, "Library", "Application Support", "Code") - : join(xdgConfigHomeOrDefault({ home, env }), "Code"); +export const vscodeUserDirectory = ( + { home, platform, env }: ClientRootContext, + dataFolder = "Code", +): string => { + const userData = + env.VSCODE_PORTABLE && dataFolder === "Code" + ? join(env.VSCODE_PORTABLE, "user-data") + : env.VSCODE_APPDATA + ? join(env.VSCODE_APPDATA, dataFolder) + : platform === "win32" + ? join(windowsAppDataRoots(home, env).roaming, dataFolder) + : platform === "darwin" + ? join(home, "Library", "Application Support", dataFolder) + : join(xdgConfigHomeOrDefault({ home, env }), dataFolder); // The catalog can describe Windows clients on another host; retain its // drive-absolute paths instead of resolving them against that host cwd. const absoluteUserData = diff --git a/src/application/ClientConfigurationDocument.ts b/src/application/ClientConfigurationDocument.ts index e3101b5280..da20b2c933 100644 --- a/src/application/ClientConfigurationDocument.ts +++ b/src/application/ClientConfigurationDocument.ts @@ -38,9 +38,7 @@ import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; export type ClientConfigurationFormat = | NonNullable - | "amp" | "fx" - | "zed" | "kilo" | "goose" | "copilot_cli_project"; diff --git a/src/application/McpRegistrationCatalog.ts b/src/application/McpRegistrationCatalog.ts index cc7a9a61ad..f1df6c0b80 100644 --- a/src/application/McpRegistrationCatalog.ts +++ b/src/application/McpRegistrationCatalog.ts @@ -34,15 +34,10 @@ import { fromSetup, present, fixedProjectLocation, - clineLocation, fxLocation, gooseLocation, junieLocation, - kiroLocation, - mastraLocation, mcporterLocation, - zedLocation, - ampLocation, type McpRegistrationLocationContext, type McpRegistrationGlobalLocation, type McpRegistrationLocation, @@ -136,14 +131,7 @@ const MCPORTER_STDIO_INCOMPATIBILITIES: readonly NativeStdioIncompatibility[] = */ export const MCP_REGISTRATION_CLIENTS = { antigravity: tableClient("antigravity"), - cline: { - kind: "registration-only", - displayName: "Cline VSCode Extension", - format: "json", - aliases: ["cline-vscode"], - globalLocation: clineLocation, - registrationConnection: { kind: "cline" }, - }, + cline: tableClient("cline_vscode"), "cline-cli": tableClient("cline"), "claude-code": tableClient("claude_code"), "claude-desktop": tableClient("claude_desktop"), @@ -211,35 +199,8 @@ export const MCP_REGISTRATION_CLIENTS = { }, }, "kimi-code": tableClient("kimi"), - "kiro-cli": { - kind: "registration-only", - displayName: "Kiro CLI", - format: "json", - aliases: ["kiro"], - globalLocation: kiroLocation, - projectLocation: fixedProjectLocation([".kiro/settings/mcp.json"]), - registrationConnection: { - kind: "flat", - fields: ["type", "url"], - stdio: [ - { kind: "optional-enum", field: "type", values: ["stdio"] }, - { kind: "present", field: "url" }, - ], - }, - }, - mastracode: { - kind: "registration-only", - displayName: "Mastra Code", - format: "json", - aliases: ["mastra"], - globalLocation: mastraLocation, - projectLocation: fixedProjectLocation([".mastracode/mcp.json"]), - registrationConnection: { - kind: "flat", - fields: ["url"], - stdio: [{ kind: "string", field: "url" }], - }, - }, + "kiro-cli": tableClient("kiro"), + mastracode: tableClient("mastracode"), mcporter: { kind: "registration-only", displayName: "MCPorter", @@ -256,29 +217,8 @@ export const MCP_REGISTRATION_CLIENTS = { pi: tableClient("pi"), vscode: tableClient("vscode"), windsurf: tableClient("windsurf"), - zed: { - kind: "registration-only", - displayName: "Zed", - format: "zed", - globalLocation: zedLocation, - projectLocation: fixedProjectLocation([".zed/settings.json"]), - registrationConnection: { - kind: "flat", - fields: ["url"], - stdio: [{ kind: "present", field: "url" }], - }, - }, - amp: { - kind: "registration-only", - displayName: "Amp", - format: "amp", - globalLocation: ampLocation, - registrationConnection: { - kind: "flat", - fields: ["url"], - stdio: [{ kind: "present", field: "url" }], - }, - }, + zed: tableClient("zed"), + amp: tableClient("amp"), } as const satisfies Record; export type McpRegistrationClientId = keyof typeof MCP_REGISTRATION_CLIENTS; diff --git a/src/application/McpRegistrationLocations.ts b/src/application/McpRegistrationLocations.ts index d1fb18aad3..762f181507 100644 --- a/src/application/McpRegistrationLocations.ts +++ b/src/application/McpRegistrationLocations.ts @@ -5,7 +5,6 @@ import { ConfigurationError } from "../domain/configurationErrors.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; import { absoluteXdgConfigHome, - vscodeUserDirectory, type ClientRootContext, } from "./ClientConfigRoots.js"; import { windowsAppDataRoots } from "./MsixPackageStorage.js"; @@ -116,18 +115,6 @@ export const firstExisting = async ( return fallback; }; -export const clineLocation = async ( - context: McpRegistrationLocationContext, -): Promise => - location( - join( - vscodeUserDirectory(rootContext(context)), - "globalStorage", - "saoudrizwan.claude-dev", - "settings", - "cline_mcp_settings.json", - ), - ); export const gooseLocation = async ( context: McpRegistrationLocationContext, ): Promise => { @@ -169,13 +156,6 @@ export const fixedProjectLocation = ), }; }; -export const kiroLocation = async ( - context: McpRegistrationLocationContext, -): Promise => - location( - join(context.home, ".kiro", "settings", "mcp.json"), - join(context.home, ".kiro"), - ); export const mcporterLocation = async ( context: McpRegistrationLocationContext, ): Promise => { @@ -186,36 +166,8 @@ export const mcporterLocation = async ( root, ); }; -export const zedLocation = async ( - context: McpRegistrationLocationContext, -): Promise => - // Zed's paths::config_dir. On Windows it reads the RoamingAppData known - // folder, which APPDATA normally names; on Linux, `dirs::config_dir` - // admits only an absolute XDG_CONFIG_HOME. - location( - context.platform === "darwin" - ? join(context.home, ".config", "zed", "settings.json") - : context.platform === "win32" - ? join(windowsRoaming(context), "Zed", "settings.json") - : join( - absoluteXdgConfigHome({ - home: context.home, - env: context.environment, - }), - "zed", - "settings.json", - ), - ); export const fxLocation = async ( context: McpRegistrationLocationContext, ): Promise => location(join(context.home, ".fx", "mcp.json")); -export const mastraLocation = async ( - context: McpRegistrationLocationContext, -): Promise => - location(join(context.home, ".mastracode", "mcp.json")); -export const ampLocation = async ( - context: McpRegistrationLocationContext, -): Promise => - location(join(context.home, ".config", "amp", "settings.json")); diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts index 7a90dd57c2..119d76be8b 100644 --- a/src/application/SupportedClients.ts +++ b/src/application/SupportedClients.ts @@ -5,7 +5,7 @@ import type { import type { ClientConfigurationFormat } from "./ClientConfigurationDocument.js"; import { dirname, isAbsolute, join, posix, resolve, win32 } from "node:path"; import { fileURLToPath } from "node:url"; -import { existsSync, lstatSync, readFileSync } from "node:fs"; +import { existsSync, lstatSync, readFileSync, statSync } from "node:fs"; import { err, ok, type Result } from "../domain/result.js"; import { HermesClientPathError, @@ -14,6 +14,7 @@ import { import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; import { appendCallerPath } from "../filesystem/callerPath.js"; import { + absoluteXdgConfigHome, vscodeUserDirectory, xdgConfigHomeOrDefault, } from "./ClientConfigRoots.js"; @@ -75,6 +76,8 @@ export interface SetupClient { | "zcode_fallback" | "zcode" | "dsh" + | "zed" + | "amp" | "unsupported"; } @@ -546,6 +549,144 @@ const devinDirectory = ({ home, platform, env }: ClientPathContext): string => ? join(windowsAppDataRoots(home, env).roaming, "devin") : join(xdgConfigHomeOrDefault({ home, env }), "devin"); +/** The Cline extension's settings in one editor's global storage. */ +const clineSettingsDirectory = + (dataFolder: string) => + (context: ClientPathContext): string => + join( + vscodeUserDirectory(context, dataFolder), + "globalStorage", + "saoudrizwan.claude-dev", + "settings", + ); +const clineVscodeSettingsDirectory = clineSettingsDirectory("Code"); + +/** Flathub's Zed (`dev.zed.Zed`) gets this XDG_CONFIG_HOME inside its sandbox. */ +const ZED_FLATPAK_CONFIG = [".var", "app", "dev.zed.Zed", "config"] as const; + +const directoryPresent = (path: string): Result => { + try { + lstatSync(path); + return ok(true); + } catch (cause: unknown) { + if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") + return ok(false); + return err({ + path, + message: `Cannot determine whether ${path} exists: ${cause instanceof Error ? cause.message : String(cause)}. Repair its access before configuring Zed.`, + }); + } +}; + +/** Whether two existing paths resolve to the same folder, by device and inode. */ +const sameDirectory = ( + first: string, + second: string, +): Result => { + const identities: { dev: bigint; ino: bigint }[] = []; + for (const path of [first, second]) { + try { + const { dev, ino } = statSync(path, { bigint: true }); + identities.push({ dev, ino }); + } catch (cause: unknown) { + return err({ + path, + message: `Cannot resolve ${path}: ${cause instanceof Error ? cause.message : String(cause)}. Repair it before configuring Zed.`, + }); + } + } + const [a, b] = identities; + return ok( + a !== undefined && b !== undefined && a.dev === b.dev && a.ino === b.ino, + ); +}; + +/** + * Zed's `paths::config_dir`. On Windows it reads the RoamingAppData known + * folder, which APPDATA normally names. On Linux and FreeBSD, + * `FLATPAK_XDG_CONFIG_HOME` wins, then `dirs::config_dir`, which admits only an + * absolute XDG_CONFIG_HOME. A Flathub Zed reads its sandbox's config folder, + * so REA uses it when only that folder exists and refuses to guess when a + * native configuration exists too. + */ +const zedLocation = ({ + home, + platform, + env, +}: ClientPathContext): Result => { + const at = (directory: string): ClientLocation => ({ + configPath: join(directory, "settings.json"), + markerPath: directory, + }); + if (platform === "darwin") return ok(at(join(home, ".config", "zed"))); + if (platform === "win32") + return ok(at(join(windowsAppDataRoots(home, env).roaming, "Zed"))); + const flatpakOverride = env.FLATPAK_XDG_CONFIG_HOME; + if (flatpakOverride) + return posix.isAbsolute(flatpakOverride) + ? ok(at(join(flatpakOverride, "zed"))) + : err({ + path: flatpakOverride, + message: + "FLATPAK_XDG_CONFIG_HOME is relative, so Zed's configuration folder depends on its working directory. Set an absolute path before configuring Zed.", + }); + const native = join(absoluteXdgConfigHome({ home, env }), "zed"); + const sandboxed = join(home, ...ZED_FLATPAK_CONFIG, "zed"); + const flatpak = directoryPresent(sandboxed); + if (!flatpak.ok) return flatpak; + if (!flatpak.value) return ok(at(native)); + const nativePresent = directoryPresent(native); + if (!nativePresent.ok) return nativePresent; + if (!nativePresent.value) return ok(at(sandboxed)); + // XDG_CONFIG_HOME or a link may make both names one folder. + const same = sameDirectory(native, sandboxed); + if (!same.ok) return same; + return same.value + ? ok(at(native)) + : err({ + path: sandboxed, + message: `Both ${native} and the Flatpak Zed folder ${sandboxed} exist, so REA cannot tell which Zed you use. Remove the configuration of the Zed you no longer use, then configure Zed again.`, + }); +}; + +/** + * Amp's user settings: `settings.json` or `settings.jsonc` in + * `~/.config/amp` on every platform. Amp does not document which one wins + * when both exist, so that case stays unresolved. + */ +const ampLocation = ({ + home, +}: ClientPathContext): Result => { + const directory = join(home, ".config", "amp"); + const candidates = ["settings.json", "settings.jsonc"].map((name) => + join(directory, name), + ); + const present: string[] = []; + for (const candidate of candidates) { + try { + lstatSync(candidate); + present.push(candidate); + } catch (cause: unknown) { + if ( + !(cause instanceof Error && "code" in cause && cause.code === "ENOENT") + ) + return err({ + path: candidate, + message: `Cannot determine whether ${candidate} exists: ${cause instanceof Error ? cause.message : String(cause)}. Repair its access before configuring Amp.`, + }); + } + } + if (present.length > 1) + return err({ + path: directory, + message: `Both ${candidates[0]} and ${candidates[1]} exist, and Amp does not document which one it reads. Merge them into one file before configuring Amp.`, + }); + return ok({ + configPath: present[0] ?? join(directory, "settings.json"), + markerPath: directory, + }); +}; + /** * FreeBuff's own profile directory (its `state.json` root, fixed under * `.config` on every platform). The shared `~/.agents` folder is not @@ -1069,6 +1210,118 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [ sharedRegistration: true, format: "json", }), + defineClient({ + name: "cline_vscode", + mcpAdd: { aliases: ["cline-vscode"] }, + registrationConnection: { kind: "cline" }, + displayName: "Cline VS Code extension", + configPath: (context: ClientPathContext) => + join(clineVscodeSettingsDirectory(context), "cline_mcp_settings.json"), + markerPath: clineVscodeSettingsDirectory, + format: "json", + }), + defineClient({ + name: "cline_vscode_insiders", + registrationConnection: { kind: "cline" }, + displayName: "Cline in VS Code Insiders", + configPath: (context: ClientPathContext) => + join( + clineSettingsDirectory("Code - Insiders")(context), + "cline_mcp_settings.json", + ), + markerPath: clineSettingsDirectory("Code - Insiders"), + format: "json", + }), + defineClient({ + name: "cline_vscodium", + registrationConnection: { kind: "cline" }, + displayName: "Cline in VSCodium", + configPath: (context: ClientPathContext) => + join( + clineSettingsDirectory("VSCodium")(context), + "cline_mcp_settings.json", + ), + markerPath: clineSettingsDirectory("VSCodium"), + format: "json", + }), + defineClient({ + name: "cline_cursor", + registrationConnection: { kind: "cline" }, + displayName: "Cline in Cursor", + configPath: (context: ClientPathContext) => + join( + clineSettingsDirectory("Cursor")(context), + "cline_mcp_settings.json", + ), + markerPath: clineSettingsDirectory("Cursor"), + format: "json", + }), + defineClient({ + name: "cline_windsurf", + registrationConnection: { kind: "cline" }, + displayName: "Cline in Windsurf", + configPath: (context: ClientPathContext) => + join( + clineSettingsDirectory("Windsurf")(context), + "cline_mcp_settings.json", + ), + markerPath: clineSettingsDirectory("Windsurf"), + format: "json", + }), + defineClient({ + name: "kiro", + mcpAdd: { aliases: ["kiro"], projectPaths: [".kiro/settings/mcp.json"] }, + registrationConnection: { + kind: "flat", + fields: ["type", "url"], + stdio: [ + { kind: "optional-enum", field: "type", values: ["stdio"] }, + { kind: "present", field: "url" }, + ], + }, + // The IDE, CLI and web clients share the user file. + displayName: "Kiro", + configPath: [".kiro", "settings", "mcp.json"], + markerPath: [".kiro"], + format: "json", + }), + defineClient({ + name: "mastracode", + mcpAdd: { aliases: ["mastra"], projectPaths: [".mastracode/mcp.json"] }, + registrationConnection: { + kind: "flat", + fields: ["url"], + stdio: [{ kind: "string", field: "url" }], + }, + displayName: "Mastra Code", + configPath: [".mastracode", "mcp.json"], + markerPath: [".mastracode"], + format: "json", + }), + defineClient({ + name: "zed", + mcpAdd: { projectPaths: [".zed/settings.json"] }, + registrationConnection: { + kind: "flat", + fields: ["url"], + stdio: [{ kind: "present", field: "url" }], + }, + displayName: "Zed", + location: zedLocation, + format: "zed", + }), + defineClient({ + name: "amp", + mcpAdd: {}, + registrationConnection: { + kind: "flat", + fields: ["url"], + stdio: [{ kind: "present", field: "url" }], + }, + displayName: "Amp", + location: ampLocation, + format: "amp", + }), defineClient({ name: "grok_bot", registrationConnection: { diff --git a/tests/boundary/cli/packageRunnerRegistration.test.ts b/tests/boundary/cli/packageRunnerRegistration.test.ts index f883bce32d..eb7952962e 100644 --- a/tests/boundary/cli/packageRunnerRegistration.test.ts +++ b/tests/boundary/cli/packageRunnerRegistration.test.ts @@ -115,9 +115,15 @@ for (const { runner, userAgent } of [ expect(registered.clients).toMatchObject([ { client: "amp", status: "configured" }, ]); + // Doctor also reports Amp, whose table row mcp add registered through. const doctor = await run(["doctor", "--client", "omp", "--json"]); expect(doctor.json).toMatchObject({ - identity: { registrations: [{ client: "omp", state: "aligned" }] }, + identity: { + registrations: [ + { client: "amp", state: "aligned" }, + { client: "omp", state: "aligned" }, + ], + }, }); const repeat = await run([ "setup", diff --git a/tests/boundary/filesystem/clientLifecycle.test.ts b/tests/boundary/filesystem/clientLifecycle.test.ts index b99bf1be52..a785356fbe 100644 --- a/tests/boundary/filesystem/clientLifecycle.test.ts +++ b/tests/boundary/filesystem/clientLifecycle.test.ts @@ -80,6 +80,15 @@ describe("client configuration filesystem lifecycle", () => { "zcode", "dsh", "freebuff", + "cline_vscode", + "cline_vscode_insiders", + "cline_vscodium", + "cline_cursor", + "cline_windsurf", + "kiro", + "mastracode", + "zed", + "amp", "grok_bot", ]); expect( diff --git a/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts b/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts new file mode 100644 index 0000000000..b1da6def6d --- /dev/null +++ b/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts @@ -0,0 +1,269 @@ +import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; + +import { parseClientConfiguration } from "../../../src/application/ClientConfigurationDocument.js"; +import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; +import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; +import { registerMcpClients } from "../../../src/application/McpClientRegistration.js"; +import { resolveMcpRegistrationClients } from "../../../src/application/McpRegistrationCatalog.js"; +import { + configureClientConfiguration, + inspectClientConfiguration, +} from "../../../src/application/SetupClientConfiguration.js"; +import { supportedClients } from "../../../src/application/SupportedClients.js"; +import { detectClients } from "../../../src/application/SetupHost.js"; +import { + runUninstall, + systemUninstallHost, +} from "../../../src/application/Uninstall.js"; +import { existingMaintenanceScope } from "../../../src/application/UpdateMaintenance.js"; +import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js"; +import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const platform = process.platform; +const command = currentClientRegistrationCommand({ platform }); + +beforeEach(clearClientLocationEnvironment); +afterEach(() => vi.unstubAllEnvs()); + +// Each client REA registers through `rea mcp add` is one client-table row, so +// doctor, update and uninstall see what mcp add wrote (#7181). +it.each([ + { agent: "cline", client: "cline_vscode" }, + { agent: "kiro-cli", client: "kiro" }, + { agent: "mastracode", client: "mastracode" }, + { agent: "zed", client: "zed" }, + { agent: "amp", client: "amp" }, +])( + "inspects, refreshes and removes the $agent registration that mcp add wrote as $client", + async ({ agent, client }) => { + const home = await createTestTempDirectory(`rea-mcp-add-${client}-`); + const environment = {}; + const resources = new ArtifactResourceScope(); + const selected = await resolveMcpRegistrationClients( + { agents: [agent], global: true, cwd: home, home, platform, environment }, + resources, + ); + if (!selected.ok) throw selected.error; + const row = supportedClients(home, platform, environment).find( + ({ name }) => name === client, + ); + if (row === undefined) throw new Error(`${client} has no table row`); + expect(selected.value.map(({ configPath }) => configPath)).toEqual([ + row.configPath, + ]); + + // An older, still REA-owned launcher: the package runner form that + // current setup migrates to the selected installation. + const legacy = { command: "npx", args: ["-y", "rea-agents@1.0.0", "mcp"] }; + const [outcome] = await registerMcpClients( + selected.value, + legacy, + undefined, + resources, + ); + expect(outcome).toMatchObject({ + status: "completed", + result: { ok: true, value: { status: "configured" } }, + }); + const status = async () => + ( + await readClientRegistrationStatuses(home, command[1], { + platform, + environment, + }) + ).find((entry) => entry.client === client); + + // Doctor reads the registration from the same row. + expect(await status()).toMatchObject({ + config_path: row.configPath, + command: [legacy.command, ...legacy.args], + command_identity: "owned", + state: "stale", + }); + // Update selects it, and setup refreshes it to the current launcher. + await expect( + existingMaintenanceScope(home, command[1] ?? "", environment), + ).resolves.toMatchObject({ clients: [client] }); + await expect( + inspectClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "update" }); + await expect( + configureClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "configured" }); + expect(await status()).toMatchObject({ + command: [...command], + command_identity: "owned", + }); + + // Uninstall removes only REA's row and keeps the file. + const uninstall = await runUninstall( + false, + systemUninstallHost(home, undefined, environment, platform), + ); + expect(uninstall.items).toContainEqual( + expect.objectContaining({ name: client, status: "removed" }), + ); + const remaining = parseClientConfiguration( + await readFile(row.configPath, "utf8"), + row.format, + ); + expect(remaining.servers).not.toHaveProperty("rea"); + }, +); + +it("registers Amp in settings.jsonc when that is Amp's only settings file", async () => { + const home = await createTestTempDirectory("rea-amp-jsonc-"); + const directory = join(home, ".config", "amp"); + const jsonc = join(directory, "settings.jsonc"); + await mkdir(directory, { recursive: true }); + await writeFile(jsonc, '{\n // keep\n "amp.theme": "dark"\n}\n'); + const resources = new ArtifactResourceScope(); + const selected = await resolveMcpRegistrationClients( + { + agents: ["amp"], + global: true, + cwd: home, + home, + platform, + environment: {}, + }, + resources, + ); + if (!selected.ok) throw selected.error; + expect(selected.value[0]?.configPath).toBe(jsonc); + await registerMcpClients( + selected.value, + { command: command[0] ?? "", args: command.slice(1) }, + undefined, + resources, + ); + const text = await readFile(jsonc, "utf8"); + expect(text).toContain("// keep"); + expect(parseClientConfiguration(text, "amp").servers).toHaveProperty("rea"); + + // With both files present, which one Amp reads is unknown. + await writeFile(join(directory, "settings.json"), "{}\n"); + const row = supportedClients(home, platform, {}).find( + ({ name }) => name === "amp", + ); + expect(row?.configPathError).toContain("Both"); + const ambiguous = await resolveMcpRegistrationClients( + { + agents: ["amp"], + global: true, + cwd: home, + home, + platform, + environment: {}, + }, + resources, + ); + expect(ambiguous.ok).toBe(false); +}); + +it.each([ + { client: "cline_vscode_insiders", folder: "Code - Insiders" }, + { client: "cline_vscodium", folder: "VSCodium" }, + { client: "cline_cursor", folder: "Cursor" }, + { client: "cline_windsurf", folder: "Windsurf" }, +])( + "manages Cline's registration in $folder's global storage", + async ({ client, folder }) => { + const home = await createTestTempDirectory(`rea-${client}-`); + const row = supportedClients(home, "linux", {}).find( + ({ name }) => name === client, + ); + if (row === undefined) throw new Error(`${client} has no table row`); + const settings = join( + home, + ".config", + folder, + "User", + "globalStorage", + "saoudrizwan.claude-dev", + "settings", + ); + expect(row.configPath).toBe(join(settings, "cline_mcp_settings.json")); + // VSCODE_PORTABLE names VS Code's own portable data, not this editor's. + expect( + supportedClients(home, "linux", { + VSCODE_PORTABLE: join(home, "portable"), + }).find(({ name }) => name === client)?.configPath, + ).toBe(row.configPath); + expect( + supportedClients(home, "linux", { + VSCODE_PORTABLE: join(home, "portable"), + }).find(({ name }) => name === "cline_vscode")?.configPath, + ).toBe( + join( + home, + "portable", + "user-data", + "User", + "globalStorage", + "saoudrizwan.claude-dev", + "settings", + "cline_mcp_settings.json", + ), + ); + // Detected only where that editor's Cline extension has run. + expect( + (await detectClients(home, "linux", {})).map(({ name }) => name), + ).not.toContain(client); + await mkdir(settings, { recursive: true }); + expect( + (await detectClients(home, "linux", {})).map(({ name }) => name), + ).toContain(client); + + await expect( + configureClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "configured" }); + const status = ( + await readClientRegistrationStatuses(home, command[1], { + platform: "linux", + environment: {}, + }) + ).find(({ client: name }) => name === client); + expect(status).toMatchObject({ command_identity: "owned" }); + const uninstall = await runUninstall( + false, + systemUninstallHost(home, undefined, {}, "linux"), + ); + expect(uninstall.items).toContainEqual( + expect.objectContaining({ name: client, status: "removed" }), + ); + }, +); + +it("selects the Zed configuration a Linux Flatpak Zed reads", async () => { + const home = await createTestTempDirectory("rea-zed-flatpak-"); + const zed = (env: NodeJS.ProcessEnv = {}) => + supportedClients(home, "linux", env).find(({ name }) => name === "zed"); + const native = join(home, ".config", "zed"); + const sandboxed = join(home, ".var", "app", "dev.zed.Zed", "config", "zed"); + expect(zed()?.configPath).toBe(join(native, "settings.json")); + await mkdir(sandboxed, { recursive: true }); + expect(zed()?.configPath).toBe(join(sandboxed, "settings.json")); + await mkdir(native, { recursive: true }); + expect(zed()?.configPathError).toContain("cannot tell which Zed"); + // A native folder linked to the Flatpak folder is one configuration. + await rm(native, { recursive: true }); + await symlink(sandboxed, native, "dir"); + expect(zed()?.configPath).toBe(join(native, "settings.json")); + await rm(native); + await mkdir(native, { recursive: true }); + // An XDG_CONFIG_HOME naming the Flatpak folder is one folder, not two. + expect( + zed({ XDG_CONFIG_HOME: join(home, ".var", "app", "dev.zed.Zed", "config") }) + ?.configPath, + ).toBe(join(sandboxed, "settings.json")); + expect( + zed({ FLATPAK_XDG_CONFIG_HOME: join(home, "selected") })?.configPath, + ).toBe(join(home, "selected", "zed", "settings.json")); + expect( + zed({ FLATPAK_XDG_CONFIG_HOME: "relative" })?.configPathError, + ).toContain("FLATPAK_XDG_CONFIG_HOME is relative"); +}); diff --git a/tests/fixtures/clientEnvironment.ts b/tests/fixtures/clientEnvironment.ts index 8d68a49560..d75f81d9e9 100644 --- a/tests/fixtures/clientEnvironment.ts +++ b/tests/fixtures/clientEnvironment.ts @@ -16,6 +16,7 @@ const CLIENT_LOCATION_ENVIRONMENT = [ "DSH_AGENTS_HOME", "COPILOT_HOME", "FACTORY_HOME_OVERRIDE", + "FLATPAK_XDG_CONFIG_HOME", "GROK_HOME", "GEMINI_CLI_HOME", "GEMINI_CLI_TRUST_WORKSPACE",