Skip to content

Commit 91e1d2c

Browse files
committed
fix(qa): prepare packaged plugins before gateway startup
1 parent 383a293 commit 91e1d2c

2 files changed

Lines changed: 224 additions & 61 deletions

File tree

‎extensions/qa-lab/src/gateway-child-setup.ts‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import { seedQaAgentWorkspace } from "./qa-agent-workspace.js";
4848
import { buildQaGatewayConfig, type QaThinkingLevel } from "./qa-gateway-config.js";
4949
import type { QaTransportAdapter } from "./qa-transport.js";
5050
import type { RuntimeId } from "./runtime-parity.js";
51-
const QA_PACKAGE_AUTH_FAILURE_MAX_CHARS = 2_048;
51+
const QA_PACKAGE_BOOTSTRAP_FAILURE_MAX_CHARS = 2_048;
5252
export type QaGatewayChildStateMutationContext = {
5353
configPath: string;
5454
runtimeEnv: NodeJS.ProcessEnv;
@@ -143,7 +143,7 @@ async function stageQaPackagedMockAuthProfiles(params: {
143143
const details = sliceUtf16Safe(
144144
redactQaGatewayDebugText(errorMessage),
145145
0,
146-
QA_PACKAGE_AUTH_FAILURE_MAX_CHARS,
146+
QA_PACKAGE_BOOTSTRAP_FAILURE_MAX_CHARS,
147147
);
148148
// oxlint-disable-next-line preserve-caught-error -- Candidate CLI errors can contain the submitted API key; only the redacted message crosses this boundary.
149149
throw new Error(`installed package mock auth bootstrap failed for ${provider}: ${details}`);
@@ -425,6 +425,39 @@ export async function prepareQaGatewayChild(
425425
}
426426
packagedMockAuthStaged = true;
427427
}
428+
if (usesPackagedCandidate && gatewayCommand) {
429+
try {
430+
// The separate onboarding smoke cannot prepare this child's state.
431+
// Converge every freshly written config; a new-port retry can otherwise
432+
// restore plugin entries the candidate removed before verify-only startup.
433+
const command = {
434+
executablePath: gatewayCommand.executablePath,
435+
argsPrefix: gatewayCommand.argsPrefix ?? [],
436+
cwd: gatewayCwd,
437+
env,
438+
};
439+
// Published candidates such as 2026.7.1-2 predate capability consent.
440+
const help = await runQaGatewayCliCommand({
441+
...command,
442+
args: ["update", "repair", "--help"],
443+
});
444+
const consentArgs = help.includes("--accept-capabilities")
445+
? ["--accept-capabilities"]
446+
: [];
447+
await runQaGatewayCliCommand({
448+
...command,
449+
args: ["update", "repair", ...consentArgs, "--yes", "--no-restart", "--json"],
450+
});
451+
} catch (error) {
452+
const details = sliceUtf16Safe(
453+
redactQaGatewayDebugText(toErrorObject(error, "plugin setup failed").message),
454+
0,
455+
QA_PACKAGE_BOOTSTRAP_FAILURE_MAX_CHARS,
456+
);
457+
// oxlint-disable-next-line preserve-caught-error -- Candidate output can include credentials; retain only the bounded redacted diagnostic.
458+
throw new Error(`installed package plugin setup failed: ${details}`);
459+
}
460+
}
428461
}
429462
if (!env) {
430463
throw new Error("qa gateway runtime env not initialized");

‎extensions/qa-lab/src/gateway-child.test.ts‎

Lines changed: 189 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import os from "node:os";
66
import path from "node:path";
77
import { Writable } from "node:stream";
88
import { pathToFileURL } from "node:url";
9+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
910
import { toErrorObject } from "openclaw/plugin-sdk/error-runtime";
1011
import { afterEach, describe, expect, it, vi } from "vitest";
1112
import {
@@ -204,6 +205,27 @@ if (args[0] === "models") {
204205
fs.writeFileSync(configPath, JSON.stringify(config));
205206
process.exit(0);
206207
}
208+
if (args[0] === "update") {
209+
if (args.includes("--help")) {
210+
process.stdout.write(process.env.QA_LEGACY_PLUGIN_SETUP === "1" ? "Options: --yes" : "Options: --accept-capabilities --yes");
211+
process.exit(0);
212+
}
213+
if (process.env.QA_LEGACY_PLUGIN_SETUP === "1" && args.includes("--accept-capabilities")) {
214+
process.stderr.write("unknown option --accept-capabilities");
215+
process.exit(2);
216+
}
217+
record({ kind: "plugins", args, authDbPath, configPath, stateDir });
218+
if (process.env.QA_FAIL_PLUGIN_SETUP === "1") {
219+
process.stderr.write("plugin fixture rejected: Authorization: Bearer fixture-plugin-secret");
220+
process.exit(8);
221+
}
222+
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
223+
delete config.plugins.entries["qa-lab"];
224+
config.plugins.allow = config.plugins.allow.filter((id) => id !== "qa-lab");
225+
fs.writeFileSync(configPath, JSON.stringify(config));
226+
process.stdout.write(JSON.stringify({ status: "ok", mode: "finalize", restart: false }));
227+
process.exit(0);
228+
}
207229
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
208230
record({
209231
kind: "gateway",
@@ -213,8 +235,18 @@ record({
213235
configPath,
214236
authProfileIds: Object.keys(config.auth?.profiles ?? {}),
215237
fixtureProfiles: config.fixtureProfiles,
238+
sourcePluginConfigured: Boolean(config.plugins?.entries?.["qa-lab"]),
239+
configPort: config.gateway.port,
216240
stateDir,
217241
});
242+
const gatewayAttempts = fs.readFileSync(recordPath, "utf8").trim().split("\\n")
243+
.map((line) => JSON.parse(line)).filter((entry) => entry.kind === "gateway").length;
244+
if (gatewayAttempts === 1 && process.env.QA_STARTUP_RETRY) {
245+
process.stderr.write(process.env.QA_STARTUP_RETRY === "migration"
246+
? "OpenClaw plugin migration inputs changed during startup convergence; refusing readiness."
247+
: "listen EADDRINUSE: address already in use");
248+
process.exit(18);
249+
}
218250
process.stderr.write("fixture gateway exit");
219251
process.exit(17);
220252
`,
@@ -1487,16 +1519,159 @@ describe("buildQaRuntimeEnv", () => {
14871519
}
14881520
});
14891521

1490-
it("lets an explicit packaged command own mock auth state before gateway spawn", async () => {
1491-
const fixtureRoot = await tempDirs.makeTempDir("qa-packaged-auth-");
1522+
it.each([false, true])(
1523+
"lets an explicit packaged command own mock auth and plugins before gateway spawn (legacy=%s)",
1524+
async (legacy) => {
1525+
const fixtureRoot = await tempDirs.makeTempDir("qa-packaged-auth-");
1526+
const tempParentDir = path.join(fixtureRoot, "gateway-temp");
1527+
const recordPath = path.join(fixtureRoot, "commands.jsonl");
1528+
const fixturePath = await writePackagedGatewayFixture(fixtureRoot);
1529+
await mkdir(tempParentDir);
1530+
1531+
const owner = ownGateway();
1532+
await expect(
1533+
owner.start({
1534+
repoRoot: process.cwd(),
1535+
command: {
1536+
executablePath: process.execPath,
1537+
argsPrefix: [fixturePath],
1538+
tempParentDir,
1539+
usePackagedPlugins: true,
1540+
},
1541+
providerMode: "mock-openai",
1542+
transportBaseUrl: "http://127.0.0.1:43123",
1543+
runtimeEnvPatch: {
1544+
QA_RECORD_PATH: recordPath,
1545+
QA_LEGACY_PLUGIN_SETUP: legacy ? "1" : "0",
1546+
},
1547+
}),
1548+
).rejects.toThrow("fixture gateway exit");
1549+
await expect(owner.stop()).resolves.toMatchObject({ errors: [] });
1550+
1551+
const records = await readJsonLines(recordPath);
1552+
const authRecords = records.filter((record) => record.kind === "auth");
1553+
expect(authRecords).toHaveLength(2);
1554+
expect(authRecords.map((record) => record.args)).toEqual([
1555+
[
1556+
"models",
1557+
"auth",
1558+
"--agent",
1559+
"qa",
1560+
"paste-api-key",
1561+
"--provider",
1562+
"openai",
1563+
"--profile-id",
1564+
"qa-mock-openai",
1565+
],
1566+
[
1567+
"models",
1568+
"auth",
1569+
"--agent",
1570+
"qa",
1571+
"paste-api-key",
1572+
"--provider",
1573+
"anthropic",
1574+
"--profile-id",
1575+
"qa-mock-anthropic",
1576+
],
1577+
]);
1578+
for (const record of authRecords) {
1579+
expect(record.stdin).toMatch(/^sk-qa-mock-[a-f0-9]{32}\n$/u);
1580+
expect(record.env).toMatchObject({
1581+
OPENCLAW_CLI: "1",
1582+
});
1583+
expect(record.configMode).toBe(0o600);
1584+
expect(record.configRegular).toBe(true);
1585+
expect(record.configSymlink).toBe(false);
1586+
}
1587+
expect(authRecords.map((record) => record.dbExists)).toEqual([false, true]);
1588+
const authConfigPaths = authRecords.map((record) => String(record.configPath));
1589+
expect(new Set(authConfigPaths).size).toBe(1);
1590+
expect(authConfigPaths[0]).toBe(
1591+
path.join(String(authRecords[0]?.stateDir), "qa-auth-bootstrap", "openclaw.json"),
1592+
);
1593+
expect(records.at(-1)).toMatchObject({
1594+
kind: "gateway",
1595+
authProfileIds: ["qa-mock-openai", "qa-mock-anthropic"],
1596+
dbExists: true,
1597+
});
1598+
expect(records.at(-1)?.configPath).not.toBe(authConfigPaths[0]);
1599+
expect(records.at(-1)?.fixtureProfiles).toBeUndefined();
1600+
expect(records.map((record) => record.kind)).toEqual(["auth", "auth", "plugins", "gateway"]);
1601+
expect(records[2]).toMatchObject({
1602+
args: [
1603+
"update",
1604+
"repair",
1605+
...(legacy ? [] : ["--accept-capabilities"]),
1606+
"--yes",
1607+
"--no-restart",
1608+
"--json",
1609+
],
1610+
configPath: records.at(-1)?.configPath,
1611+
stateDir: records.at(-1)?.stateDir,
1612+
});
1613+
expect(new Set(records.map((record) => record.authDbPath)).size).toBe(1);
1614+
},
1615+
);
1616+
1617+
it.each([
1618+
{ retry: "bind", configBuilds: 2 },
1619+
{ retry: "migration", configBuilds: 1 },
1620+
])(
1621+
"preserves packaged config repair across $retry startup retries",
1622+
async ({ retry, configBuilds }) => {
1623+
const fixtureRoot = await tempDirs.makeTempDir("qa-packaged-retry-");
1624+
const tempParentDir = path.join(fixtureRoot, "gateway-temp");
1625+
const recordPath = path.join(fixtureRoot, "commands.jsonl");
1626+
const fixturePath = await writePackagedGatewayFixture(fixtureRoot);
1627+
await mkdir(tempParentDir);
1628+
const mutateConfig = vi.fn((cfg: OpenClawConfig) => cfg);
1629+
const owner = ownGateway();
1630+
await expect(
1631+
owner.start({
1632+
repoRoot: process.cwd(),
1633+
command: {
1634+
executablePath: process.execPath,
1635+
argsPrefix: [fixturePath],
1636+
tempParentDir,
1637+
usePackagedPlugins: true,
1638+
},
1639+
providerMode: "mock-openai",
1640+
transportBaseUrl: "http://127.0.0.1:43123",
1641+
runtimeEnvPatch: { QA_RECORD_PATH: recordPath, QA_STARTUP_RETRY: retry },
1642+
mutateConfig,
1643+
}),
1644+
).rejects.toThrow("fixture gateway exit");
1645+
const records = await readJsonLines(recordPath);
1646+
const gateways = records.filter((record) => record.kind === "gateway");
1647+
expect(gateways).toHaveLength(2);
1648+
expect(gateways.map((record) => record.sourcePluginConfigured)).toEqual([false, false]);
1649+
expect(records.filter((record) => record.kind === "plugins")).toHaveLength(configBuilds);
1650+
expect(mutateConfig).toHaveBeenCalledTimes(configBuilds);
1651+
expect(records.filter((record) => record.kind === "auth")).toHaveLength(2);
1652+
expect(new Set(records.map((record) => record.stateDir)).size).toBe(1);
1653+
for (const gateway of gateways) {
1654+
expect(gateway.args).toContainEqual(String(gateway.configPort));
1655+
expect(gateway).toMatchObject({
1656+
dbExists: true,
1657+
authProfileIds: ["qa-mock-openai", "qa-mock-anthropic"],
1658+
});
1659+
}
1660+
if (retry === "migration") {
1661+
expect(gateways[1]?.configPort).toBe(gateways[0]?.configPort);
1662+
}
1663+
},
1664+
);
1665+
1666+
it("blocks packaged gateway spawn when candidate plugin setup fails", async () => {
1667+
const fixtureRoot = await tempDirs.makeTempDir("qa-packaged-plugins-fail-");
14921668
const tempParentDir = path.join(fixtureRoot, "gateway-temp");
14931669
const recordPath = path.join(fixtureRoot, "commands.jsonl");
14941670
const fixturePath = await writePackagedGatewayFixture(fixtureRoot);
14951671
await mkdir(tempParentDir);
1496-
14971672
const owner = ownGateway();
1498-
await expect(
1499-
owner.start({
1673+
const error = await owner
1674+
.start({
15001675
repoRoot: process.cwd(),
15011676
command: {
15021677
executablePath: process.execPath,
@@ -1506,61 +1681,16 @@ describe("buildQaRuntimeEnv", () => {
15061681
},
15071682
providerMode: "mock-openai",
15081683
transportBaseUrl: "http://127.0.0.1:43123",
1509-
runtimeEnvPatch: { QA_RECORD_PATH: recordPath },
1510-
}),
1511-
).rejects.toThrow("fixture gateway exit");
1512-
await expect(owner.stop()).resolves.toMatchObject({ errors: [] });
1513-
1684+
runtimeEnvPatch: { QA_RECORD_PATH: recordPath, QA_FAIL_PLUGIN_SETUP: "1" },
1685+
})
1686+
.catch((caught: unknown) => caught);
1687+
expect(error).toBeInstanceOf(Error);
1688+
if (!(error instanceof Error)) throw new Error("expected package plugin setup error");
1689+
expect(error.message).toContain("installed package plugin setup failed: OpenClaw CLI exited 8");
1690+
expect(error.message).not.toContain("fixture-plugin-secret");
1691+
expect(String(error.cause)).not.toContain("fixture-plugin-secret");
15141692
const records = await readJsonLines(recordPath);
1515-
const authRecords = records.filter((record) => record.kind === "auth");
1516-
expect(authRecords).toHaveLength(2);
1517-
expect(authRecords.map((record) => record.args)).toEqual([
1518-
[
1519-
"models",
1520-
"auth",
1521-
"--agent",
1522-
"qa",
1523-
"paste-api-key",
1524-
"--provider",
1525-
"openai",
1526-
"--profile-id",
1527-
"qa-mock-openai",
1528-
],
1529-
[
1530-
"models",
1531-
"auth",
1532-
"--agent",
1533-
"qa",
1534-
"paste-api-key",
1535-
"--provider",
1536-
"anthropic",
1537-
"--profile-id",
1538-
"qa-mock-anthropic",
1539-
],
1540-
]);
1541-
for (const record of authRecords) {
1542-
expect(record.stdin).toMatch(/^sk-qa-mock-[a-f0-9]{32}\n$/u);
1543-
expect(record.env).toMatchObject({
1544-
OPENCLAW_CLI: "1",
1545-
});
1546-
expect(record.configMode).toBe(0o600);
1547-
expect(record.configRegular).toBe(true);
1548-
expect(record.configSymlink).toBe(false);
1549-
}
1550-
expect(authRecords.map((record) => record.dbExists)).toEqual([false, true]);
1551-
const authConfigPaths = authRecords.map((record) => String(record.configPath));
1552-
expect(new Set(authConfigPaths).size).toBe(1);
1553-
expect(authConfigPaths[0]).toBe(
1554-
path.join(String(authRecords[0]?.stateDir), "qa-auth-bootstrap", "openclaw.json"),
1555-
);
1556-
expect(records.at(-1)).toMatchObject({
1557-
kind: "gateway",
1558-
authProfileIds: ["qa-mock-openai", "qa-mock-anthropic"],
1559-
dbExists: true,
1560-
});
1561-
expect(records.at(-1)?.configPath).not.toBe(authConfigPaths[0]);
1562-
expect(records.at(-1)?.fixtureProfiles).toBeUndefined();
1563-
expect(new Set(records.map((record) => record.authDbPath)).size).toBe(1);
1693+
expect(records.map((record) => record.kind)).toEqual(["auth", "auth", "plugins"]);
15641694
});
15651695

15661696
it("blocks packaged gateway spawn when candidate auth bootstrap fails", async () => {

0 commit comments

Comments
 (0)