Skip to content

Commit d93d07a

Browse files
authored
fix(telegram): prevent durable ingress lane spins (#118357)
* fix(channels): prevent ingress lane reconciliation spins * fix(ui): restore composer lint budget
1 parent f2af4e9 commit d93d07a

7 files changed

Lines changed: 121 additions & 22 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ Docs: https://docs.openclaw.ai
6060

6161
### Fixes
6262

63+
- **Telegram durable ingress:** preserve pre-identity control-lane ownership during replay and attempt each drain snapshot row only once per pass, preventing targeted commands from spinning the spool and blocking polling shutdown.
6364
- **Control UI operator session permissions:** honor Gateway-advertised operator scopes for new-thread creation, thread management, checkpoints, and sharing controls while preserving read-only navigation and legacy Gateway compatibility. Fixes #117786. Thanks @shakkernerd.
6465
- **Control UI archived session deletion:** send archive-gated delete requests from Sessions-page row and mixed-selection actions so write-scoped operators can remove archived threads while active-session deletion remains admin-only. Thanks @shakkernerd.
6566
- **Control UI command recovery:** keep delayed detached and immediate command failures scoped to their submitting session, preserving failed drafts and attachments for that pane without overwriting the active session. Fixes #116846. Thanks @shakkernerd.

‎extensions/telegram/src/telegram-ingress-drain.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,14 +62,26 @@ function telegramSpooledLaneKey(update: unknown, botInfo?: TelegramBotInfo): str
6262
});
6363
}
6464

