Skip to content

Commit ee13bb9

Browse files
committed
fix: keep model-resolution tests inside owned state
1 parent 6b68a4a commit ee13bb9

11 files changed

Lines changed: 658 additions & 347 deletions

‎src/agents/btw.test.ts‎

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import { expectDefined } from "@openclaw/normalization-core";
44
import { MAX_TIMER_TIMEOUT_MS } from "@openclaw/normalization-core/number-coercion";
5-
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
66
import type { SessionEntry } from "../config/sessions.js";
77
import type { ProviderResolveModelRoutesContext } from "../plugin-sdk/provider-model-types.js";
88
import { getCurrentPluginMetadataSnapshot } from "../plugins/current-plugin-metadata-snapshot.js";
@@ -14,16 +14,40 @@ import {
1414
mintSecretSentinel,
1515
resolveSecretSentinel,
1616
} from "../secrets/sentinel.js";
17+
import {
18+
createOpenClawTestState,
19+
type OpenClawTestState,
20+
} from "../test-utils/openclaw-test-state.js";
21+
import { guardModelFixtureWorkspace } from "./embedded-agent-runner/model.fixture.test-support.js";
1722
import {
1823
createModelGenerationFixture,
19-
GENERATION_WORKSPACE_DIR,
2024
publishCurrentModelGeneration,
2125
resetModelGenerationFixtureState,
2226
} from "./embedded-agent-runner/model.generation-scope.test-support.js";
2327
import type { AgentHarnessHostCapabilities } from "./harness/host-capability-types.js";
2428
import type { AgentHarness } from "./harness/types.js";
2529
import type { AgentRuntimeAuthPlan } from "./runtime-plan/types.js";
2630

