Skip to content

Commit f99a0c6

Browse files
authored
test: pin model-selection path behavior incl. divergences (#125727)
* test: pin turn model selection paths * test: satisfy model selection baseline gates
1 parent c9d924c commit f99a0c6

5 files changed

Lines changed: 1053 additions & 0 deletions
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
import path from "node:path";
2+
import { afterEach, describe, expect, it, vi } from "vitest";
3+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
4+
import type { SessionEntry } from "../../config/sessions/types.js";
5+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
6+
import {
7+
TURN_MODEL_DEFAULT_REF,
8+
TURN_MODEL_DIFFERENTIAL_FIXTURES,
9+
TURN_MODEL_OVERRIDE_REF,
10+
turnModelRefLabel,
11+
turnModelVerdict,
12+
type TurnModelDifferentialFixture,
13+
} from "../../test-utils/turn-model-selection-differential.js";
14+
import type { AgentCommandOpts, AgentRunContext } from "./types.js";
15+
16+
vi.mock("../agent-scope.js", () => ({
17+
clearAutoFallbackPrimaryProbeSelection: vi.fn(),
18+
hasLegacyAutoFallbackWithoutOrigin: () => false,
19+
hasSessionAutoModelFallbackProvenance: () => false,
20+
resolveAutoFallbackPrimaryProbe: () => undefined,
21+
resolveAgentConfig: () => undefined,
22+
resolveAgentEffectiveModelPrimary: () => undefined,
23+
}));
24+
vi.mock("../../channels/model-overrides.js", () => ({
25+
resolveChannelModelOverride: (params: {
26+
cfg: OpenClawConfig;
27+
channel?: string | null;
28+
groupId?: string | null;
29+
groupChatType?: string | null;
30+
groupChannel?: string | null;
31+
groupSubject?: string | null;
32+
directUserIds?: (string | null | undefined)[];
33+
}) => {
34+
const channel = params.channel?.trim().toLowerCase();
35+
const entries = channel ? params.cfg.channels?.modelByChannel?.[channel] : undefined;
36+
if (!channel || !entries) {
37+
return null;
38+
}
39+
const candidates =
40+
params.groupChatType === "direct"
41+
? [params.groupId, ...(params.directUserIds ?? [])]
42+
: [params.groupId, params.groupChannel, params.groupSubject];
43+
const matchKey = candidates.find((candidate) => candidate && entries[candidate] !== undefined);
44+
const wildcard = entries["*"];
45+
const model = matchKey ? entries[matchKey] : wildcard;
46+
return model
47+
? { channel, model, matchKey: matchKey ?? "*", matchSource: matchKey ? "exact" : "wildcard" }
48+
: null;
49+
},
50+
}));
51+
52+
vi.mock("../auth-profiles/order.js", () => ({
53+
isStoredCredentialCompatibleWithAuthProvider: () => true,
54+
}));
55+
vi.mock("../auth-profiles/session-override.js", () => ({
56+
clearSessionAuthProfileOverride: vi.fn(async () => undefined),
57+
}));
58+
vi.mock("../auth-profiles/store.js", () => ({
59+
ensureAuthProfileStore: () => ({ profiles: {} }),
60+
}));
61+
vi.mock("../harness/runtime-plugin.js", () => ({
62+
ensureSelectedAgentHarnessPlugin: vi.fn(async () => undefined),
63+
}));
64+
vi.mock("../harness/selection.js", () => ({
65+
resolveAvailableAgentHarnessPolicy: () => ({ runtime: "openclaw" }),
66+
}));
67+
vi.mock("../model-catalog.js", () => ({ loadManifestModelCatalog: () => [] }));
68+
vi.mock("../model-selection.js", () => ({
69+
modelKey: (provider: string, model: string) => `${provider}/${model}`,
70+
resolveDefaultModelForAgent: ({ cfg }: { cfg: OpenClawConfig }) => {
71+
const configured = cfg.agents?.defaults?.model;
72+
const raw =
73+
typeof configured === "string"
74+
? configured
75+
: (configured?.primary ?? turnModelRefLabel(TURN_MODEL_DEFAULT_REF));
76+
const slash = raw.indexOf("/");
77+
return slash > 0
78+
? { provider: raw.slice(0, slash), model: raw.slice(slash + 1) }
79+
: { provider: TURN_MODEL_DEFAULT_REF.provider, model: raw };
80+
},
81+
resolveModelAliasFromPair: () => null,
82+
resolveThinkingDefault: () => "off",
83+
}));
84+
vi.mock("../model-thinking-default.js", () => ({
85+
resolveConfiguredThinkingDefault: () => undefined,
86+
}));
87+
vi.mock("../model-visibility-policy.js", () => ({
88+
createModelVisibilityPolicy: () => ({
89+
allowAny: true,
90+
allowedCatalog: [],
91+
selectionAliasIndex: { byAlias: new Map(), byKey: new Map() },
92+
allowsKey: () => true,
93+
resolveSelection: (ref: { provider: string; model: string }) => ref,
94+
}),
95+
}));
96+
vi.mock("../openai-routing.js", () => ({
97+
listOpenAIAuthProfileProvidersForAgentRuntime: ({ provider }: { provider: string }) => [provider],
98+
}));
99+
vi.mock("../provider-auth-aliases.js", () => ({
100+
resolveProviderIdForAuth: (provider: string) => provider,
101+
}));
102+
vi.mock("../session-runtime-compat.js", () => ({
103+
resolveSessionRuntimeOverrideForProvider: () => undefined,
104+
}));
105+
vi.mock("../thinking-runtime.js", () => ({
106+
hasResolvedThinkingCatalogEntry: () => false,
107+
normalizeThinkingCatalogProviders: (catalog: unknown) => catalog,
108+
resolveEffectiveAgentRuntime: () => undefined,
109+
}));
110+
vi.mock("../../plugins/runtime.js", () => ({ requireActivePluginRegistry: () => ({}) }));
111+
vi.mock("../../sessions/agent-harness-session-key.js", () => ({
112+
isValidAgentHarnessSessionStoreEntry: () => false,
113+
}));
114+
vi.mock("../../sessions/model-overrides.js", () => ({
115+
applyModelOverrideToSessionEntry: () => ({ updated: false }),
116+
isModelSelectionLocked: (entry?: SessionEntry) => entry?.modelSelectionLocked === true,
117+
ModelSelectionLockedError: class ModelSelectionLockedError extends Error {},
118+
repairProviderWrappedModelOverride: () => ({ updated: false }),
119+
}));
120+
vi.mock("./attempt-execution.shared.js", () => ({
121+
persistAgentSession: async ({ entry }: { entry?: SessionEntry }) => entry,
122+
}));
123+
vi.mock("./model-ref.js", () => ({
124+
normalizeAgentCommandDefaultModelRef: (
125+
_cfg: OpenClawConfig,
126+
provider: string,
127+
model: string,
128+
) => ({ provider, model }),
129+
normalizeAgentCommandModelRef: (_cfg: OpenClawConfig, provider: string, model: string) => ({
130+
provider,
131+
model,
132+
}),
133+
parseAgentCommandModelRef: (_cfg: OpenClawConfig, raw: string, defaultProvider: string) => {
134+
const slash = raw.indexOf("/");
135+
return slash > 0
136+
? { provider: raw.slice(0, slash), model: raw.slice(slash + 1) }
137+
: { provider: defaultProvider, model: raw };
138+
},
139+
}));
140+
vi.mock("./prepare.js", () => ({
141+
normalizeExplicitOverrideInput: (value: string) => value.trim() || undefined,
142+
}));
143+
vi.mock("./runtime-loaders.js", () => ({
144+
loadTranscriptResolveRuntime: async () => ({
145+
resolveSessionTranscriptFile: async (params: { sessionEntry?: SessionEntry }) => ({
146+
sessionEntry: params.sessionEntry,
147+
sessionFile: "/tmp/turn-model-session.jsonl",
148+
}),
149+
}),
150+
}));
151+
152+
const { resolveEmbeddedModelSelection } = await import("./model-selection.js");
153+
154+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
155+
156+
function createConfig(fixture: TurnModelDifferentialFixture): OpenClawConfig {
157+
return {
158+
agents: { defaults: { model: { primary: turnModelRefLabel(TURN_MODEL_DEFAULT_REF) } } },
159+
channels: fixture.modelByChannel ? { modelByChannel: fixture.modelByChannel } : undefined,
160+
} as OpenClawConfig;
161+
}
162+
163+
async function observeCommandSelection(fixture: TurnModelDifferentialFixture) {
164+
const sessionKey = "agent:main:telegram:group:selection";
165+
const sessionStore: Record<string, SessionEntry> = { [sessionKey]: fixture.child };
166+
if (fixture.parent) {
167+
sessionStore[fixture.parent.key] = fixture.parent.entry;
168+
}
169+
const opts: AgentCommandOpts = {
170+
message: "hello",
171+
to: "target",
172+
channel: fixture.ctx.Provider,
173+
messageChannel: fixture.ctx.Provider,
174+
groupId: fixture.child.groupId,
175+
groupChannel: fixture.child.groupChannel,
176+
...(fixture.heartbeat
177+
? {
178+
provider: TURN_MODEL_OVERRIDE_REF.provider,
179+
model: TURN_MODEL_OVERRIDE_REF.model,
180+
allowModelOverride: true,
181+
}
182+
: {}),
183+
};
184+
const runContext: AgentRunContext = {
185+
messageChannel: fixture.ctx.Provider,
186+
groupId: fixture.child.groupId,
187+
groupChannel: fixture.child.groupChannel,
188+
currentChannelId: "target",
189+
};
190+
const selection = await resolveEmbeddedModelSelection({
191+
cfg: createConfig(fixture),
192+
opts,
193+
sessionEntry: fixture.child,
194+
sessionStore,
195+
sessionKey,
196+
sessionId: fixture.child.sessionId,
197+
storePath: path.join(tempDirs.make("turn-model-command-"), "sessions.json"),
198+
sessionAgentId: "main",
199+
workspaceDir: tempDirs.make("turn-model-command-workspace-"),
200+
pluginsEnabled: false,
201+
modelManifestContext: {},
202+
configuredThinkingCatalog: [],
203+
isSubagentLane: false,
204+
suppressVisibleSessionEffects: true,
205+
runContext,
206+
});
207+
return turnModelVerdict(
208+
{ provider: selection.provider, model: selection.model },
209+
fixture.locked ? "locked" : fixture.heartbeat ? "explicit" : undefined,
210+
);
211+
}
212+
213+
describe("turn model selection command-path differential", () => {
214+
it.each(TURN_MODEL_DIFFERENTIAL_FIXTURES)("pins observed $name behavior", async (fixture) => {
215+
await expect(observeCommandSelection(fixture)).resolves.toEqual(fixture.expected.command);
216+
});
217+
});
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import path from "node:path";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
4+
import type { AgentHarness } from "../../agents/harness/types.js";
5+
import { replaceSessionEntrySync } from "../../config/sessions/session-accessor.js";
6+
import type { SessionEntry } from "../../config/sessions/types.js";
7+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
8+
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../../plugins/runtime.js";
9+
import { createSessionConversationTestRegistry } from "../../test-utils/session-conversation-registry.js";
10+
import {
11+
TURN_MODEL_DEFAULT_REF,
12+
TURN_MODEL_DIFFERENTIAL_FIXTURES,
13+
TURN_MODEL_OVERRIDE_REF,
14+
turnModelRefLabel,
15+
turnModelVerdict,
16+
type TurnModelDifferentialFixture,
17+
type TurnModelSelectionVerdict,
18+
} from "../../test-utils/turn-model-selection-differential.js";
19+
import { buildTestCtx } from "./test-ctx.js";
20+
21+
const selectAgentHarnessMock = vi.hoisted(() => vi.fn());
22+
23+
vi.mock("../../agents/harness/selection.js", async (importOriginal) => {
24+
const actual = await importOriginal<typeof import("../../agents/harness/selection.js")>();
25+
return {
26+
...actual,
27+
selectAgentHarness: (...args: unknown[]) => selectAgentHarnessMock(...args),
28+
};
29+
});
30+
31+
const { resolveVisibleRepliesPolicy } = await import("./dispatch-from-config.harness-defaults.js");
32+
33+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
34+
35+
const recorderHarness = {
36+
id: "turn-model-recorder",
37+
label: "Turn model recorder",
38+
deliveryDefaults: { visibleReplies: "automatic" },
39+
supports: () => ({ supported: true as const, priority: 1 }),
40+
runAttempt: vi.fn(async () => ({}) as never),
41+
} satisfies AgentHarness;
42+
43+
function createConfig(
44+
storePath: string,
45+
modelByChannel: TurnModelDifferentialFixture["modelByChannel"],
46+
): OpenClawConfig {
47+
return {
48+
session: { store: storePath },
49+
agents: { defaults: { model: { primary: turnModelRefLabel(TURN_MODEL_DEFAULT_REF) } } },
50+
channels: modelByChannel ? { modelByChannel } : undefined,
51+
} as OpenClawConfig;
52+
}
53+
54+
function observeHarnessSelection(fixture: TurnModelDifferentialFixture): TurnModelSelectionVerdict {
55+
const storePath = path.join(tempDirs.make("turn-model-harness-"), "sessions.json");
56+
const sessionKey = "agent:main:telegram:group:selection";
57+
replaceSessionEntrySync({ agentId: "main", storePath, sessionKey }, fixture.child);
58+
const sessionStore: Record<string, SessionEntry> = { [sessionKey]: fixture.child };
59+
if (fixture.parent) {
60+
replaceSessionEntrySync(
61+
{ agentId: "main", storePath, sessionKey: fixture.parent.key },
62+
fixture.parent.entry,
63+
);
64+
sessionStore[fixture.parent.key] = fixture.parent.entry;
65+
}
66+
67+
selectAgentHarnessMock.mockClear();
68+
resolveVisibleRepliesPolicy({
69+
cfg: createConfig(storePath, fixture.modelByChannel),
70+
// Visible-reply defaults are queried only for direct delivery. The stored
71+
// chat type still drives the real channel matcher for group fixtures.
72+
chatType: "direct",
73+
ctx: buildTestCtx({ SessionKey: sessionKey, ...fixture.ctx }),
74+
entry: fixture.child,
75+
sessionAgentId: "main",
76+
sessionKey,
77+
sessionStore,
78+
turnModelOverride: fixture.heartbeat ? turnModelRefLabel(TURN_MODEL_OVERRIDE_REF) : undefined,
79+
});
80+
const call = selectAgentHarnessMock.mock.calls.at(-1)?.[0] as
81+
| { provider: string; modelId?: string }
82+
| undefined;
83+
if (!call?.modelId) {
84+
throw new Error(`harness path did not select a model for ${fixture.name}`);
85+
}
86+
return turnModelVerdict(
87+
{ provider: call.provider, model: call.modelId },
88+
fixture.locked ? "locked" : undefined,
89+
);
90+
}
91+
92+
describe("turn model selection harness-path differential", () => {
93+
beforeEach(() => {
94+
resetPluginRuntimeStateForTest();
95+
setActivePluginRegistry(createSessionConversationTestRegistry());
96+
selectAgentHarnessMock.mockImplementation(() => recorderHarness);
97+
});
98+
99+
afterEach(() => {
100+
resetPluginRuntimeStateForTest();
101+
});
102+
103+
it.each(TURN_MODEL_DIFFERENTIAL_FIXTURES)("pins observed $name behavior", (fixture) => {
104+
expect(observeHarnessSelection(fixture)).toEqual(fixture.expected.harness);
105+
});
106+
});

0 commit comments

Comments
 (0)