65-
function inspectTelegramSpooledUpdate(update: unknown, botInfo?: TelegramBotInfo) {
65+
function inspectTelegramSpooledUpdate(
66+
update: unknown,
67+
botInfo?: TelegramBotInfo,
68+
claimedLaneKey?: string,
69+
) {
6670
const updateId = resolveTelegramUpdateId(update);
6771
if (updateId === null) {
6872
throw new TelegramIngressPayloadError("Telegram spooled update is missing numeric update_id.");
6973
}
74+
const derivedLaneKey = telegramSpooledLaneKey(update, botInfo);
75+
const preservePreIdentityControlLane =
76+
botInfo !== undefined &&
77+
claimedLaneKey?.endsWith(":control") === true &&
78+
claimedLaneKey !== derivedLaneKey &&
79+
claimedLaneKey === telegramSpooledLaneKey(update);
7080
return {
7181
eventId: telegramQueueEventId(updateId),
72-
laneKey: telegramSpooledLaneKey(update, botInfo),
82+
// Admission can precede getMe(). Preserve only the exact control lane that
83+
// the same payload derived before identity became available.
84+
laneKey: preservePreIdentityControlLane ? claimedLaneKey : derivedLaneKey,
7385
};
7486
}
7587

@@ -256,7 +268,12 @@ export function createTelegramIngressMonitor(params: CreateTelegramIngressMonito
256268
TelegramSpooledUpdatePayload
257269
>({
258270
queue: params.queue,
259-
inspect: (update) => inspectTelegramSpooledUpdate(update, params.botInfo),
271+
inspect: (update, context) =>
272+
inspectTelegramSpooledUpdate(
273+
update,
274+
params.botInfo,
275+
context.phase === "claim" ? context.claimedLaneKey : undefined,
276+
),
260277
payload: {
261278
version: TELEGRAM_SPOOLED_UPDATE_PAYLOAD_VERSION,
262279
serialize: (update, { receivedAt }) => {
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { createChannelIngressDrain } from "./ingress-drain.js";
3+
import {
4+
createTestIngressQueue,
5+
type IngressDrainTestPayload as Payload,
6+
withTempState,
7+
} from "./ingress-drain.test-helpers.js";
8+
9+
describe("channel ingress drain lanes", () => {
10+
it("preserves rejected stored lanes and attempts each snapshot candidate once", async () => {
11+
await withTempState(async (stateDir) => {
12+
const queue = createTestIngressQueue(stateDir);
13+
await queue.enqueue("active", { text: "topic" }, { laneKey: "topic" });
14+
let releaseActive: (() => void) | undefined;
15+
const activeDone = new Promise<void>((resolve) => {
16+
releaseActive = resolve;
17+
});
18+
const dispatches: string[] = [];
19+
const drain = createChannelIngressDrain<Payload>({
20+
queue,
21+
deriveLaneKey: (record) => record.payload.text,
22+
reconcileStoredLaneKey: () => false,
23+
dispatchClaimedEvent: async (event, lifecycle) => {
24+
dispatches.push(event.id);
25+
if (event.id === "active") {
26+
await activeDone;
27+
}
28+
await lifecycle.onAdopted();
29+
},
30+
});
31+
32+
expect(await drain.drainOnce()).toEqual({ started: 1 });
33+
await vi.waitFor(() => expect(dispatches).toEqual(["active"]));
34+
await queue.enqueue("candidate", { text: "topic" }, { laneKey: "control" });
35+
const claimNext = vi.spyOn(queue, "claimNext");
36+
37+
await expect(drain.drainOnce()).resolves.toEqual({ started: 1 });
38+
await vi.waitFor(() => expect(dispatches).toEqual(["active", "candidate"]));
39+
expect(claimNext).toHaveBeenCalledTimes(2);
40+
await expect(queue.enqueue("candidate", { text: "topic" })).resolves.toMatchObject({
41+
kind: "completed",
42+
});
43+
44+
releaseActive?.();
45+
await drain.waitForIdle();
46+
drain.dispose();
47+
});
48+
});
49+
});

‎src/channels/message/ingress-drain-state.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,25 @@ export function activeClaimKey<TPayload, TMetadata>(
4747
export function resolveLaneKey<TPayload, TMetadata>(
4848
record: ChannelIngressQueueRecord<TPayload, TMetadata>,
4949
deriveLaneKey?: (record: ChannelIngressQueueRecord<TPayload, TMetadata>) => string | undefined,
50+
reconcileStoredLaneKey?: (
51+
record: ChannelIngressQueueRecord<TPayload, TMetadata>,
52+
storedLaneKey: string,
53+
derivedLaneKey: string,
54+
) => boolean,
5055
): string {
51-
return deriveLaneKey?.(record) ?? record.laneKey ?? record.id;
56+
const derivedLaneKey = deriveLaneKey?.(record);
57+
const storedLaneKey = record.laneKey;
58+
if (
59+
!reconcileStoredLaneKey ||
60+
storedLaneKey === undefined ||
61+
derivedLaneKey === undefined ||
62+
storedLaneKey === derivedLaneKey
63+
) {
64+
return derivedLaneKey ?? storedLaneKey ?? record.id;
65+
}
66+
return reconcileStoredLaneKey(record, storedLaneKey, derivedLaneKey)
67+
? derivedLaneKey
68+
: storedLaneKey;
5269
}
5370

5471
export function sortedKeys(keys: Iterable<string>): string[] {

‎src/channels/message/ingress-drain.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -720,12 +720,16 @@ export function createChannelIngressDrain<
720720
!state.superseded
721721
);
722722
})
723-
.map((claim) => resolveLaneKey(claim, options.deriveLaneKey)),
723+
.map((claim) =>
724+
resolveLaneKey(claim, options.deriveLaneKey, options.reconcileStoredLaneKey),
725+
),
724726
);
725727
const retryDelayedLaneKeys = new Set<string>();
726728
for (const event of pending) {
727729
if (resolveIngressRetryDelayMs(event, options.retryPolicy, now()) > 0) {
728-
retryDelayedLaneKeys.add(resolveLaneKey(event, options.deriveLaneKey));
730+
retryDelayedLaneKeys.add(
731+
resolveLaneKey(event, options.deriveLaneKey, options.reconcileStoredLaneKey),
732+
);
729733
}
730734
}
731735

@@ -742,13 +746,13 @@ export function createChannelIngressDrain<
742746
if (shouldStop()) {
743747
break;
744748
}
745-
const laneKey = resolveLaneKey(event, options.deriveLaneKey);
749+
const laneKey = resolveLaneKey(event, options.deriveLaneKey, options.reconcileStoredLaneKey);
746750
if (await supersedeActiveIfNeeded(event, laneKey)) {
747751
blockedLaneKeys.delete(laneKey);
748752
}
749753
}
750754

751-
const candidateIds = pending.map((event) => event.id);
755+
const candidateIds = new Set(pending.map((event) => event.id));
752756
let started = 0;
753757
while (started < startLimit) {
754758
if (shouldStop()) {
@@ -768,11 +772,18 @@ export function createChannelIngressDrain<
768772
if (!claimed) {
769773
break;
770774
}
775+
// One snapshot row gets one attempt per pass. A released claim remains
776+
// pending for the next pump instead of spinning through SQLite here.
777+
candidateIds.delete(claimed.id);
771778
if (shouldStop()) {
772779
await queue.release(claimed, { recordAttempt: false });
773780
break;
774781
}
775-
const laneKey = resolveLaneKey(claimed, options.deriveLaneKey);
782+
const laneKey = resolveLaneKey(
783+
claimed,
784+
options.deriveLaneKey,
785+
options.reconcileStoredLaneKey,
786+
);
776787
const existing = laneOwnerByKey.get(laneKey);
777788
if (existing && existing.phase !== "settled") {
778789
if (await supersedeActiveIfNeeded(claimed, laneKey)) {

‎ui/src/pages/chat/components/chat-composer-dom.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,20 @@ export function focusComposerFromChrome(event: MouseEvent, connected: boolean) {
129129
?.focus({ preventScroll: true });
130130
}
131131

132+
export function preserveComposerFocusOnPrimaryAction(
133+
event: PointerEvent,
134+
textarea: HTMLTextAreaElement | null,
135+
): void {
136+
const composerShell = textarea?.closest<HTMLElement>(".agent-chat__composer-shell");
137+
if (
138+
document.activeElement === textarea &&
139+
composerShell &&
140+
Number.parseFloat(getComputedStyle(composerShell).marginBottom) === 0
141+
) {
142+
event.preventDefault();
143+
}
144+
}
145+
132146
export function restoreHistoryCaret(target: HTMLTextAreaElement, direction: "up" | "down") {
133147
requestAnimationFrame(() => {
134148
if (document.activeElement !== target) {

‎ui/src/pages/chat/components/chat-composer.ts‎

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
adjustTextareaHeight,
1414
disconnectTextareaOverflowObserver,
1515
observeTextareaOverflow,
16+
preserveComposerFocusOnPrimaryAction,
1617
restoreHistoryCaret,
1718
scheduleTextareaHeightAdjustment,
1819
} from "./chat-composer-dom.ts";
@@ -638,18 +639,6 @@ export function renderChatComposer(props: ChatComposerProps) {
638639
target.readOnly = true;
639640
}
640641
};
641-
const handlePrimaryActionPointerDown = (event: PointerEvent) => {
642-
const composerShell = state.composerTextarea?.closest<HTMLElement>(
643-
".agent-chat__composer-shell",
644-
);
645-
if (
646-
document.activeElement === state.composerTextarea &&
647-
composerShell &&
648-
Number.parseFloat(getComputedStyle(composerShell).marginBottom) === 0
649-
) {
650-
event.preventDefault();
651-
}
652-
};
653642
const runControlsProps: ChatRunControlsProps = {
654643
canAbort: showAbortableUi,
655644
canSend: canSubmitDraft(actionDraft),
@@ -678,7 +667,8 @@ export function renderChatComposer(props: ChatComposerProps) {
678667
microphonePicker,
679668
dictation,
680669
onDictationPointerDown: handleDictationPointerDown,
681-
onPrimaryActionPointerDown: handlePrimaryActionPointerDown,
670+
onPrimaryActionPointerDown: (event) =>
671+
preserveComposerFocusOnPrimaryAction(event, state.composerTextarea),
682672
};
683673
const cameraFacingMode = props.realtimeTalkVideoStream
684674
?.getVideoTracks?.()[0]

0 commit comments

Comments
 (0)