31+
let state: OpenClawTestState;
32+
let workspaceGuard: ReturnType<typeof guardModelFixtureWorkspace>;
33+
beforeAll(async () => {
34+
state = await createOpenClawTestState({ label: "btw-model" });
35+
});
36+
beforeEach(() => {
37+
workspaceGuard = guardModelFixtureWorkspace(state.root);
38+
});
39+
afterEach(() => {
40+
try {
41+
workspaceGuard.verify();
42+
} finally {
43+
workspaceGuard.spy.mockRestore();
44+
}
45+
});
46+
afterAll(async () => {
47+
defaultPluginMetadataSnapshot = undefined;
48+
await state.cleanup();
49+
});
50+
2751
const streamSimpleMock = vi.fn();
2852
const readFileMock = vi.fn();
2953
const parseSessionEntriesMock = vi.fn();
@@ -728,11 +752,16 @@ describe("runBtwSideQuestion", () => {
728752
resolveProviderEntryApiKeyProfileReferenceMock.mockReset();
729753
resolveProviderEntryApiKeyProfileReferenceMock.mockReturnValue({ kind: "none" });
730754
clearAgentHarnesses();
731-
defaultPluginMetadataSnapshot ??= resolvePluginMetadataSnapshot({
732-
config: {},
733-
workspaceDir: "/tmp/workspace",
734-
allowCurrent: false,
735-
});
755+
if (!defaultPluginMetadataSnapshot) {
756+
defaultPluginMetadataSnapshot = resolvePluginMetadataSnapshot({
757+
config: {},
758+
workspaceDir: state.workspaceDir,
759+
allowCurrent: false,
760+
});
761+
expect(workspaceGuard.spy).toHaveBeenCalledWith(
762+
expect.objectContaining({ workspaceDir: state.workspaceDir }),
763+
);
764+
}
736765
preparedRuntimeSnapshotState.snapshot = {
737766
metadataSnapshot: defaultPluginMetadataSnapshot,
738767
};
@@ -916,13 +945,17 @@ describe("runBtwSideQuestion", () => {
916945
it("keeps model, runtime auth, and stream selection on prepared A after current advances to B", async () => {
917946
const cfg = { agents: { entries: { main: { default: true } } } } as never;
918947
const generationA = createModelGenerationFixture({
948+
agentDir: state.agentDir(),
949+
workspaceDir: state.workspaceDir,
919950
config: cfg,
920951
label: "btw-a",
921952
provider: "local-proxy",
922953
requestProvider: "local-proxy",
923954
modelId: "side-model",
924955
});
925956
const generationB = createModelGenerationFixture({
957+
agentDir: state.agentDir(),
958+
workspaceDir: state.workspaceDir,
926959
config: cfg,
927960
label: "btw-b",
928961
provider: "local-proxy",
@@ -931,7 +964,7 @@ describe("runBtwSideQuestion", () => {
931964
});
932965
preparedRuntimeSnapshotState.snapshot = generationA.preparedModelRuntime;
933966
preparedRuntimeSnapshotState.useSnapshotPluginRegistry = true;
934-
resolveAgentWorkspaceDirMock.mockReturnValue(GENERATION_WORKSPACE_DIR);
967+
resolveAgentWorkspaceDirMock.mockReturnValue(state.workspaceDir);
935968
publishCurrentModelGeneration(generationB);
936969
const runtimeAuthA = vi.fn(async () => ({ apiKey: "runtime-auth-a" }));
937970
const runtimeAuthB = vi.fn(async () => ({ apiKey: "runtime-auth-b" }));
@@ -953,7 +986,7 @@ describe("runBtwSideQuestion", () => {
953986
resolveModelWithRegistryMock.mockImplementation(() => {
954987
const snapshot = getCurrentPluginMetadataSnapshot({
955988
config: cfg,
956-
workspaceDir: GENERATION_WORKSPACE_DIR,
989+
workspaceDir: state.workspaceDir,
957990
});
958991
const label = snapshot === generationA.metadataSnapshot ? "A" : "B";
959992
return {

‎src/agents/command/cli-compaction.test.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
5+
import { expectDefined } from "@openclaw/normalization-core";
56
import { CURRENT_SESSION_VERSION } from "openclaw/plugin-sdk/agent-sessions";
67
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
78
import { replaceSessionEntry } from "../../config/sessions/session-accessor.js";
@@ -119,13 +120,16 @@ function createPreparedRuntimeLease(input: {
119120
agentId?: string;
120121
workspaceDir?: string;
121122
}) {
122-
const prepared = createModelGenerationFixture({ config: input.config, label: "cli" });
123+
const prepared = createModelGenerationFixture({
124+
config: input.config,
125+
label: "cli",
126+
agentDir: input.agentDir,
127+
workspaceDir: expectDefined(input.workspaceDir, "compaction fixture workspace"),
128+
});
123129
return {
124130
snapshot: {
125131
...prepared.preparedModelRuntime,
126132
...(input.agentId ? { agentId: input.agentId } : {}),
127-
agentDir: input.agentDir,
128-
...(input.workspaceDir ? { workspaceDir: input.workspaceDir } : {}),
129133
},
130134
pluginGeneration: {
131135
configuredCatalogEntries: [],
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { expect, vi } from "vitest";
2+
import { isPathInside } from "../../infra/path-guards.js";
3+
import * as pluginDiscovery from "../../plugins/discovery.js";
4+
import * as authProfileStore from "../auth-profiles/store.js";
5+
6+
export function guardModelFixtureAuth(root: string) {
7+
const violations: Array<string | undefined> = [];
8+
const ensureAuthProfileStore = authProfileStore.ensureAuthProfileStore;
9+
const spy = vi
10+
.spyOn(authProfileStore, "ensureAuthProfileStore")
11+
.mockImplementation((dir, options) => {
12+
// Discovery stores and prepared metadata do not bypass native auth reads.
13+
// Record even swallowed violations before the owner can inspect the path.
14+
if (!dir || !isPathInside(root, dir)) {
15+
violations.push(dir);
16+
throw new Error("Auth profile request escaped the model fixture");
17+
}
18+
return ensureAuthProfileStore(dir, options);
19+
});
20+
return { spy, verify: () => expect(violations).toEqual([]) };
21+
}
22+
23+
export function guardModelFixtureWorkspace(root: string) {
24+
const violations: string[] = [];
25+
const discoverOpenClawPlugins = pluginDiscovery.discoverOpenClawPlugins;
26+
const spy = vi.spyOn(pluginDiscovery, "discoverOpenClawPlugins").mockImplementation((params) => {
27+
// This is before discovery's realpath/stat probes; bundled roots remain real.
28+
if (params.workspaceDir && !isPathInside(root, params.workspaceDir)) {
29+
violations.push(params.workspaceDir);
30+
throw new Error("Workspace discovery escaped the model fixture");
31+
}
32+
return discoverOpenClawPlugins(params);
33+
});
34+
return { spy, verify: () => expect(violations).toEqual([]) };
35+
}

‎src/agents/embedded-agent-runner/model.forward-compat.test.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,33 @@
11
// Coverage for registry-backed model forward-compatibility fallbacks.
2-
import { describe, it, vi } from "vitest";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
import {
4+
createOpenClawTestState,
5+
type OpenClawTestState,
6+
} from "../../test-utils/openclaw-test-state.js";
7+
import { guardModelFixtureAuth } from "./model.fixture.test-support.js";
38
import {
49
buildForwardCompatTemplate,
510
expectResolvedForwardCompatFallbackWithRegistryResult,
611
} from "./model.forward-compat.test-support.js";
712
import { resolveModelWithRegistry } from "./model.js";
813
import { createProviderRuntimeTestMock } from "./model.provider-runtime.test-support.js";
914

15+
let state: OpenClawTestState;
16+
let auth: ReturnType<typeof guardModelFixtureAuth>;
17+
beforeEach(async () => {
18+
state = await createOpenClawTestState({ label: "model-forward-compat" });
19+
auth = guardModelFixtureAuth(state.root);
20+
});
21+
afterEach(async () => {
22+
try {
23+
auth.verify();
24+
expect(auth.spy).toHaveBeenCalled();
25+
} finally {
26+
auth.spy.mockRestore();
27+
await state.cleanup();
28+
}
29+
});
30+
1031
vi.mock("../../plugins/provider-runtime.js", () => ({
1132
applyProviderResolvedTransportWithPlugin: () => undefined,
1233
buildProviderUnknownModelHintWithPlugin: () => undefined,
@@ -105,7 +126,7 @@ function runAnthropicOpusForwardCompatFallback() {
105126
result: resolveModelWithRegistry({
106127
provider: "anthropic",
107128
modelId: "claude-opus-4-6",
108-
agentDir: "/tmp/agent",
129+
agentDir: state.agentDir(),
109130
modelRegistry: createRegistry([
110131
{
111132
provider: "anthropic",
@@ -124,7 +145,7 @@ function runAnthropicSonnetForwardCompatFallback() {
124145
result: resolveModelWithRegistry({
125146
provider: "anthropic",
126147
modelId: "claude-sonnet-4-6",
127-
agentDir: "/tmp/agent",
148+
agentDir: state.agentDir(),
128149
modelRegistry: createRegistry([
129150
{
130151
provider: "anthropic",
@@ -145,7 +166,7 @@ function runClaudeCliSonnetForwardCompatFallback() {
145166
result: resolveModelWithRegistry({
146167
provider: "claude-cli",
147168
modelId: "claude-sonnet-4-6",
148-
agentDir: "/tmp/agent",
169+
agentDir: state.agentDir(),
149170
modelRegistry: createRegistry([
150171
{
151172
provider: "anthropic",
@@ -166,7 +187,7 @@ function runZaiForwardCompatFallback() {
166187
const result = resolveModelWithRegistry({
167188
provider: ZAI_GLM5_CASE.provider,
168189
modelId: ZAI_GLM5_CASE.id,
169-
agentDir: "/tmp/agent",
190+
agentDir: state.agentDir(),
170191
modelRegistry: createRegistry(
171192
ZAI_GLM5_CASE.registryEntries.map((entry) => ({
172193
provider: entry.provider,

‎src/agents/embedded-agent-runner/model.generation-scope.test-support.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,12 @@ import { AuthStorage, ModelRegistry } from "../sessions/index.js";
1212

1313
const GENERATION_MODEL_ID = "generation-model";
1414
const GENERATION_REQUEST_PROVIDER = "generation-alias";
15-
export const GENERATION_WORKSPACE_DIR = "/tmp/openclaw-model-generation-scope";
1615

1716
type ImagePolicy = NonNullable<NonNullable<ProviderRuntimeModel["mediaInput"]>["image"]>;
1817

1918
export function createModelGenerationFixture(params: {
19+
agentDir: string;
20+
workspaceDir: string;
2021
config: OpenClawConfig;
2122
createStores?: PreparedModelRuntimeSnapshot["createStores"];
2223
label: string;
@@ -73,7 +74,7 @@ export function createModelGenerationFixture(params: {
7374
const metadataSnapshot = createPluginMetadataSnapshot({
7475
config: params.config,
7576
manifestRegistry: { plugins: [plugin], diagnostics: [] },
76-
workspaceDir: GENERATION_WORKSPACE_DIR,
77+
workspaceDir: params.workspaceDir,
7778
});
7879
const pluginRegistry = createEmptyPluginRegistry();
7980
const resolveDynamicModel = vi.fn(() => ({
@@ -108,8 +109,8 @@ export function createModelGenerationFixture(params: {
108109
});
109110
const preparedModelRuntime = {
110111
catalogOwner: undefined,
111-
agentDir: "/tmp/openclaw-model-generation-agent",
112-
workspaceDir: GENERATION_WORKSPACE_DIR,
112+
agentDir: params.agentDir,
113+
workspaceDir: params.workspaceDir,
113114
activeProjectKeys: [],
114115
config: params.config,
115116
authModes: {},
@@ -139,13 +140,13 @@ export function publishCurrentModelGeneration(
139140
): void {
140141
setCurrentPluginMetadataSnapshot(generation.metadataSnapshot, {
141142
config: generation.preparedModelRuntime.config,
142-
workspaceDir: GENERATION_WORKSPACE_DIR,
143+
workspaceDir: generation.preparedModelRuntime.workspaceDir,
143144
});
144145
setActivePluginRegistry(
145146
generation.pluginRegistry,
146147
`generation-${generation.provider}`,
147148
"default",
148-
GENERATION_WORKSPACE_DIR,
149+
generation.preparedModelRuntime.workspaceDir,
149150
);
150151
}
151152

0 commit comments

Comments
 (0)