Skip to content

Commit c2e2b56

Browse files
committed
fix: show effective channel model in Telegram status
1 parent f32a266 commit c2e2b56

2 files changed

Lines changed: 352 additions & 5 deletions

File tree

Lines changed: 293 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,293 @@
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 * as preparedModelCatalog from "../../agents/prepared-model-catalog.js";
5+
import type { OpenClawConfig } from "../../config/config.js";
6+
import { replaceSessionEntry } from "../../config/sessions/session-accessor.js";
7+
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../../plugins/runtime.js";
8+
import { createSessionConversationTestRegistry } from "../../test-utils/session-conversation-registry.js";
9+
import { normalizeSessionDeliveryState } from "../../utils/delivery-context.shared.js";
10+
import { markCompleteReplyConfig } from "./get-reply-fast-path.test-support.js";
11+
import { buildTestCtx } from "./test-ctx.js";
12+
import type { TypingController } from "./typing.js";
13+
14+
type NativeStatusSelectionCase = {
15+
selection: string;
16+
source: "user" | "auto" | undefined;
17+
channelModel?: string;
18+
deliveryChannel?: string;
19+
directSenderId?: string;
20+
directUserId?: string;
21+
expectedModel?: string;
22+
expectedProvider?: string;
23+
groupId?: string;
24+
locked?: boolean;
25+
modelParentSessionKey?: string;
26+
preparedModel?: string;
27+
preparedProvider?: string;
28+
};
29+
30+
const buildStatusReplyMock = vi.hoisted(() => vi.fn());
31+
32+
vi.mock("./commands-status.js", () => ({
33+
buildStatusReply: (...args: unknown[]) => buildStatusReplyMock(...args),
34+
}));
35+
36+
const { maybeResolveNativeSlashCommandFastReply } =
37+
await import("./get-reply-native-slash-fast-path.js");
38+
39+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
40+
41+
const createTypingController = (): TypingController => ({
42+
onReplyStart: async () => {},
43+
startTypingLoop: async () => {},
44+
startTypingOnText: async () => {},
45+
refreshTypingTtl: () => {},
46+
isActive: () => false,
47+
markRunComplete: () => {},
48+
markDispatchIdle: () => {},
49+
cleanup: vi.fn(),
50+
});
51+
52+
describe("native /status channel model routing", () => {
53+
beforeEach(() => {
54+
vi.restoreAllMocks();
55+
vi.stubEnv("OPENCLAW_TEST_FAST", "1");
56+
resetPluginRuntimeStateForTest();
57+
setActivePluginRegistry(createSessionConversationTestRegistry());
58+
vi.spyOn(preparedModelCatalog, "loadPreparedModelCatalog").mockResolvedValue([
59+
{
60+
id: "gpt-5.5",
61+
name: "GPT",
62+
provider: "openai",
63+
contextWindow: 400_000,
64+
reasoning: false,
65+
},
66+
{
67+
id: "claude-fable-5",
68+
name: "Fable",
69+
provider: "anthropic",
70+
contextWindow: 1_000_000,
71+
reasoning: true,
72+
},
73+
]);
74+
buildStatusReplyMock.mockReset();
75+
buildStatusReplyMock.mockResolvedValue({ text: "selected model status" });
76+
});
77+
78+
const statusSelectionCases: NativeStatusSelectionCase[] = [
79+
{ selection: "user override", source: "user" },
80+
{ selection: "automatic fallback", source: "auto" },
81+
{
82+
selection: "channel override",
83+
source: undefined,
84+
expectedProvider: "anthropic",
85+
expectedModel: "claude-fable-5",
86+
},
87+
{
88+
selection: "configured channel model alias",
89+
source: undefined,
90+
channelModel: "Fable",
91+
expectedProvider: "anthropic",
92+
expectedModel: "claude-fable-5",
93+
},
94+
{
95+
selection: "current command channel over stale session delivery",
96+
source: undefined,
97+
deliveryChannel: "discord",
98+
expectedProvider: "anthropic",
99+
expectedModel: "claude-fable-5",
100+
},
101+
{
102+
selection: "parent group override for a topic",
103+
source: undefined,
104+
groupId: "123:topic:77",
105+
expectedProvider: "anthropic",
106+
expectedModel: "claude-fable-5",
107+
},
108+
{
109+
selection: "thread-only model parent session override",
110+
source: undefined,
111+
groupId: "unmatched-thread",
112+
modelParentSessionKey: "agent:main:telegram:group:123:thread:77",
113+
expectedProvider: "anthropic",
114+
expectedModel: "claude-fable-5",
115+
},
116+
{
117+
selection: "native direct peer override before wildcard",
118+
source: undefined,
119+
directUserId: "native-peer-42",
120+
expectedProvider: "anthropic",
121+
expectedModel: "claude-fable-5",
122+
},
123+
{
124+
selection: "current direct sender override before wildcard",
125+
source: undefined,
126+
directSenderId: "live-peer-43",
127+
expectedProvider: "anthropic",
128+
expectedModel: "claude-fable-5",
129+
},
130+
{
131+
selection: "current direct sender over another channel's persisted peer",
132+
source: undefined,
133+
deliveryChannel: "discord",
134+
directUserId: "stale-discord-peer",
135+
directSenderId: "live-telegram-peer",
136+
expectedProvider: "anthropic",
137+
expectedModel: "claude-fable-5",
138+
},
139+
{
140+
selection: "locked model selection",
141+
source: undefined,
142+
locked: true,
143+
},
144+
{
145+
selection: "prepared non-default heartbeat or fallback model",
146+
source: undefined,
147+
preparedProvider: "xai",
148+
preparedModel: "grok-4.3",
149+
expectedProvider: "xai",
150+
expectedModel: "grok-4.3",
151+
},
152+
];
153+
154+
it.each(statusSelectionCases)(
155+
"preserves canonical native /status $selection",
156+
async (testCase) => {
157+
const targetSessionKey = "agent:main:main";
158+
const storePath = path.join(tempDirs.make("openclaw-native-status-"), "sessions.json");
159+
const {
160+
channelModel = "anthropic/claude-fable-5",
161+
deliveryChannel = "telegram",
162+
directSenderId,
163+
directUserId,
164+
expectedModel = "gpt-5.5",
165+
expectedProvider = "openai",
166+
groupId = "123",
167+
locked = false,
168+
modelParentSessionKey,
169+
preparedModel = "gpt-5.5",
170+
preparedProvider = "openai",
171+
source,
172+
} = testCase;
173+
const isDirect = directUserId !== undefined || directSenderId !== undefined;
174+
const overrideKey = directSenderId ?? directUserId ?? "123";
175+
const conflictingDirectUserId =
176+
directSenderId !== undefined && directUserId !== undefined ? directUserId : undefined;
177+
await replaceSessionEntry(
178+
{ agentId: "main", sessionKey: targetSessionKey, storePath },
179+
{
180+
sessionId: "status-session",
181+
updatedAt: Date.now(),
182+
contextTokens: 1_000_000,
183+
delivery: normalizeSessionDeliveryState({
184+
context: { channel: deliveryChannel },
185+
...(directUserId
186+
? { origin: { provider: deliveryChannel, nativeDirectUserId: directUserId } }
187+
: {}),
188+
}),
189+
...(isDirect ? {} : { groupId }),
190+
...(locked ? { modelSelectionLocked: true } : {}),
191+
...(source
192+
? {
193+
providerOverride: "anthropic",
194+
modelOverride: "claude-fable-5",
195+
modelOverrideSource: source,
196+
...(source === "auto"
197+
? {
198+
modelOverrideFallbackOriginProvider: "openai",
199+
modelOverrideFallbackOriginModel: "gpt-5.5",
200+
modelProvider: "openai",
201+
model: "gpt-5.5",
202+
}
203+
: {}),
204+
}
205+
: {}),
206+
},
207+
);
208+
209+
const result = await maybeResolveNativeSlashCommandFastReply({
210+
ctx: buildTestCtx({
211+
Body: "/status",
212+
CommandBody: "/status",
213+
CommandSource: "native",
214+
CommandAuthorized: true,
215+
Provider: "telegram",
216+
Surface: "telegram",
217+
ChatType: isDirect ? "direct" : "group",
218+
...(directSenderId
219+
? { From: `telegram:${directSenderId}`, SenderId: directSenderId }
220+
: {}),
221+
...(modelParentSessionKey ? { ModelParentSessionKey: modelParentSessionKey } : {}),
222+
SessionKey: "telegram:slash:123",
223+
CommandTargetSessionKey: targetSessionKey,
224+
CommandTurn: {
225+
kind: "native",
226+
source: "native",
227+
authorized: true,
228+
commandName: "status",
229+
body: "/status",
230+
},
231+
}),
232+
cfg: markCompleteReplyConfig({
233+
session: { store: storePath },
234+
agents: {
235+
defaults: {
236+
model: { primary: "openai/gpt-5.5" },
237+
modelPolicy: { allow: ["openai/*", "anthropic/*", "xai/*"] },
238+
models: {
239+
"anthropic/claude-fable-5": {
240+
alias: "Fable",
241+
params: { thinking: "high", fastMode: true },
242+
},
243+
},
244+
},
245+
},
246+
channels: {
247+
modelByChannel: {
248+
telegram: {
249+
[overrideKey]: channelModel,
250+
...(conflictingDirectUserId ? { [conflictingDirectUserId]: "xai/grok-4.3" } : {}),
251+
"*": "openai/gpt-5.5",
252+
},
253+
discord: { "123": "openai/gpt-5.5" },
254+
},
255+
},
256+
} as OpenClawConfig),
257+
agentId: "main",
258+
agentDir: "/tmp/agent",
259+
agentCfg: undefined,
260+
commandAuthorized: true,
261+
defaultProvider: "openai",
262+
defaultModel: "gpt-5.5",
263+
aliasIndex: {
264+
byKey: new Map(),
265+
byAlias: new Map([
266+
["fable", { alias: "Fable", ref: { provider: "anthropic", model: "claude-fable-5" } }],
267+
]),
268+
},
269+
provider: preparedProvider,
270+
model: preparedModel,
271+
workspaceDir: "/tmp/workspace",
272+
typing: createTypingController(),
273+
});
274+
275+
const statusCall = buildStatusReplyMock.mock.calls[0]?.[0];
276+
expect(statusCall).toMatchObject({ provider: expectedProvider, model: expectedModel });
277+
if (expectedProvider === "anthropic") {
278+
await expect(statusCall.resolveDefaultThinkingLevel()).resolves.toBe("high");
279+
}
280+
if (source) {
281+
expect(statusCall.sessionEntry).toMatchObject({
282+
providerOverride: "anthropic",
283+
modelOverride: "claude-fable-5",
284+
modelOverrideSource: source,
285+
});
286+
} else {
287+
expect(statusCall.sessionEntry).not.toHaveProperty("providerOverride");
288+
expect(statusCall.sessionEntry).not.toHaveProperty("modelOverride");
289+
}
290+
expect(result).toMatchObject({ reply: { text: "selected model status" } });
291+
},
292+
);
293+
});

