Skip to content

Commit 1f578f0

Browse files
steipetePeter Steinberger
andauthored
fix(telegram): validate native queue arguments before fallback (#116726)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent 6fbe39e commit 1f578f0

6 files changed

Lines changed: 207 additions & 3 deletions

File tree

‎extensions/qa-lab/src/live-transports/telegram/profiles.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,16 @@ describe("Telegram QA profiles", () => {
5656
).toThrow("execution.kind=flow");
5757
});
5858

59+
it("selects the native queue-validation regression as an explicit live scenario", () => {
60+
expect(
61+
resolveTelegramQaScenarioIds({
62+
profile: "release",
63+
providerMode: "live-frontier",
64+
scenarioIds: ["telegram-queue-invalid-mode"],
65+
}),
66+
).toEqual(["telegram-queue-invalid-mode"]);
67+
});
68+
5969
it("rejects unknown profiles and channel-ineligible explicit scenarios", () => {
6070
expect(() =>
6171
resolveTelegramQaScenarioIds({ providerMode: "live-frontier", profile: "transport" }),

‎extensions/telegram/src/bot-native-commands.session-meta.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
type NativeCommandTestParams,
1616
} from "./bot-native-commands.fixture-test-support.js";
1717
import type { RegisterTelegramHandlerParams } from "./bot-native-commands.js";
18+
import { runWithTelegramUpdateProcessingFrame } from "./bot-processing-outcome.js";
1819

1920
// All mocks scoped to this file only — does not affect bot-native-commands.test.ts
2021

@@ -731,6 +732,39 @@ describe("registerTelegramNativeCommands — session metadata", () => {
731732
expect(turnPlan?.record?.sessionKey).toBe(turnPlan?.ctxPayload.CommandTargetSessionKey);
732733
});
733734

735+
it("records a completed outcome after a native slash command", async () => {
736+
const { handler } = registerAndResolveStatusHandler({ cfg: {} });
737+
738+
const { result } = await runWithTelegramUpdateProcessingFrame(async () => {
739+
await handler(createTelegramPrivateCommandContext());
740+
});
741+
742+
expect(result).toEqual({ kind: "completed" });
743+
});
744+
745+
it("preserves every argument on native queue command turns", async () => {
746+
const { handler } = registerAndResolveCommandHandler({
747+
commandName: "queue",
748+
cfg: {},
749+
allowFrom: ["*"],
750+
});
751+
752+
await handler(createTelegramPrivateCommandContext({ match: "Can you diagnose this?" }));
753+
754+
expect(dispatchChannelInboundTurnMock).toHaveBeenCalledWith(
755+
expect.objectContaining({
756+
ctxPayload: expect.objectContaining({
757+
Body: "/queue Can you diagnose this?",
758+
CommandBody: "/queue Can you diagnose this?",
759+
CommandTurn: expect.objectContaining({
760+
kind: "native",
761+
body: "/queue Can you diagnose this?",
762+
}),
763+
}),
764+
}),
765+
);
766+
});
767+
734768
it("keeps one live config snapshot through native command execution", async () => {
735769
const startupCfg: OpenClawConfig = { session: { store: "/tmp/startup-sessions.json" } };
736770
const runtimeCfg: OpenClawConfig = { session: { store: "/tmp/runtime-sessions.json" } };

‎extensions/telegram/src/bot-native-commands.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,10 @@ import {
7575
syncTelegramMenuCommands as syncTelegramMenuCommandsRuntime,
7676
type TelegramMenuCommand,
7777
} from "./bot-native-command-menu.js";
78-
import type { TelegramMessageProcessingResult } from "./bot-processing-outcome.js";
78+
import {
79+
recordTelegramMessageProcessingResult,
80+
type TelegramMessageProcessingResult,
81+
} from "./bot-processing-outcome.js";
7982
import type { TelegramUpdateKeyContext } from "./bot-updates.js";
8083
import type { TelegramBotOptions } from "./bot.types.js";
8184
import {
@@ -122,6 +125,20 @@ const EMPTY_RESPONSE_FALLBACK = "No response generated. Please try again.";
122125
const activeTelegramCodexLoginFlows = new Map<string, { expiresAt: number }>();
123126

124127
type TelegramNativeCommandContext = Context & { match?: string };
128+
129+
function registerTelegramNativeCommandHandler(
130+
bot: Bot,
131+
command: string,
132+
handler: (ctx: TelegramNativeCommandContext) => Promise<void>,
133+
): void {
134+
bot.command(command, async (ctx: TelegramNativeCommandContext) => {
135+
await handler(ctx);
136+
// Native commands bypass processMessage, so their terminal outcome must be
137+
// recorded here for every built-in, plugin, and direct-delivery branch.
138+
recordTelegramMessageProcessingResult({ kind: "completed" });
139+
});
140+
}
141+
125142
type TelegramChunkMode = ReturnType<
126143
typeof import("openclaw/plugin-sdk/reply-dispatch-runtime").resolveChunkMode
127144
>;
@@ -1210,7 +1227,7 @@ export const registerTelegramNativeCommands = ({
12101227
if (commandsToRegister.length > 0 || pluginCatalog.commands.length > 0) {
12111228
for (const command of nativeCommands) {
12121229
const normalizedCommandName = normalizeTelegramCommandName(command.name);
1213-
bot.command(normalizedCommandName, async (ctx: TelegramNativeCommandContext) => {
1230+
registerTelegramNativeCommandHandler(bot, normalizedCommandName, async (ctx) => {
12141231
const msg = ctx.message;
12151232
if (!msg) {
12161233
return;
@@ -1800,7 +1817,7 @@ export const registerTelegramNativeCommands = ({
18001817
}
18011818

18021819
for (const pluginCommand of pluginCatalog.commands) {
1803-
bot.command(pluginCommand.command, async (ctx: TelegramNativeCommandContext) => {
1820+
registerTelegramNativeCommandHandler(bot, pluginCommand.command, async (ctx) => {
18041821
const msg = ctx.message;
18051822
if (!msg) {
18061823
return;
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
title: Telegram native queue command rejects ordinary prompt text
2+
3+
scenario:
4+
id: telegram-queue-invalid-mode
5+
surface: channels
6+
category: channels.channel-actions-commands-and-approvals
7+
coverage:
8+
primary:
9+
- telegram.built-in-commands
10+
regressionRefs:
11+
- openclaw/openclaw#116688
12+
objective: Verify a native Telegram queue command with ordinary trailing text returns its queue-mode validation error without invoking the model or synthesizing a model-failure fallback.
13+
successCriteria:
14+
- Telegram accepts the native queue command with its complete trailing argument text.
15+
- The reply identifies the invalid queue mode and lists supported queue modes.
16+
- The reply never blames the model, and a mock provider receives no request for the command.
17+
codeRefs:
18+
- extensions/telegram/src/bot-native-commands.ts
19+
- src/auto-reply/reply/get-reply-directives.ts
20+
- src/auto-reply/reply/directive-handling.queue-validation.ts
21+
execution:
22+
kind: flow
23+
channel: telegram
24+
summary: Send the reported native queue command and verify its explicit validation reply.
25+
config:
26+
commandText: /queue Can you diagnose this?
27+
invalidModeNeedle: Unrecognized queue mode "Can"
28+
validModesNeedle: "Valid modes: steer, followup, collect, interrupt."
29+
falseFallbackNeedle: temporary model failure
30+
31+
flow:
32+
steps:
33+
- name: invalid native queue arguments produce a visible command error
34+
actions:
35+
- resetTransport: true
36+
- set: requestCursorBefore
37+
value:
38+
expr: "env.mock ? (await fetchJson(`${env.mock.baseUrl}/debug/request-cursor`)).cursor : 0"
39+
- set: startIndex
40+
value:
41+
expr: "state.getSnapshot().messages.filter((message) => message.direction === 'outbound').length"
42+
- sendInbound:
43+
conversation: { id: telegram-command-room, kind: channel }
44+
senderId: qa-command-operator
45+
senderName: QA Command Operator
46+
text: { ref: config.commandText }
47+
nativeCommand: { name: queue }
48+
- waitForOutbound:
49+
conversation: { id: telegram-command-room, kind: channel }
50+
sinceIndex: { ref: startIndex }
51+
textIncludes: { ref: config.invalidModeNeedle }
52+
timeoutMs: 60000
53+
saveAs: reply
54+
- assert:
55+
expr: "reply.text.includes(config.validModesNeedle)"
56+
message:
57+
expr: "`queue validation reply omitted the valid modes: ${reply.text}`"
58+
- assert:
59+
expr: "!reply.text.includes(config.falseFallbackNeedle)"
60+
message:
61+
expr: "`queue validation emitted the false model fallback: ${reply.text}`"
62+
- set: scenarioRequests
63+
value:
64+
expr: "env.mock ? await fetchJson(`${env.mock.baseUrl}/debug/requests?after=${requestCursorBefore}`) : []"
65+
- assert:
66+
expr: "!env.mock || scenarioRequests.length === 0"
67+
message:
68+
expr: "`native queue validation unexpectedly invoked the model ${String(scenarioRequests.length)} time(s)`"
69+
detailsExpr: reply.text

‎src/auto-reply/reply/get-reply-directives.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { normalizeAgentId } from "../../routing/session-key.js";
1818
import { ModelSelectionLockedError } from "../../sessions/model-overrides.js";
1919
import { createLazyImportLoader } from "../../shared/lazy-promise.js";
2020
import type { SkillCommandSpec } from "../../skills/types.js";
21+
import { isNativeCommandTurn, resolveCommandTurnContext } from "../command-turn-context.js";
2122
import { shouldHandleTextCommands } from "../commands-text-routing.js";
2223
import { markCommandReplyForDelivery } from "../reply-payload.js";
2324
import type {
@@ -36,6 +37,7 @@ import type { GetReplyOptions, ReplyPayload } from "../types.js";
3637
import { resolveBlockStreamingChunking } from "./block-streaming.js";
3738
import { buildCommandContext } from "./commands-context.js";
3839
import { type InlineDirectives, parseInlineDirectives } from "./directive-handling.parse.js";
40+
import { maybeHandleQueueDirective } from "./directive-handling.queue-validation.js";
3941
import {
4042
reserveSkillCommandNames,
4143
resolveConfiguredDirectiveAliases,
@@ -275,6 +277,25 @@ export async function resolveReplyDirectives(params: {
275277
modelAliases: configuredAliases,
276278
allowStatusDirective,
277279
});
280+
const commandTurn = resolveCommandTurnContext(ctx);
281+
if (
282+
command.isAuthorizedSender &&
283+
isNativeCommandTurn(commandTurn) &&
284+
commandTurn.commandName === "queue" &&
285+
parsedDirectives.hasQueueDirective
286+
) {
287+
// Native command arguments belong to the command, not to an inline prompt;
288+
// validate them before mixed-text cleanup can erase an invalid queue mode.
289+
const queueReply = maybeHandleQueueDirective({
290+
directives: parsedDirectives,
291+
cfg,
292+
channel: command.channel,
293+
sessionEntry: targetSessionEntry,
294+
});
295+
if (queueReply) {
296+
return { kind: "reply", reply: markCommandReplyForDelivery(queueReply) };
297+
}
298+
}
278299
const hasInlineStatus =
279300
parsedDirectives.hasStatusDirective && parsedDirectives.cleaned.trim().length > 0;
280301
if (hasInlineStatus) {

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

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,59 @@ describe("maybeResolveNativeSlashCommandFastReply", () => {
4343
handleCommandsMock.mockReset();
4444
});
4545

46+
it("returns native queue validation instead of discarding trailing command arguments", async () => {
47+
handleCommandsMock.mockResolvedValue({ shouldContinue: true });
48+
49+
const body = "/queue Can you diagnose this?";
50+
const typing = createTypingController();
51+
const result = await maybeResolveNativeSlashCommandFastReply({
52+
ctx: buildTestCtx({
53+
Body: body,
54+
BodyForAgent: body,
55+
RawBody: body,
56+
CommandBody: body,
57+
CommandSource: "native",
58+
CommandAuthorized: true,
59+
Provider: "telegram",
60+
Surface: "telegram",
61+
SessionKey: "telegram:slash:123",
62+
CommandTargetSessionKey: "agent:main:telegram:123",
63+
CommandTurn: {
64+
kind: "native",
65+
source: "native",
66+
authorized: true,
67+
commandName: "queue",
68+
body,
69+
},
70+
}),
71+
cfg: markCompleteReplyConfig({
72+
session: {
73+
store: path.join(tempDirs.make("openclaw-native-queue-"), "sessions.json"),
74+
},
75+
} as OpenClawConfig),
76+
agentId: "main",
77+
agentDir: "/tmp/agent",
78+
agentCfg: undefined,
79+
commandAuthorized: true,
80+
defaultProvider: "openai",
81+
defaultModel: "gpt-5.5",
82+
aliasIndex: { byKey: new Map(), byAlias: new Map() },
83+
provider: "openai",
84+
model: "gpt-5.5",
85+
workspaceDir: "/tmp/workspace",
86+
typing,
87+
});
88+
89+
expect(result).toEqual({
90+
handled: true,
91+
reply: expect.objectContaining({
92+
text: 'Unrecognized queue mode "Can". Valid modes: steer, followup, collect, interrupt.',
93+
}),
94+
});
95+
expect(handleCommandsMock).toHaveBeenCalledOnce();
96+
expect(typing.cleanup).toHaveBeenCalledOnce();
97+
});
98+
4699
it("marks native /compact terminal replies for delivery under message_tool_only (#90185)", async () => {
47100
handleCommandsMock.mockResolvedValueOnce({
48101
shouldContinue: false,

0 commit comments

Comments
 (0)