Skip to content

Commit 23c7981

Browse files
steipetePeter Steinberger
andauthored
test(system-agent): reduce suite setup overhead (#119424)
* test(system-agent): reduce suite setup overhead * test(system-agent): type-check TUI call ordering --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 866dade commit 23c7981

13 files changed

Lines changed: 166 additions & 96 deletions

‎src/system-agent/assistant.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
33
import fs from "node:fs/promises";
44
import os from "node:os";
55
import path from "node:path";
6-
import { SessionManager } from "../agents/sessions/index.js";
6+
import { SessionManager } from "../agents/sessions/session-manager.js";
77
import {
88
SYSTEM_AGENT_ASSISTANT_SYSTEM_PROMPT,
99
SYSTEM_AGENT_GREETING_SYSTEM_PROMPT,

‎src/system-agent/operations-execute.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
// Public operation dispatcher. Parsing and mutation helpers live in focused modules.
22
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
3-
import { createAgent } from "../agents/agent-create.js";
43
import { buildAgentMainSessionKey, normalizeAgentId } from "../routing/session-key.js";
54
import type { RuntimeEnv } from "../runtime.js";
65
import { resolveUserPath, shortenHomePath } from "../utils.js";
@@ -407,8 +406,10 @@ export async function executeSystemAgentOperation(
407406
runtime,
408407
opts,
409408
run: async (ctx) => {
409+
const createAgentForOperation =
410+
ctx.deps?.createAgent ?? (await import("../agents/agent-create.js")).createAgent;
410411
const result = await ctx.commit(async () => {
411-
return await (ctx.deps?.createAgent ?? createAgent)({
412+
return await createAgentForOperation({
412413
name: operation.agentId,
413414
...(operation.workspace ? { workspace: operation.workspace } : {}),
414415
});

‎src/system-agent/operations-setup-flows.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
isPersistentSystemAgentOperation,
66
parseSystemAgentOperation,
77
} from "./operations.js";
8-
import { createSystemAgentTestRuntime } from "./system-agent.test-helpers.js";
8+
import { createSystemAgentTestRuntime } from "./system-agent.runtime.test-support.js";
99

1010
describe("system agent setup-flow operations", () => {
1111
it("parses channel listing and connect requests", () => {

‎src/system-agent/operations.setup-transaction.test.ts‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
1+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
22
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
33
import type { OpenClawConfig } from "../config/types.openclaw.js";
44
import { resetPluginStateStoreForTests } from "../plugin-state/plugin-state-store.js";
@@ -7,7 +7,11 @@ import { captureEnv, setTestEnvValue } from "../test-utils/env.js";
77
import { SystemAgentInferenceUnavailableError } from "./inference-error.js";
88
import { executeSystemAgentOperation, type SystemAgentCommandDeps } from "./operations.js";
99
import type { SystemAgentSetupApplyResult } from "./setup-apply.js";
10-
import { createSystemAgentTestRuntime } from "./system-agent.test-helpers.js";
10+
import { createSystemAgentTestRuntime } from "./system-agent.runtime.test-support.js";
11+
import {
12+
installSystemAgentPluginMetadataTestSnapshot,
13+
type SystemAgentPluginMetadataTestSnapshot,
14+
} from "./system-agent.test-helpers.js";
1115

1216
const mocks = vi.hoisted(() => ({ ensureOnboardingAgent: vi.fn() }));
1317

@@ -43,8 +47,10 @@ const mockConfig = vi.hoisted(() => {
4347
exists: true,
4448
config: { agents: { entries: { main: { default: true } } } } as OpenClawConfig,
4549
};
50+
let bindPluginMetadata = (_config: OpenClawConfig) => {};
4651
const snapshot = () => {
4752
const config = structuredClone(state.config);
53+
bindPluginMetadata(config);
4854
return {
4955
exists: state.exists,
5056
valid: state.exists,
@@ -66,6 +72,7 @@ const mockConfig = vi.hoisted(() => {
6672
state.path = "/tmp/openclaw.json";
6773
state.exists = true;
6874
state.config = { agents: { entries: { main: { default: true } } } };
75+
bindPluginMetadata(state.config);
6976
readConfigFileSnapshot.mockReset().mockImplementation(async () => snapshot());
7077
withConfigMutationExclusive
7178
.mockReset()
@@ -74,9 +81,17 @@ const mockConfig = vi.hoisted(() => {
7481
missing(configPath: string) {
7582
state.path = configPath;
7683
state.exists = false;
84+
bindPluginMetadata(state.config);
7785
},
7886
setConfig(config: OpenClawConfig) {
7987
state.config = structuredClone(config);
88+
bindPluginMetadata(state.config);
89+
},
90+
bindPluginMetadata(config: OpenClawConfig) {
91+
bindPluginMetadata(config);
92+
},
93+
setPluginMetadataBinder(binder: (config: OpenClawConfig) => void) {
94+
bindPluginMetadata = binder;
8095
},
8196
readConfigFileSnapshot,
8297
withConfigMutationExclusive,
@@ -160,6 +175,20 @@ function createRecoverySetupDeps(
160175
}
161176

162177
const opTempDirs = useAutoCleanupTempDirTracker(afterEach);
178+
let pluginMetadataSnapshot: SystemAgentPluginMetadataTestSnapshot | undefined;
179+
180+
beforeAll(() => {
181+
pluginMetadataSnapshot = installSystemAgentPluginMetadataTestSnapshot();
182+
mockConfig.setPluginMetadataBinder((config) => {
183+
pluginMetadataSnapshot?.bindForConfig(config);
184+
});
185+
mockConfig.reset();
186+
});
187+
188+
afterAll(() => {
189+
mockConfig.setPluginMetadataBinder(() => {});
190+
pluginMetadataSnapshot?.restore();
191+
});
163192

164193
describe("system-agent setup transaction", () => {
165194
let stateDirSnapshot: ReturnType<typeof captureEnv> | undefined;
@@ -188,6 +217,7 @@ describe("system-agent setup transaction", () => {
188217
list: [{ id: "main", default: true }],
189218
},
190219
} satisfies OpenClawConfig;
220+
mockConfig.bindPluginMetadata(config);
191221
mockConfig.readConfigFileSnapshot.mockResolvedValue({
192222
exists: true,
193223
valid: true,

‎src/system-agent/operations.setup.test.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@ import { resetPluginStateStoreForTests } from "../plugin-state/plugin-state-stor
99
import { captureEnv, setTestEnvValue } from "../test-utils/env.js";
1010
import { SystemAgentInferenceUnavailableError } from "./inference-error.js";
1111
import { executeSystemAgentOperation, type SystemAgentCommandDeps } from "./operations.js";
12+
import { createSystemAgentTestRuntime } from "./system-agent.runtime.test-support.js";
1213
import {
13-
createSystemAgentTestRuntime,
1414
expectSystemAgentAuditRecord as expectAuditRecord,
1515
expectTestRecordFields as expectRecordFields,
1616
installSystemAgentClaudeCliBackendTestFixture,
17+
installSystemAgentPluginMetadataTestSnapshot,
1718
readLastSystemAgentAuditEntry as readLastAuditEntry,
1819
requireTestRecord as requireRecord,
20+
type SystemAgentPluginMetadataTestSnapshot,
1921
} from "./system-agent.test-helpers.js";
2022

2123
type TestConfig = Record<string, unknown>;
@@ -29,8 +31,10 @@ const mockConfig = vi.hoisted(() => {
2931
hash: "mock-hash-0" as string | undefined,
3032
};
3133
const cloneConfig = () => structuredClone(state.config);
34+
let bindPluginMetadata = (_config: TestConfig) => {};
3235
const snapshot = () => {
3336
const config = cloneConfig();
37+
bindPluginMetadata(config);
3438
return {
3539
path: state.path,
3640
exists: state.exists,
@@ -53,18 +57,24 @@ const mockConfig = vi.hoisted(() => {
5357
state.exists = true;
5458
state.config = { agents: { entries: { main: { default: true } } } };
5559
state.hash = "mock-hash-0";
60+
bindPluginMetadata(state.config);
5661
},
5762
missing(pathLocal: string) {
5863
state.path = pathLocal;
5964
state.exists = false;
6065
state.config = { agents: { entries: { main: { default: true } } } };
6166
state.hash = undefined;
67+
bindPluginMetadata(state.config);
6268
},
6369
currentConfig() {
6470
return cloneConfig();
6571
},
6672
setConfig(config: TestConfig) {
6773
state.config = structuredClone(config);
74+
bindPluginMetadata(state.config);
75+
},
76+
setPluginMetadataBinder(binder: (config: TestConfig) => void) {
77+
bindPluginMetadata = binder;
6878
},
6979
readConfigFileSnapshot: vi.fn(async () => snapshot()),
7080
mutateConfigFile: vi.fn(
@@ -80,10 +90,12 @@ const mockConfig = vi.hoisted(() => {
8090
const before = snapshot();
8191
const draft = cloneConfig();
8292
await params.mutate(draft, { snapshot: before });
93+
bindPluginMetadata(draft);
8394
await params.writeOptions?.preCommitRuntimePreflight?.(structuredClone(draft));
8495
state.exists = true;
8596
state.config = draft;
8697
state.hash = "mock-hash-1";
98+
bindPluginMetadata(state.config);
8799
return {
88100
path: state.path,
89101
previousHash: before.hash ?? null,
@@ -148,12 +160,20 @@ vi.mock("../state/local-onboarding-state.js", () => ({
148160

149161
const opTempDirs = useAutoCleanupTempDirTracker(afterEach);
150162
let restoreCliBackendFixture: (() => void) | undefined;
163+
let pluginMetadataSnapshot: SystemAgentPluginMetadataTestSnapshot | undefined;
151164

152165
beforeAll(() => {
153166
restoreCliBackendFixture = installSystemAgentClaudeCliBackendTestFixture();
167+
pluginMetadataSnapshot = installSystemAgentPluginMetadataTestSnapshot();
168+
mockConfig.setPluginMetadataBinder((config) => {
169+
pluginMetadataSnapshot?.bindForConfig(config as OpenClawConfig);
170+
});
171+
mockConfig.reset();
154172
});
155173

156174
afterAll(() => {
175+
mockConfig.setPluginMetadataBinder(() => {});
176+
pluginMetadataSnapshot?.restore();
157177
restoreCliBackendFixture?.();
158178
});
159179

‎src/system-agent/operations.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
isPersistentSystemAgentOperation,
1515
parseSystemAgentOperation,
1616
} from "./operations.js";
17-
import { createSystemAgentTestRuntime } from "./system-agent.test-helpers.js";
17+
import { createSystemAgentTestRuntime } from "./system-agent.runtime.test-support.js";
1818

1919
type TestConfig = Record<string, unknown>;
2020

‎src/system-agent/operations.tui.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import path from "node:path";
44
import { withTempHome } from "openclaw/plugin-sdk/test-env";
55
import { describe, expect, it, vi } from "vitest";
66
import { executeSystemAgentOperation, isPersistentSystemAgentOperation } from "./operations.js";
7-
import { createSystemAgentTestRuntime } from "./system-agent.test-helpers.js";
7+
import { createSystemAgentTestRuntime } from "./system-agent.runtime.test-support.js";
88

99
describe("system-agent TUI operations", () => {
1010
it("refuses doctor repairs before any write or audit", async () => {

‎src/system-agent/setup-inference.test.ts‎

Lines changed: 3 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,8 @@ import { detectInferenceBackends } from "../commands/onboard-inference.js";
1717
import { resolveAgentModelPrimaryValue } from "../config/model-input.js";
1818
import type { OpenClawConfig } from "../config/types.openclaw.js";
1919
import type { PluginInstallRecord } from "../config/types.plugins.js";
20-
import { setCurrentPluginMetadataSnapshot } from "../plugins/current-plugin-metadata-snapshot.js";
21-
import { resolveInstalledPluginIndexPolicyHash } from "../plugins/installed-plugin-index-policy.js";
2220
import { withoutPluginInstallRecords } from "../plugins/installed-plugin-index-records.js";
2321
import { hasRetainedManagedNpmInstallMarker } from "../plugins/managed-npm-retention.js";
24-
import { resolvePluginControlPlaneFingerprint } from "../plugins/plugin-control-plane-context.js";
2522
import { resolvePluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
2623
import type { ProviderAuthChoiceMetadata } from "../plugins/provider-auth-choices.js";
2724
import { createEmptyPluginRegistry } from "../plugins/registry-empty.js";
@@ -137,17 +134,12 @@ const suiteTempRootTracker = createSuiteTempRootTracker({
137134
prefix: "setup-inference-test-",
138135
});
139136
let pluginMetadataSnapshot: SystemAgentPluginMetadataTestSnapshot | undefined;
140-
let preparedPluginMetadataSnapshot: ReturnType<typeof resolvePluginMetadataSnapshot> | undefined;
141137
let inMemoryAuthProfileStores = new Map<string, AuthProfileStore>();
142138

143139
beforeAll(async () => {
144140
pluginMetadataSnapshot = installSystemAgentPluginMetadataTestSnapshot(
145141
materializedMainRuntimeConfig,
146142
);
147-
preparedPluginMetadataSnapshot = resolvePluginMetadataSnapshot({
148-
config: materializedMainRuntimeConfig,
149-
env: process.env,
150-
});
151143
cliBackendsTesting.setDepsForTest({
152144
resolvePluginSetupCliBackend: () => undefined,
153145
resolvePluginSetupRegistry: () => ({ cliBackends: [] }) as never,
@@ -302,7 +294,7 @@ function withSuiteFixtures<
302294
if (!deps.readCodexCliActiveApiKey) {
303295
deps.readCodexCliActiveApiKey = () => null;
304296
}
305-
deps.resolvePluginMetadataSnapshot ??= bindPreparedPluginMetadataSnapshot;
297+
deps.resolvePluginMetadataSnapshot ??= pluginMetadataSnapshot?.bind;
306298
if (!useRealAuthProfileStore) {
307299
deps.updateAuthProfileStoreWithLock ??= updateInMemoryAuthProfileStoreWithLock;
308300
deps.loadPersistedAuthProfileStore ??= loadInMemoryPersistedAuthProfileStore;
@@ -313,7 +305,7 @@ function withSuiteFixtures<
313305
const readConfigFileSnapshot = deps.readConfigFileSnapshot;
314306
deps.readConfigFileSnapshot = (async (...args: Parameters<typeof readConfigFileSnapshot>) => {
315307
const snapshot = await readConfigFileSnapshot(...args);
316-
bindPreparedPluginMetadataSnapshot({
308+
pluginMetadataSnapshot?.bind({
317309
config: snapshot.runtimeConfig ?? snapshot.config,
318310
env: process.env,
319311
});
@@ -440,7 +432,7 @@ async function verifySetupInferenceConfig(
440432
},
441433
): ReturnType<typeof verifySetupInferenceConfigImpl> {
442434
const { useRealAuthProfileStore = false, ...verifyParams } = params;
443-
bindPreparedPluginMetadataSnapshot({ config: verifyParams.config, env: process.env });
435+
pluginMetadataSnapshot?.bind({ config: verifyParams.config, env: process.env });
444436
return verifySetupInferenceConfigImpl({
445437
runtime,
446438
...verifyParams,
@@ -535,41 +527,6 @@ function mockCodexRuntimeInstall(installRecord?: PluginInstallRecord) {
535527
})) as never;
536528
}
537529

538-
function requirePreparedPluginMetadataSnapshot() {
539-
if (!preparedPluginMetadataSnapshot) {
540-
throw new Error("setup inference plugin metadata fixture was not initialized");
541-
}
542-
return preparedPluginMetadataSnapshot;
543-
}
544-
545-
function bindPreparedPluginMetadataSnapshot(
546-
params: Parameters<typeof resolvePluginMetadataSnapshot>[0],
547-
) {
548-
const prepared = requirePreparedPluginMetadataSnapshot();
549-
const policyHash = resolveInstalledPluginIndexPolicyHash(params.config);
550-
const index =
551-
prepared.index.policyHash === policyHash ? prepared.index : { ...prepared.index, policyHash };
552-
const snapshot = {
553-
...prepared,
554-
index,
555-
policyHash,
556-
configFingerprint: resolvePluginControlPlaneFingerprint({
557-
config: params.config,
558-
env: params.env,
559-
index,
560-
policyHash,
561-
workspaceDir: params.workspaceDir,
562-
}),
563-
...(params.workspaceDir ? { workspaceDir: params.workspaceDir } : {}),
564-
};
565-
setCurrentPluginMetadataSnapshot(snapshot, {
566-
config: params.config,
567-
env: params.env,
568-
workspaceDir: params.workspaceDir,
569-
});
570-
return snapshot;
571-
}
572-
573530
function activateCodexSetup(params: Omit<TestSetupInferenceActivationParams, "kind">) {
574531
return activateSetupInference({
575532
kind: "codex-cli",
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import type { RuntimeEnv } from "../runtime.js";
2+
3+
/** Create a RuntimeEnv that records log/error lines for tests. */
4+
export function createSystemAgentTestRuntime(): { runtime: RuntimeEnv; lines: string[] } {
5+
const lines: string[] = [];
6+
return {
7+
lines,
8+
runtime: {
9+
log: (...args) => lines.push(args.join(" ")),
10+
error: (...args) => lines.push(args.join(" ")),
11+
exit: (code) => {
12+
throw new Error(`exit ${code}`);
13+
},
14+
},
15+
};
16+
}

0 commit comments

Comments
 (0)