Skip to content

Commit ec866d8

Browse files
authored
fix(telegram): clear stale localized command menus (#120885)
* fix(telegram): clear stale localized command menus * test(telegram): satisfy command menu lint
1 parent 4b7454b commit ec866d8

7 files changed

Lines changed: 1141 additions & 530 deletions
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
// Owns Telegram command-menu identity, process serialization, and durable locale state.
2+
import type { PluginStateKeyedStore } from "openclaw/plugin-sdk/plugin-state-runtime";
3+
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env";
4+
import { getOptionalTelegramRuntime } from "./runtime.js";
5+
import { fingerprintTelegramBotToken } from "./token-fingerprint.js";
6+
import { resolveTelegramBotUserIdFromToken } from "./token.js";
7+
8+
const TELEGRAM_MENU_LOCALE_LEDGER_VERSION = 1;
9+
const TELEGRAM_MENU_LOCALE_LEDGER_NAMESPACE = "telegram.command-menu-locales";
10+
const TELEGRAM_MENU_LOCALE_LEDGER_MAX_ENTRIES = 1_000;
11+
12+
type TelegramMenuLocaleLedger = {
13+
version: typeof TELEGRAM_MENU_LOCALE_LEDGER_VERSION;
14+
languageCodes: string[];
15+
};
16+
17+
type TelegramMenuLocaleLedgerHandle = {
18+
store: PluginStateKeyedStore<TelegramMenuLocaleLedger>;
19+
value?: TelegramMenuLocaleLedger;
20+
};
21+
22+
const syncTails = new Map<string, Promise<void>>();
23+
// Successful command hashes stay process-local so restarts always republish.
24+
const syncedCommandHashes = new Map<string, string>();
25+
const knownLanguageCodes = new Map<string, Set<string>>();
26+
27+
export function resolveTelegramMenuRemoteOwner(params: {
28+
accountId?: string;
29+
botId?: number;
30+
botToken?: string;
31+
}) {
32+
const token = params.botToken?.trim();
33+
const tokenBotId = resolveTelegramBotUserIdFromToken(token);
34+
const botId = params.botId ?? tokenBotId;
35+
const tokenFingerprint = token ? fingerprintTelegramBotToken(token) : undefined;
36+
const fallbackKey = `${params.accountId ?? "default"}:${tokenFingerprint ?? "unknown"}`;
37+
const queueKey = botId === undefined ? `fallback:${fallbackKey}` : `bot:${botId}`;
38+
return {
39+
queueKey,
40+
hashKey: `${queueKey}:${tokenFingerprint ?? ""}`,
41+
...(botId === undefined ? {} : { botId: String(botId) }),
42+
};
43+
}
44+
45+
export function enqueueTelegramMenuSync(params: {
46+
ownerKey: string;
47+
sync: () => Promise<void>;
48+
onError: (error: unknown) => void;
49+
}): void {
50+
const previous = syncTails.get(params.ownerKey) ?? Promise.resolve();
51+
// A remote bot owns one mutation lane so reload generations cannot interleave.
52+
const next = previous.then(params.sync).catch((error: unknown) => {
53+
try {
54+
params.onError(error);
55+
} catch {
56+
// Logging failures must not poison the remote owner's next generation.
57+
}
58+
});
59+
syncTails.set(params.ownerKey, next);
60+
void next.then(() => {
61+
if (syncTails.get(params.ownerKey) === next) {
62+
syncTails.delete(params.ownerKey);
63+
}
64+
});
65+
}
66+
67+
export function readTelegramMenuCommandHash(key: string): string | null {
68+
return syncedCommandHashes.get(key) ?? null;
69+
}
70+
71+
export function writeTelegramMenuCommandHash(key: string, hash: string): void {
72+
syncedCommandHashes.set(key, hash);
73+
}
74+
75+
export function getProcessKnownTelegramMenuLocales(ownerKey: string): Set<string> {
76+
let locales = knownLanguageCodes.get(ownerKey);
77+
if (!locales) {
78+
locales = new Set<string>();
79+
knownLanguageCodes.set(ownerKey, locales);
80+
}
81+
return locales;
82+
}
83+
84+
export function normalizeTelegramMenuLanguageCode(languageCode: string): string | null {
85+
const normalized = languageCode.trim().toLowerCase();
86+
return /^[a-z]{2}$/.test(normalized) ? normalized : null;
87+
}
88+
89+
function parseTelegramMenuLocaleLedger(value: unknown): TelegramMenuLocaleLedger | null {
90+
if (!value || typeof value !== "object") {
91+
return null;
92+
}
93+
const candidate = value as { version?: unknown; languageCodes?: unknown };
94+
if (
95+
candidate.version !== TELEGRAM_MENU_LOCALE_LEDGER_VERSION ||
96+
!Array.isArray(candidate.languageCodes)
97+
) {
98+
return null;
99+
}
100+
const languageCodes: string[] = [];
101+
for (const languageCode of candidate.languageCodes) {
102+
if (
103+
typeof languageCode !== "string" ||
104+
normalizeTelegramMenuLanguageCode(languageCode) !== languageCode
105+
) {
106+
return null;
107+
}
108+
languageCodes.push(languageCode);
109+
}
110+
const sortedLanguageCodes = languageCodes.toSorted();
111+
if (
112+
new Set(languageCodes).size !== languageCodes.length ||
113+
languageCodes.some((languageCode, index) => languageCode !== sortedLanguageCodes[index])
114+
) {
115+
return null;
116+
}
117+
return { version: TELEGRAM_MENU_LOCALE_LEDGER_VERSION, languageCodes };
118+
}
119+
120+
export async function readTelegramMenuLocaleLedger(params: {
121+
botId: string;
122+
runtime: RuntimeEnv;
123+
}): Promise<TelegramMenuLocaleLedgerHandle | null> {
124+
const telegramRuntime = getOptionalTelegramRuntime();
125+
if (!telegramRuntime) {
126+
params.runtime.error?.(
127+
`Telegram command menu locale ledger unavailable for bot ${params.botId}: runtime not initialized`,
128+
);
129+
return null;
130+
}
131+
try {
132+
const store = telegramRuntime.state.openKeyedStore<TelegramMenuLocaleLedger>({
133+
namespace: TELEGRAM_MENU_LOCALE_LEDGER_NAMESPACE,
134+
maxEntries: TELEGRAM_MENU_LOCALE_LEDGER_MAX_ENTRIES,
135+
overflowPolicy: "reject-new",
136+
});
137+
const stored = await store.lookup(params.botId);
138+
if (stored === undefined) {
139+
return { store };
140+
}
141+
const value = parseTelegramMenuLocaleLedger(stored);
142+
if (!value) {
143+
params.runtime.error?.(
144+
`Telegram command menu locale ledger is malformed for bot ${params.botId}; preserving it for recovery.`,
145+
);
146+
return null;
147+
}
148+
return { store, value };
149+
} catch (error) {
150+
params.runtime.error?.(
151+
`Telegram command menu locale ledger unavailable for bot ${params.botId}: ${String(error)}`,
152+
);
153+
return null;
154+
}
155+
}
156+
157+
export async function persistTelegramMenuLocaleLedger(params: {
158+
botId: string;
159+
read: TelegramMenuLocaleLedgerHandle;
160+
languageCodes: string[];
161+
}): Promise<void> {
162+
const current = params.read.value?.languageCodes ?? [];
163+
if (
164+
current.length === params.languageCodes.length &&
165+
current.every((languageCode, index) => languageCode === params.languageCodes[index])
166+
) {
167+
return;
168+
}
169+
if (params.languageCodes.length === 0) {
170+
await params.read.store.delete(params.botId);
171+
return;
172+
}
173+
// Record locale intent before publishing so partial writes remain cleanup-visible.
174+
await params.read.store.register(params.botId, {
175+
version: TELEGRAM_MENU_LOCALE_LEDGER_VERSION,
176+
languageCodes: params.languageCodes,
177+
});
178+
}

0 commit comments

Comments
 (0)