Files
reverse-engineering-anything/tests/boundary/filesystem/qwenClientConfiguration.test.ts
T
morluto 6537e35fa7 fix(setup): honor Qwen Code MCP settings precedence (#15131)
* fix(setup): honor Qwen Code MCP settings precedence

* fix(setup): preserve Qwen settings identity and readiness
2026-11-29 19:19:32 +00:00

462 lines
16 KiB
TypeScript

import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js";
import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import {
access,
mkdir,
readFile,
rmdir,
symlink,
writeFile,
} from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { parse as parseJsonc } from "jsonc-parser";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import {
configureClientConfiguration,
inspectClientConfiguration,
} from "../../../src/application/SetupClientConfiguration.js";
import { existingMaintenanceScope } from "../../../src/application/UpdateMaintenance.js";
import { systemSetupHost } from "../../../src/application/SetupHost.js";
import { MANAGED_SKILL_FILES } from "../../../src/application/SetupSkill.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
const command = currentClientRegistrationCommand();
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const qwenPath = (
home: string,
platform: NodeJS.Platform,
env: Parameters<typeof supportedClients>[2] = {},
) =>
supportedClients(home, platform, env).find(
({ name }) => name === "qwen_code",
);
describe("Qwen Code configuration paths", () => {
it("resolves the user settings file and marker directory", () => {
expect(qwenPath("/home/a", "linux")).toMatchObject({
name: "qwen_code",
displayName: "Qwen Code",
configPath: join("/home/a", ".qwen", "settings.json"),
markerPath: join("/home/a", ".qwen"),
format: "json",
});
expect(qwenPath("/Users/a", "darwin")?.configPath).toBe(
join("/Users/a", ".qwen", "settings.json"),
);
});
it.each([
["", join("/home/a", ".qwen")],
["~", "/home/a"],
["~/profiles/work", join("/home/a", "profiles", "work")],
["~\\profiles\\work", join("/home/a", "profiles", "work")],
["profiles/work", resolve("profiles/work")],
[" profile ", resolve(" profile ")],
["$PROFILE", resolve("$PROFILE")],
])("matches Qwen's QWEN_HOME resolution for %j", (override, directory) => {
vi.stubEnv("QWEN_HOME", override);
const client = qwenPath("/home/a", process.platform, {
QWEN_HOME: override,
});
expect(
supportedClients("/home/a", HOST_PLATFORM.platform).find(
({ name }) => name === "qwen_code",
),
).toEqual(client);
expect(client).toMatchObject({
configPath: join(directory, "settings.json"),
markerPath: directory,
});
});
});
describe("Qwen Code client lifecycle", () => {
const qwenClient = async () => {
const home = await createTestTempDirectory("rea-qwen-");
const client = qwenPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Qwen Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("registers rea in mcpServers while preserving unrelated settings and comments", async () => {
const { home, client } = await qwenClient();
await writeFile(
client.configPath,
`{
// Keep this note.
"model": { "name": "qwen3-coder-plus" },
"mcpServers": { "other": { "command": "other-server" } }
}
`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(text).toContain("// Keep this note.");
expect(parseJsonc(text)).toEqual({
model: { name: "qwen3-coder-plus" },
mcpServers: {
other: { command: "other-server" },
rea: { command: command[0], args: command.slice(1) },
},
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
const removedText = await readFile(client.configPath, "utf8");
const removed = parseJsonc(removedText);
expect(removed).toEqual({
model: { name: "qwen3-coder-plus" },
mcpServers: { other: { command: "other-server" } },
});
expect(removedText).toContain("// Keep this note.");
});
it("preserves Qwen environment expressions when refreshing a registration", async () => {
const { home, client } = await qwenClient();
const projectPath = join(home, "retained.gpr");
const language = "${QWEN_GHIDRA_LANGUAGE}";
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: {
command: command[0],
args: command.slice(1),
env: {
PATH: "/opt/bin:${PATH}",
REA_GHIDRA_PROJECT_PATH: projectPath,
REA_GHIDRA_LANGUAGE_ID: language,
},
},
},
}),
);
expect(
(
await configureClientConfiguration(
client,
{ REA_KUNA_JOBS: "4" },
command,
)
).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(parseJsonc(text).mcpServers.rea.env).toEqual({
PATH: "/opt/bin:${PATH}",
REA_GHIDRA_PROJECT_PATH: projectPath,
REA_GHIDRA_LANGUAGE_ID: language,
REA_KUNA_JOBS: "4",
});
expect(
await configureClientConfiguration(
client,
{ REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default" },
command,
),
).toMatchObject({ status: "failed", reason: "readback" });
expect(await readFile(client.configPath, "utf8")).toBe(text);
});
it("reports the selected installation as aligned", async () => {
const { home, client } = await qwenClient();
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const entry = command[1];
const status = (
await readClientRegistrationStatuses(home, entry, {
platform: HOST_PLATFORM.platform,
environment: {},
})
).find(({ client: name }) => name === "qwen_code");
expect(status).toMatchObject({ state: "aligned" });
});
});
describe("Qwen Code effective settings", () => {
const qwenSettings = async (overrideDefaults = false) => {
const home = await createTestTempDirectory("rea-qwen-settings-");
const cwd = join(home, "workspace");
const project = join(cwd, ".qwen", "settings.json");
const defaults = join(
home,
overrideDefaults ? "defaults.json" : "system-defaults.json",
);
const environment = {
...(overrideDefaults ? { QWEN_CODE_SYSTEM_DEFAULTS_PATH: defaults } : {}),
QWEN_CODE_SYSTEM_SETTINGS_PATH: join(home, "system.json"),
QWEN_CODE_TRUSTED_FOLDERS_PATH: join(home, "trustedFolders.json"),
};
const client = qwenPath(home, process.platform, environment);
if (client === undefined) throw new Error("missing Qwen Code client");
await mkdir(dirname(project), { recursive: true });
await mkdir(dirname(client.configPath), { recursive: true });
const write = (path: string, settings: unknown) =>
writeFile(path, JSON.stringify(settings));
const inWorkspace = async <T>(operation: () => Promise<T>): Promise<T> => {
const workingDirectory = vi.spyOn(process, "cwd").mockReturnValue(cwd);
try {
return await operation();
} finally {
workingDirectory.mockRestore();
}
};
const status = () =>
inWorkspace(async () =>
(
await readClientRegistrationStatuses(home, command[1], {
platform: process.platform,
environment,
selectedClientIds: ["qwen_code"],
})
).find(({ client: name }) => name === "qwen_code"),
);
return {
client,
cwd,
defaults,
environment,
home,
inWorkspace,
project,
status,
write,
};
};
it("selects the highest layer as a whole and tracks workspace approval separately", async () => {
const { client, cwd, defaults, environment, project, status, write } =
await qwenSettings();
await write(defaults, {
mcpServers: { rea: { command: command[0], args: ["default"] } },
security: { folderTrust: { enabled: true } },
});
expect(await status()).toMatchObject({
config_path: defaults,
command: [command[0], "default"],
});
await write(client.configPath, {
mcpServers: { rea: { command: command[0], args: command.slice(1) } },
});
await write(project, { mcpServers: { rea: { command: command[0] } } });
expect(await status()).toMatchObject({
config_path: client.configPath,
state: "aligned",
});
await write(environment.QWEN_CODE_TRUSTED_FOLDERS_PATH, {
[cwd]: "TRUST_FOLDER",
});
expect(await status()).toMatchObject({
config_path: project,
scope: "project",
command: [command[0]],
state: "unknown",
remediation: expect.stringContaining("qwen mcp list"),
});
await write(project, { mcpServers: { rea: { command: 42 } } });
expect(await status()).toMatchObject({
config_path: project,
scope: "project",
state: "invalid",
remediation: expect.stringContaining(project),
});
await write(environment.QWEN_CODE_SYSTEM_SETTINGS_PATH, {
mcpServers: { rea: { command: command[0], args: ["system"] } },
});
expect(await status()).toMatchObject({
config_path: environment.QWEN_CODE_SYSTEM_SETTINGS_PATH,
command: [command[0], "system"],
state: "stale",
});
await write(environment.QWEN_CODE_SYSTEM_SETTINGS_PATH, {
mcpServers: { rea: { command: command[0], args: command.slice(1) } },
});
expect(await status()).toMatchObject({
config_path: environment.QWEN_CODE_SYSTEM_SETTINGS_PATH,
state: "aligned",
});
expect(await inspectClientConfiguration(client, {}, command)).toMatchObject(
{
status: "invalid",
remediation: expect.stringContaining(
environment.QWEN_CODE_SYSTEM_SETTINGS_PATH,
),
},
);
});
it("keeps user ownership when the workspace alias triggers native approval", async () => {
const { client, inWorkspace, project, status, write } =
await qwenSettings();
await write(client.configPath, {
mcpServers: { rea: { command: command[0], args: command.slice(1) } },
});
expect(await status()).toMatchObject({
config_path: client.configPath,
state: "aligned",
});
await rmdir(dirname(project));
await symlink(dirname(client.configPath), dirname(project), "junction");
expect(await status()).toMatchObject({
config_path: client.configPath,
command_identity: "owned",
state: "unknown",
remediation: expect.stringContaining("qwen mcp list"),
});
expect(
await inWorkspace(() => inspectClientConfiguration(client, {}, command)),
).toMatchObject({ status: "already_current" });
});
it("keeps a defaults-only registration out of refresh and validates the selected launcher environment", async () => {
const { client, defaults, environment, home, status, write } =
await qwenSettings();
await write(defaults, {
mcpServers: {
rea: {
command: "npx",
args: ["-y", "rea-agents@1.0.0", "mcp"],
env: { CALLER_SETTING: "kept" },
},
},
});
if (command[1] === undefined) throw new Error("missing REA entrypoint");
expect(await status()).toMatchObject({
config_path: defaults,
command_identity: "owned",
});
const scope = await existingMaintenanceScope(
home,
command[1],
environment,
{
platform: process.platform,
},
);
expect(scope.clients).not.toContain("qwen_code");
expect(await inspectClientConfiguration(client, {}, command)).toMatchObject(
{
status: "invalid",
remediation: expect.stringContaining(defaults),
},
);
await write(defaults, {
mcpServers: {
rea: {
command: command[0],
args: command.slice(1),
env: { REA_KUNA_JOBS: 42 },
},
},
});
expect(await status()).toMatchObject({
config_path: defaults,
command_identity: "owned",
state: "invalid",
remediation: expect.stringContaining("REA_KUNA_JOBS"),
});
});
it("applies a lower-layer MCP exclusion even when a higher layer defines the server", async () => {
const { client, defaults, status, write } = await qwenSettings(true);
await write(defaults, {
mcp: { excluded: ["r.a", "r?b"] },
});
await write(client.configPath, {
mcpServers: { rea: { command: command[0], args: command.slice(1) } },
});
expect(await status()).toMatchObject({ state: "aligned" });
await write(defaults, {
mcp: { excluded: ["r?a"] },
});
expect(await status()).toMatchObject({
config_path: defaults,
state: "manual",
remediation: expect.stringContaining("mcp.excluded"),
});
});
});
describe("Qwen Code profile setup", () => {
it.each([false, true])(
"installs and removes the shared skill with a custom home: %s",
async (customHome) => {
const home = await createTestTempDirectory("rea-qwen-profile-");
const profile = join(home, customHome ? "qwen-profile" : ".qwen");
const environment = {
HOME: home,
USERPROFILE: home,
...(customHome ? { QWEN_HOME: profile } : {}),
};
await mkdir(profile);
const setup = systemSetupHost(undefined, environment);
const client = (await setup.detectedClients()).find(
({ name }) => name === "qwen_code",
);
if (client === undefined) throw new Error("missing Qwen Code client");
expect(client.configPath).toBe(join(profile, "settings.json"));
expect(await setup.configureClient(client, {}, command)).toEqual({
status: "configured",
});
expect(await setup.installSkill([client.name])).toEqual({
ok: true,
value: "installed",
});
const skill = join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName);
await writeFile(join(skill, "user-notes.txt"), "user-authored");
expect(await readFile(join(skill, "SKILL.md"), "utf8")).toContain(
"reverse-engineer-anything",
);
expect(await setup.clientNeedsConfigure(client, {}, command)).toBe(false);
expect(await setup.skillNeedsInstall([client.name])).toBe(false);
expect(await setup.installSkill([client.name])).toEqual({
ok: true,
value: "unchanged",
});
expect(
(
await readClientRegistrationStatuses(home, command[1], {
platform: HOST_PLATFORM.platform,
environment,
})
).find(({ client: name }) => name === "qwen_code"),
).toMatchObject({ state: "aligned" });
const uninstall = systemUninstallHost(home, undefined, environment);
const registered = (await uninstall.clients()).find(
({ name }) => name === "qwen_code",
);
expect(registered).toEqual(client);
expect((await uninstall.removeClient(client)).status).toBe("removed");
expect((await uninstall.removeSkill()).status).toBe("removed");
for (const relativePath of MANAGED_SKILL_FILES)
await expect(access(join(skill, relativePath))).rejects.toMatchObject({
code: "ENOENT",
});
expect(await readFile(join(skill, "user-notes.txt"), "utf8")).toBe(
"user-authored",
);
if (customHome)
await expect(access(join(home, ".qwen"))).rejects.toMatchObject({
code: "ENOENT",
});
},
);
});