‎src/auto-reply/reply/get-reply-native-slash-fast-path.ts‎

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
11
// Handles native slash commands before full get-reply pipeline execution.
22
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
33
import {
4+
resolveModelRefFromString,
45
resolveThinkingDefaultWithRuntimeCatalog,
56
type ModelAliasIndex,
67
} from "../../agents/model-selection.js";
78
import { loadPreparedModelCatalog } from "../../agents/prepared-model-catalog.js";
9+
import { resolveChannelModelOverride } from "../../channels/model-overrides.js";
810
import type { OpenClawConfig } from "../../config/config.js";
11+
import { isModelSelectionLocked } from "../../sessions/model-overrides.js";
912
import { recordSessionCreated } from "../../sessions/session-state-events.js";
1013
import { createLazyImportLoader } from "../../shared/lazy-promise.js";
1114
import type { SkillCommandSpec } from "../../skills/types.js";
12-
import { isInternalMessageChannel } from "../../utils/message-channel.js";
15+
import {
16+
sessionDeliveryChannel,
17+
sessionDeliveryOrigin,
18+
} from "../../utils/delivery-context.shared.js";
19+
import { isInternalMessageChannel, normalizeMessageChannel } from "../../utils/message-channel.js";
1320
import {
1421
isAuthorizedTextSlashCommandTurn,
1522
isNativeCommandTurn,
@@ -194,13 +201,60 @@ export async function maybeResolveNativeSlashCommandFastReply(params: {
194201
if (command.commandBodyNormalized === "/status") {
195202
const targetSessionEntry =
196203
sessionState.sessionStore[sessionState.sessionKey] ?? sessionState.sessionEntry;
204+
const canApplyChannelModel =
205+
params.cfg.channels?.modelByChannel &&
206+
!isModelSelectionLocked(targetSessionEntry) &&
207+
!normalizeOptionalString(targetSessionEntry?.modelOverride) &&
208+
!normalizeOptionalString(targetSessionEntry?.providerOverride) &&
209+
params.provider === params.defaultProvider &&
210+
params.model === params.defaultModel;
211+
const deliveryChannel = normalizeMessageChannel(sessionDeliveryChannel(targetSessionEntry));
212+
// Shared sessions can retain another channel's peer; never let that stale
213+
// identity outrank the authorized current command's live sender.
214+
const deliveryOrigin =
215+
deliveryChannel && deliveryChannel === normalizeMessageChannel(command.channel)
216+
? sessionDeliveryOrigin(targetSessionEntry)
217+
: undefined;
218+
const channelModelOverride = canApplyChannelModel
219+
? resolveChannelModelOverride({
220+
cfg: params.cfg,
221+
channel: command.channel,
222+
groupId: targetSessionEntry?.groupId,
223+
groupChatType: targetSessionEntry?.chatType ?? params.ctx.ChatType,
224+
groupChannel: targetSessionEntry?.groupChannel ?? params.ctx.GroupChannel,
225+
groupSubject: targetSessionEntry?.subject ?? params.ctx.GroupSubject,
226+
parentSessionKey:
227+
params.ctx.ModelParentSessionKey ??
228+
params.ctx.ParentSessionKey ??
229+
targetSessionEntry?.parentSessionKey,
230+
directUserIds: [
231+
deliveryOrigin?.nativeDirectUserId,
232+
deliveryOrigin?.from,
233+
deliveryOrigin?.to,
234+
params.ctx.OriginatingTo,
235+
params.ctx.From,
236+
params.ctx.SenderId,
237+
],
238+
})
239+
: null;
240+
const resolvedChannelModel = channelModelOverride
241+
? resolveModelRefFromString({
242+
raw: channelModelOverride.model,
243+
defaultProvider: params.defaultProvider,
244+
aliasIndex: params.aliasIndex,
245+
})
246+
: null;
247+
// Native status returns before normal channel routing; select once before
248+
// preparing model-bound thinking, runtime, auth, context, or fast-mode facts.
249+
const statusProvider = resolvedChannelModel?.ref.provider ?? params.provider;
250+
const statusModel = resolvedChannelModel?.ref.model ?? params.model;
197251
let resolvedDefaultThinkingLevel: ThinkLevel | undefined;
198252
const resolveDefaultThinkingLevel = async () => {
199253
resolvedDefaultThinkingLevel ??= await resolveNativeSlashDefaultThinkingLevel({
200254
cfg: params.cfg,
201255
agentId: params.agentId,
202-
provider: params.provider,
203-
model: params.model,
256+
provider: statusProvider,
257+
model: statusModel,
204258
agentDir: params.agentDir,
205259
workspaceDir: params.workspaceDir,
206260
});
@@ -227,8 +281,8 @@ export async function maybeResolveNativeSlashCommandFastReply(params: {
227281
parentSessionKey: targetSessionEntry?.parentSessionKey ?? params.ctx.ParentSessionKey,
228282
sessionScope: sessionState.sessionScope,
229283
storePath: sessionState.storePath,
230-
provider: params.provider,
231-
model: params.model,
284+
provider: statusProvider,
285+
model: statusModel,
232286
workspaceDir: params.workspaceDir,
233287
thinkingCatalog,
234288
resolvedThinkLevel,

0 commit comments

Comments
 (0)