Skip to content

Commit 6f52e9f

Browse files
authored
fix(telegram): preserve direct-message topics in config and cron writeback (#127010)
* fix(telegram): preserve direct message topics in target writeback * test(ui): consolidate cron scheduler status coverage
1 parent 57a2677 commit 6f52e9f

3 files changed

Lines changed: 97 additions & 74 deletions

File tree

‎extensions/telegram/src/target-writeback.test-shared.ts‎

Lines changed: 75 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,48 @@ type CronStoreWrite = {
2929
jobs: Array<{ id: string; delivery: { channel: string; to: string } }>;
3030
};
3131

32+
const scopedTargetWritebackCases = [
33+
{
34+
name: "channel Direct Messages topic",
35+
rawTarget: "@mychannel:direct-topic:77",
36+
matchingTarget: "t.me/MyChannel:direct-topic:77",
37+
resolvedTarget: "-100123:direct-topic:77",
38+
unmatchedTargets: [
39+
"@mychannel",
40+
"@mychannel:direct-topic:88",
41+
"@mychannel:topic:77",
42+
"@mychannel:77",
43+
"@otherchannel:direct-topic:77",
44+
],
45+
},
46+
{
47+
name: "explicit forum topic",
48+
rawTarget: "@mychannel:topic:77",
49+
matchingTarget: "t.me/MyChannel:77",
50+
resolvedTarget: "-100123:topic:77",
51+
unmatchedTargets: ["@mychannel", "@mychannel:direct-topic:77", "@mychannel:topic:88"],
52+
},
53+
{
54+
name: "shorthand forum topic",
55+
rawTarget: "@mychannel:77",
56+
matchingTarget: "t.me/MyChannel:topic:77",
57+
resolvedTarget: "-100123:77",
58+
unmatchedTargets: ["@mychannel", "@mychannel:direct-topic:77", "@mychannel:88"],
59+
},
60+
{
61+
name: "unthreaded target",
62+
rawTarget: "t.me/mychannel",
63+
matchingTarget: "@MyChannel",
64+
resolvedTarget: "-100123",
65+
unmatchedTargets: [
66+
"@mychannel:direct-topic:77",
67+
"@mychannel:direct-topic:88",
68+
"@mychannel:topic:77",
69+
"@mychannel:77",
70+
],
71+
},
72+
] as const;
73+
3274
vi.mock("openclaw/plugin-sdk/config-mutation", async () => {
3375
const actual = await vi.importActual<typeof import("openclaw/plugin-sdk/config-mutation")>(
3476
"openclaw/plugin-sdk/config-mutation",
@@ -251,33 +293,58 @@ export function installMaybePersistResolvedTelegramTargetTests(params?: {
251293
]);
252294
});
253295

254-
it("preserves topic suffix style in writeback target", async () => {
296+
it.each(
297+
scopedTargetWritebackCases.flatMap((testCase) =>
298+
(["config", "cron"] as const).map((surface) => ({
299+
name: testCase.name,
300+
surface,
301+
testCase,
302+
})),
303+
),
304+
)("rewrites only matching $name $surface targets", async ({ surface, testCase }) => {
305+
const unmatchedAccounts = Object.fromEntries(
306+
testCase.unmatchedTargets.map((target, index) => [`other${index}`, { defaultTo: target }]),
307+
);
255308
readConfigFileSnapshotForWrite.mockResolvedValue({
256309
snapshot: {
257310
config: {
258311
channels: {
259312
telegram: {
260-
defaultTo: "t.me/mychannel:topic:9",
313+
defaultTo: testCase.matchingTarget,
314+
accounts: unmatchedAccounts,
261315
},
262316
},
263317
},
264318
},
265319
writeOptions: {},
266320
});
267-
loadCronStore.mockResolvedValue({ version: 1, jobs: [] });
321+
loadCronStore.mockResolvedValue({
322+
version: 1,
323+
jobs: [testCase.matchingTarget, ...testCase.unmatchedTargets].map((target, index) => ({
324+
id: String(index),
325+
delivery: { channel: "telegram", to: target },
326+
})),
327+
});
268328

269329
await maybePersistResolvedTelegramTarget({
270330
cfg: {} as OpenClawConfig,
271-
rawTarget: "t.me/mychannel:topic:9",
331+
rawTarget: testCase.rawTarget,
272332
resolvedChatId: "-100123",
273333
gatewayClientScopes: undefined,
274334
trustedInternalWriteback: true,
275335
});
276336

277-
expect(writeConfigFile).toHaveBeenCalledTimes(1);
278-
const [writtenConfig, writeOptions] = requireWriteConfigCall();
279-
expect(writtenConfig.channels?.telegram?.defaultTo).toBe("-100123:topic:9");
280-
expect(writeOptions).toEqual({});
337+
const persistedTargets =
338+
surface === "config"
339+
? [
340+
requireWriteConfigCall()[0].channels?.telegram?.defaultTo,
341+
...Object.values(requireWriteConfigCall()[0].channels?.telegram?.accounts ?? {}).map(
342+
(account) => account.defaultTo,
343+
),
344+
]
345+
: requireSaveCronStoreCall()[1].jobs.map((job) => job.delivery.to);
346+
347+
expect(persistedTargets).toEqual([testCase.resolvedTarget, ...testCase.unmatchedTargets]);
281348
});
282349

283350
it("matches username targets case-insensitively", async () => {

‎extensions/telegram/src/target-writeback.ts‎

Lines changed: 15 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,8 @@ import {
1111
} from "openclaw/plugin-sdk/cron-store-runtime";
1212
import { asObjectRecord } from "openclaw/plugin-sdk/runtime-doctor-migrations";
1313
import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
14-
import {
15-
normalizeLowercaseStringOrEmpty,
16-
normalizeOptionalString,
17-
} from "openclaw/plugin-sdk/string-coerce-runtime";
14+
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
15+
import { telegramMessagingTargetsMatch } from "./normalize.js";
1816
import {
1917
normalizeTelegramChatId,
2018
normalizeTelegramLookupTarget,
@@ -24,30 +22,15 @@ import {
2422
const writebackLogger = createSubsystemLogger("telegram/target-writeback");
2523
const TELEGRAM_ADMIN_SCOPE = "operator.admin";
2624

27-
function normalizeTelegramLookupTargetForMatch(raw: string): string | undefined {
28-
const normalized = normalizeTelegramLookupTarget(raw);
29-
if (!normalized) {
30-
return undefined;
31-
}
32-
return normalized.startsWith("@") ? normalizeLowercaseStringOrEmpty(normalized) : normalized;
33-
}
34-
35-
function normalizeTelegramTargetForMatch(raw: string): string | undefined {
36-
const parsed = parseTelegramTarget(raw);
37-
const normalized = normalizeTelegramLookupTargetForMatch(parsed.chatId);
38-
if (!normalized) {
39-
return undefined;
40-
}
41-
const threadKey = parsed.messageThreadId == null ? "" : String(parsed.messageThreadId);
42-
return `${normalized}|${threadKey}`;
43-
}
44-
4525
function buildResolvedTelegramTarget(params: {
4626
raw: string;
4727
parsed: ReturnType<typeof parseTelegramTarget>;
4828
resolvedChatId: string;
4929
}): string {
5030
const { raw, parsed, resolvedChatId } = params;
31+
if (parsed.directMessagesTopicId != null) {
32+
return `${resolvedChatId}:direct-topic:${parsed.directMessagesTopicId}`;
33+
}
5134
if (parsed.messageThreadId == null) {
5235
return resolvedChatId;
5336
}
@@ -59,18 +42,13 @@ function buildResolvedTelegramTarget(params: {
5942
function resolveLegacyRewrite(params: {
6043
raw: string;
6144
resolvedChatId: string;
62-
}): { matchKey: string; resolvedTarget: string } | null {
45+
}): { sourceTarget: string; resolvedTarget: string } | null {
6346
const parsed = parseTelegramTarget(params.raw);
64-
if (normalizeTelegramChatId(parsed.chatId)) {
65-
return null;
66-
}
67-
const normalized = normalizeTelegramLookupTargetForMatch(parsed.chatId);
68-
if (!normalized) {
47+
if (normalizeTelegramChatId(parsed.chatId) || !normalizeTelegramLookupTarget(parsed.chatId)) {
6948
return null;
7049
}
71-
const threadKey = parsed.messageThreadId == null ? "" : String(parsed.messageThreadId);
7250
return {
73-
matchKey: `${normalized}|${threadKey}`,
51+
sourceTarget: params.raw,
7452
resolvedTarget: buildResolvedTelegramTarget({
7553
raw: params.raw,
7654
parsed,
@@ -81,7 +59,7 @@ function resolveLegacyRewrite(params: {
8159

8260
function rewriteTargetIfMatch(params: {
8361
rawValue: unknown;
84-
matchKey: string;
62+
sourceTarget: string;
8563
resolvedTarget: string;
8664
}): string | null {
8765
if (typeof params.rawValue !== "string" && typeof params.rawValue !== "number") {
@@ -91,15 +69,15 @@ function rewriteTargetIfMatch(params: {
9169
if (!value) {
9270
return null;
9371
}
94-
if (normalizeTelegramTargetForMatch(value) !== params.matchKey) {
72+
if (!telegramMessagingTargetsMatch(value, params.sourceTarget)) {
9573
return null;
9674
}
9775
return params.resolvedTarget;
9876
}
9977

10078
function replaceTelegramDefaultToTargets(params: {
10179
cfg: OpenClawConfig;
102-
matchKey: string;
80+
sourceTarget: string;
10381
resolvedTarget: string;
10482
}): boolean {
10583
let changed = false;
@@ -111,7 +89,7 @@ function replaceTelegramDefaultToTargets(params: {
11189
const maybeReplace = (holder: Record<string, unknown>, key: string) => {
11290
const nextTarget = rewriteTargetIfMatch({
11391
rawValue: holder[key],
114-
matchKey: params.matchKey,
92+
sourceTarget: params.sourceTarget,
11593
resolvedTarget: params.resolvedTarget,
11694
});
11795
if (!nextTarget) {
@@ -155,7 +133,7 @@ export async function maybePersistResolvedTelegramTarget(params: {
155133
if (!rewrite) {
156134
return;
157135
}
158-
const { matchKey, resolvedTarget } = rewrite;
136+
const { sourceTarget, resolvedTarget } = rewrite;
159137
const hasGatewayAdminScope = params.gatewayClientScopes?.includes(TELEGRAM_ADMIN_SCOPE) === true;
160138
const trustedInternalWriteback =
161139
params.gatewayClientScopes === undefined && params.trustedInternalWriteback === true;
@@ -171,7 +149,7 @@ export async function maybePersistResolvedTelegramTarget(params: {
171149
const nextConfig = structuredClone(snapshot.config ?? {});
172150
const configChanged = replaceTelegramDefaultToTargets({
173151
cfg: nextConfig,
174-
matchKey,
152+
sourceTarget,
175153
resolvedTarget,
176154
});
177155
if (configChanged) {
@@ -201,7 +179,7 @@ export async function maybePersistResolvedTelegramTarget(params: {
201179
}
202180
const nextTarget = rewriteTargetIfMatch({
203181
rawValue: job.delivery.to,
204-
matchKey,
182+
sourceTarget,
205183
resolvedTarget,
206184
});
207185
if (!nextTarget) {

‎ui/src/pages/cron/view.test.ts‎

Lines changed: 7 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -8,45 +8,23 @@ import {
88
} from "./view.test-support.ts";
99

1010
describe("cron view list pane", () => {
11-
it("uses agent-scoped summary values", () => {
11+
it.each([
12+
{ name: "an enabled scheduler", status: { enabled: true }, hasNextWake: true },
13+
{ name: "a disabled scheduler", status: { enabled: false }, hasNextWake: false },
14+
{ name: "loading scheduler status", status: null, hasNextWake: true },
15+
])("uses agent-scoped summary values for $name", ({ status, hasNextWake }) => {
1216
const container = renderView({
1317
agentScoped: true,
1418
scopedTotal: 3,
1519
scopedNextWakeAtMs: Date.now() + 60_000,
16-
status: { enabled: true, triggersEnabled: true, jobs: 99, nextWakeAtMs: null },
20+
status: status ? { ...status, triggersEnabled: true, jobs: 99, nextWakeAtMs: null } : null,
1721
});
1822
const values = [...container.querySelectorAll(".cron-stat__value")].map((entry) =>
1923
entry.textContent?.trim(),
2024
);
2125

2226
expect(values[0]).toBe("3");
23-
expect(values[2]).not.toBe("n/a");
24-
});
25-
26-
it("hides an agent-scoped next wake while the scheduler is disabled", () => {
27-
const container = renderView({
28-
agentScoped: true,
29-
scopedNextWakeAtMs: Date.now() + 60_000,
30-
status: { enabled: false, triggersEnabled: true, jobs: 3, nextWakeAtMs: null },
31-
});
32-
const values = [...container.querySelectorAll(".cron-stat__value")].map((entry) =>
33-
entry.textContent?.trim(),
34-
);
35-
36-
expect(values[2]).toBe("n/a");
37-
});
38-
39-
it("keeps an agent-scoped next wake while scheduler status is loading", () => {
40-
const container = renderView({
41-
agentScoped: true,
42-
scopedNextWakeAtMs: Date.now() + 60_000,
43-
status: null,
44-
});
45-
const values = [...container.querySelectorAll(".cron-stat__value")].map((entry) =>
46-
entry.textContent?.trim(),
47-
);
48-
49-
expect(values[2]).not.toBe("n/a");
27+
expect(values[2] !== "n/a").toBe(hasNextWake);
5028
});
5129

5230
it("wires the enabled tabs and marks the active one", () => {

0 commit comments

Comments
 (0)