Skip to content

Commit a89907b

Browse files
luoyanglangclaude
andcommitted
fix(telegram): keep over-limit-name models selectable in /model picker (#98221)
The /model picker silently dropped any model whose callback_data exceeded Telegram's 64-byte limit on both the standard and compact encodings — long namespaced Ollama ids in particular — while the header still counted them. Add a length-safe index fallback: when neither name-based encoding fits, buildModelSelectionCallbackData emits mdl_idx_{provider}_{index} referencing the model's position in the provider's sorted list, parseModelCallbackData decodes it, and buildModelsKeyboard stops dropping over-limit models. The callback handler resolves the index against the same [...set].toSorted(localeCompare) derivation used to build the keyboard, then reuses the existing select path; a list that changed since render prompts a refresh instead of mis-selecting. Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 86bdfec commit a89907b

3 files changed

Lines changed: 114 additions & 17 deletions

File tree

‎extensions/telegram/src/bot-handlers.runtime.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2794,8 +2794,8 @@ export const registerTelegramHandlers = ({
27942794
return;
27952795
}
27962796

2797-
// Model selection callback handler (mdl_prov, mdl_list_*, mdl_sel_*, mdl_back)
2798-
const modelCallback = parseModelCallbackData(data);
2797+
// Model selection callback handler (mdl_prov, mdl_list_*, mdl_sel_*, mdl_idx_*, mdl_back)
2798+
let modelCallback = parseModelCallbackData(data);
27992799
if (modelCallback) {
28002800
if (
28012801
!(await isTelegramModelCallbackAuthorized({
@@ -2861,6 +2861,29 @@ export const registerTelegramHandlers = ({
28612861
}
28622862
};
28632863

2864+
// Resolve an index-based selection (used when a model name is too long for
2865+
// a name-based callback_data) against the same sorted list the keyboard was
2866+
// built from. A list that changed since render yields no model at the index,
2867+
// so prompt the user to reopen rather than selecting the wrong model.
2868+
if (modelCallback.type === "selectIndex") {
2869+
const orderedModels = [...(byProvider.get(modelCallback.provider) ?? [])].toSorted(
2870+
(left, right) => left.localeCompare(right),
2871+
);
2872+
const indexedModel = orderedModels[modelCallback.index];
2873+
if (!indexedModel) {
2874+
try {
2875+
await editMessageWithButtons(
2876+
"That model list changed. Send /model again to refresh.",
2877+
[],
2878+
);
2879+
} catch (err) {
2880+
throw new TelegramRetryableCallbackError(err);
2881+
}
2882+
return;
2883+
}
2884+
modelCallback = { type: "select", provider: modelCallback.provider, model: indexedModel };
2885+
}
2886+
28642887
if (modelCallback.type === "providers" || modelCallback.type === "back") {
28652888
if (providers.length === 0) {
28662889
try {

‎extensions/telegram/src/model-buttons.test.ts‎

Lines changed: 53 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ describe("parseModelCallbackData", () => {
3333
"mdl_sel/anthropic/claude-3-7-sonnet",
3434
{ type: "select", model: "anthropic/claude-3-7-sonnet" },
3535
],
36+
["mdl_idx_ollama_5", { type: "selectIndex", provider: "ollama", index: 5 }],
37+
["mdl_idx_open-ai_0", { type: "selectIndex", provider: "open-ai", index: 0 }],
3638
[" mdl_prov ", { type: "providers" }],
3739
] as const;
3840
for (const [input, expected] of cases) {
@@ -124,9 +126,14 @@ describe("buildModelSelectionCallbackData", () => {
124126
);
125127
});
126128

127-
it("returns null when even compact callback exceeds Telegram limit", () => {
129+
it("falls back to an index callback for over-limit names (#98221)", () => {
128130
const tooLongModel = "x".repeat(80);
131+
// Without an index hint the over-limit model still cannot be name-encoded.
129132
expect(buildModelSelectionCallbackData({ provider: "openai", model: tooLongModel })).toBeNull();
133+
// With the sorted-list index it stays selectable via a length-safe reference.
134+
expect(
135+
buildModelSelectionCallbackData({ provider: "openai", model: tooLongModel, index: 7 }),
136+
).toBe("mdl_idx_openai_7");
130137
});
131138
});
132139

@@ -196,6 +203,34 @@ describe("buildModelsKeyboard", () => {
196203
expect(result[0]?.[0]?.callback_data).toBe("mdl_back");
197204
});
198205

206+
it("round-trips an over-limit model through index encode/parse/resolve (#98221)", () => {
207+
const longModel = `xentriom/${"a".repeat(70)}:latest`;
208+
const models = ["alpha", longModel, "zeta"].toSorted((left, right) =>
209+
left.localeCompare(right),
210+
);
211+
const keyboard = buildModelsKeyboard({
212+
provider: "ollama",
213+
models,
214+
currentPage: 1,
215+
totalPages: 1,
216+
});
217+
// Short names keep the readable name-based callback; the long one falls back.
218+
expect(keyboard.flat().find((b) => b.callback_data === "mdl_sel_ollama/alpha")).toBeDefined();
219+
const longButton = keyboard.flat().find((b) => b.callback_data.startsWith("mdl_idx_"));
220+
expect(longButton?.callback_data).toBeDefined();
221+
// The keyboard's index callback parses back and resolves against the same sorted
222+
// list to recover the exact model — the contract the handler relies on.
223+
const parsed = parseModelCallbackData(longButton?.callback_data ?? "");
224+
expect(parsed).toEqual({
225+
type: "selectIndex",
226+
provider: "ollama",
227+
index: models.indexOf(longModel),
228+
});
229+
if (parsed?.type === "selectIndex") {
230+
expect(models[parsed.index]).toBe(longModel);
231+
}
232+
});
233+
199234
it("renders model rows and optional current-model indicator", () => {
200235
const cases = [
201236
{
@@ -495,23 +530,30 @@ describe("large model lists (OpenRouter-scale)", () => {
495530
}
496531
});
497532

498-
it("skips models that would exceed callback_data limit", () => {
499-
const models = [
500-
"short-model",
501-
"this-is-an-extremely-long-model-name-that-definitely-exceeds-the-sixty-four-byte-limit",
502-
"another-short",
503-
];
533+
it("renders over-limit models via an index callback instead of dropping them (#98221)", () => {
534+
const longModel =
535+
"this-is-an-extremely-long-model-name-that-definitely-exceeds-the-sixty-four-byte-limit";
536+
const models = ["short-model", longModel, "another-short"];
504537
const result = buildModelsKeyboard({
505538
provider: "openrouter",
506539
models,
507540
currentPage: 1,
508541
totalPages: 1,
509542
});
510543

511-
// Should have 2 model buttons (skipping the long one) + back
544+
// No model is dropped: all three render and every callback still fits 64 bytes.
512545
const modelButtons = result.filter((row) => !row[0]?.callback_data.startsWith("mdl_back"));
513-
expect(modelButtons.length).toBe(2);
514-
expect(modelButtons[0]?.[0]?.text).toBe("short-model");
515-
expect(modelButtons[1]?.[0]?.text).toBe("another-short");
546+
expect(modelButtons.length).toBe(3);
547+
for (const row of result) {
548+
for (const button of row) {
549+
expect(Buffer.byteLength(button.callback_data, "utf8")).toBeLessThanOrEqual(64);
550+
}
551+
}
552+
// The over-limit model uses the index fallback at its position in the list.
553+
const longIndex = models.indexOf(longModel);
554+
const longButton = result
555+
.flat()
556+
.find((b) => b.callback_data === `mdl_idx_openrouter_${longIndex}`);
557+
expect(longButton).toBeDefined();
516558
});
517559
});

‎extensions/telegram/src/model-buttons.ts‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export type ParsedModelCallback =
1717
| { type: "providers" }
1818
| { type: "list"; provider: string; page: number }
1919
| { type: "select"; provider?: string; model: string }
20+
| { type: "selectIndex"; provider: string; index: number }
2021
| { type: "back" };
2122

2223
export type ProviderInfo = {
@@ -47,6 +48,7 @@ const CALLBACK_PREFIX = {
4748
list: "mdl_list_",
4849
selectStandard: "mdl_sel_",
4950
selectCompact: "mdl_sel/",
51+
selectIndex: "mdl_idx_",
5052
} as const;
5153

5254
/**
@@ -73,6 +75,16 @@ export function parseModelCallbackData(data: string): ParsedModelCallback | null
7375
}
7476
}
7577

78+
// mdl_idx_{provider}_{index} (index fallback for models too long to name-encode)
79+
const indexSelMatch = trimmed.match(/^mdl_idx_([a-z0-9_.-]+)_(\d+)$/i);
80+
if (indexSelMatch) {
81+
const [, provider, indexStr] = indexSelMatch;
82+
const index = Number(indexStr);
83+
if (provider && Number.isInteger(index)) {
84+
return { type: "selectIndex", provider, index };
85+
}
86+
}
87+
7688
// mdl_sel/{model} (compact fallback)
7789
const compactSelMatch = trimmed.match(/^mdl_sel\/(.+)$/);
7890
if (compactSelMatch) {
@@ -107,13 +119,29 @@ export function parseModelCallbackData(data: string): ParsedModelCallback | null
107119
export function buildModelSelectionCallbackData(params: {
108120
provider: string;
109121
model: string;
122+
/** Index of the model in the provider's sorted list; used as a length-safe
123+
* fallback when the model name does not fit a name-based callback. */
124+
index?: number;
110125
}): string | null {
111126
const fullCallbackData = `${CALLBACK_PREFIX.selectStandard}${params.provider}/${params.model}`;
112127
if (fitsTelegramCallbackData(fullCallbackData)) {
113128
return fullCallbackData;
114129
}
115130
const compactCallbackData = `${CALLBACK_PREFIX.selectCompact}${params.model}`;
116-
return fitsTelegramCallbackData(compactCallbackData) ? compactCallbackData : null;
131+
if (fitsTelegramCallbackData(compactCallbackData)) {
132+
return compactCallbackData;
133+
}
134+
// Long model names (e.g. namespaced Ollama ids) can exceed Telegram's 64-byte
135+
// callback_data limit even compacted. Fall back to a provider+index reference
136+
// resolved server-side against the same sorted list, so the model stays
137+
// selectable instead of being silently dropped from the picker.
138+
if (params.index !== undefined) {
139+
const indexCallbackData = `${CALLBACK_PREFIX.selectIndex}${params.provider}_${params.index}`;
140+
if (fitsTelegramCallbackData(indexCallbackData)) {
141+
return indexCallbackData;
142+
}
143+
}
144+
return null;
117145
}
118146

119147
export function resolveModelSelection(params: {
@@ -210,9 +238,13 @@ export function buildModelsKeyboard(params: ModelsKeyboardParams): ButtonRow[] {
210238
const endIndex = Math.min(startIndex + pageSize, models.length);
211239
const pageModels = models.slice(startIndex, endIndex);
212240

213-
for (const model of pageModels) {
214-
const callbackData = buildModelSelectionCallbackData({ provider, model });
215-
// Skip models that still exceed Telegram's callback_data limit.
241+
for (const [pageIndex, model] of pageModels.entries()) {
242+
const callbackData = buildModelSelectionCallbackData({
243+
provider,
244+
model,
245+
index: startIndex + pageIndex,
246+
});
247+
// Skip only if even the index fallback cannot fit (pathological provider id).
216248
if (!callbackData) {
217249
continue;
218250
}

0 commit comments

Comments
 (0)