fix: tool card display issues — serial dispatch, overflow editing, thinking cleanup
- Serialize per-session message dispatch to prevent out-of-order event processing
(tool_update arriving before tool_call due to concurrent fire-and-forget dispatch)
- Buffer tool updates that arrive before their tool_call and apply on addTool
- Allow post-finalize tool updates to flush immediately (late completion after seal)
- Track overflow message IDs and edit them instead of only sending once
- Forward tool updates to previous sealed card for late completions
- Count failed/error tools as done in header (Tools N/N ✅)
- Stop deleting thinking indicator messages to reduce Telegram API calls
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
c7913ff67b
commit
e318bcba46
@ -9,7 +9,6 @@ import {
|
||||
formatToolSummary,
|
||||
resolveToolIcon,
|
||||
} from "../message-formatter.js";
|
||||
|
||||
const DEBOUNCE_MS = 500;
|
||||
|
||||
export interface ToolCardEntry {
|
||||
@ -55,6 +54,8 @@ export class ToolCardState {
|
||||
private debounceTimer?: ReturnType<typeof setTimeout>;
|
||||
private verbosity: DisplayVerbosity;
|
||||
private onFlush: (snapshot: ToolCardSnapshot) => void;
|
||||
/** Buffer for tool updates that arrive before their tool_call (out-of-order dispatch) */
|
||||
private pendingUpdates = new Map<string, { status: string; viewerLinks?: ViewerLinks; viewerFilePath?: string }>();
|
||||
|
||||
constructor(config: ToolCardStateConfig) {
|
||||
this.verbosity = config.verbosity;
|
||||
@ -78,6 +79,17 @@ export class ToolCardState {
|
||||
viewerFilePath: meta.viewerFilePath,
|
||||
hidden,
|
||||
};
|
||||
|
||||
// Apply buffered updates that arrived before this tool_call (out-of-order dispatch)
|
||||
const pending = this.pendingUpdates.get(meta.id);
|
||||
if (pending) {
|
||||
entry.status = pending.status;
|
||||
entry.icon = resolveToolIcon({ status: pending.status, kind });
|
||||
if (pending.viewerLinks) entry.viewerLinks = pending.viewerLinks;
|
||||
if (pending.viewerFilePath) entry.viewerFilePath = pending.viewerFilePath;
|
||||
this.pendingUpdates.delete(meta.id);
|
||||
}
|
||||
|
||||
this.entries.push(entry);
|
||||
|
||||
if (this.isFirstFlush) {
|
||||
@ -94,16 +106,24 @@ export class ToolCardState {
|
||||
viewerLinks?: ViewerLinks,
|
||||
viewerFilePath?: string,
|
||||
): void {
|
||||
if (this.finalized) return;
|
||||
|
||||
const entry = this.entries.find((e) => e.id === id);
|
||||
if (!entry) return;
|
||||
if (!entry) {
|
||||
// Buffer the update — tool_call may arrive later (out-of-order concurrent dispatch)
|
||||
this.pendingUpdates.set(id, { status, viewerLinks, viewerFilePath });
|
||||
return;
|
||||
}
|
||||
|
||||
entry.status = status;
|
||||
entry.icon = resolveToolIcon({ status, kind: entry.kind });
|
||||
if (viewerLinks) entry.viewerLinks = viewerLinks;
|
||||
if (viewerFilePath) entry.viewerFilePath = viewerFilePath;
|
||||
|
||||
if (this.finalized) {
|
||||
// Post-finalize update (e.g. last tool completed after card was sealed):
|
||||
// flush immediately so the final status is rendered.
|
||||
this.onFlush(this.snapshot());
|
||||
return;
|
||||
}
|
||||
this.scheduleFlush();
|
||||
}
|
||||
|
||||
@ -143,8 +163,9 @@ export class ToolCardState {
|
||||
|
||||
private snapshot(): ToolCardSnapshot {
|
||||
const visible = this.entries.filter((e) => !e.hidden);
|
||||
const DONE_STATUSES = new Set(["completed", "done", "failed", "error"]);
|
||||
const completedVisible = visible.filter(
|
||||
(e) => e.status === "completed" || e.status === "done",
|
||||
(e) => DONE_STATUSES.has(e.status),
|
||||
).length;
|
||||
const allComplete =
|
||||
visible.length > 0 && completedVisible === visible.length;
|
||||
|
||||
@ -65,24 +65,15 @@ describe("ThinkingIndicator", () => {
|
||||
expect(api.sendMessage).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("dismiss() deletes the Telegram message when msgId exists", async () => {
|
||||
it("dismiss() leaves message in chat (no deleteMessage to save API calls)", async () => {
|
||||
await indicator.show();
|
||||
await indicator.dismiss();
|
||||
expect(api.deleteMessage).toHaveBeenCalledOnce();
|
||||
expect(api.deleteMessage).toHaveBeenCalledWith(100, 42);
|
||||
});
|
||||
|
||||
it("dismiss() does not call deleteMessage when no message was sent", async () => {
|
||||
await indicator.dismiss();
|
||||
expect(api.deleteMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("dismiss() swallows errors from deleteMessage", async () => {
|
||||
api.deleteMessage.mockRejectedValueOnce(new Error("already deleted"));
|
||||
await indicator.show();
|
||||
// Should not throw
|
||||
it("dismiss() is safe when no message was sent", async () => {
|
||||
await indicator.dismiss();
|
||||
expect(api.deleteMessage).toHaveBeenCalledOnce();
|
||||
expect(api.deleteMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("show() works again after dismiss() + reset()", async () => {
|
||||
@ -100,7 +91,7 @@ describe("ThinkingIndicator", () => {
|
||||
expect(api.sendMessage).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("show() deletes just-sent message if dismissed during queue wait (C17)", async () => {
|
||||
it("show() leaves just-sent message if dismissed during queue wait", async () => {
|
||||
// Simulate a slow queue: enqueue holds the promise until we resolve it
|
||||
let resolveEnqueue!: (val: unknown) => void;
|
||||
const slowQueue = {
|
||||
@ -126,9 +117,9 @@ describe("ThinkingIndicator", () => {
|
||||
await resolveEnqueue(undefined);
|
||||
await showPromise;
|
||||
|
||||
// The message was sent but should be immediately deleted
|
||||
// The message was sent but NOT deleted (saves API calls)
|
||||
expect(api.sendMessage).toHaveBeenCalledOnce();
|
||||
expect(api.deleteMessage).toHaveBeenCalledWith(100, 42);
|
||||
expect(api.deleteMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@ -225,16 +216,16 @@ describe("ActivityTracker", () => {
|
||||
expect(api.sendMessage).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("onToolCall() dismisses thinking and deletes message", async () => {
|
||||
it("onToolCall() dismisses thinking (no delete)", async () => {
|
||||
await tracker.onThought();
|
||||
await tracker.onToolCall(makeMeta(), "file_read", { path: "/tmp/foo" });
|
||||
expect(api.deleteMessage).toHaveBeenCalledWith(100, 42);
|
||||
expect(api.deleteMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("onTextStart() dismisses thinking and deletes message", async () => {
|
||||
it("onTextStart() dismisses thinking (no delete)", async () => {
|
||||
await tracker.onThought();
|
||||
await tracker.onTextStart();
|
||||
expect(api.deleteMessage).toHaveBeenCalledWith(100, 42);
|
||||
expect(api.deleteMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sendUsage() is a no-op (usage is sent as separate message by adapter)", async () => {
|
||||
@ -244,10 +235,10 @@ describe("ActivityTracker", () => {
|
||||
expect(api.sendMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("onNewPrompt() dismisses thinking and deletes message", async () => {
|
||||
it("onNewPrompt() dismisses thinking (no delete)", async () => {
|
||||
await tracker.onThought();
|
||||
await tracker.onNewPrompt();
|
||||
expect(api.deleteMessage).toHaveBeenCalledWith(100, 42);
|
||||
expect(api.deleteMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cleanup() finalizes toolCard and dismisses thinking", async () => {
|
||||
@ -259,11 +250,11 @@ describe("ActivityTracker", () => {
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
|
||||
it("onNewPrompt() deletes thinking message", async () => {
|
||||
it("onNewPrompt() dismisses thinking (message left in chat)", async () => {
|
||||
await tracker.onThought();
|
||||
expect(api.sendMessage).toHaveBeenCalledOnce();
|
||||
await tracker.onNewPrompt();
|
||||
expect(api.deleteMessage).toHaveBeenCalledWith(100, 42);
|
||||
expect(api.deleteMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("getToolCardMsgId() returns undefined when no tool content", () => {
|
||||
|
||||
@ -46,12 +46,7 @@ export class ThinkingIndicator {
|
||||
);
|
||||
if (result) {
|
||||
if (this.dismissed) {
|
||||
// dismissed during queue wait — delete the just-sent message
|
||||
try {
|
||||
await this.api.deleteMessage(this.chatId, result.message_id);
|
||||
} catch {
|
||||
// Message may already be deleted
|
||||
}
|
||||
// dismissed during queue wait — message stays in chat (no delete to save API calls)
|
||||
} else {
|
||||
this.msgId = result.message_id;
|
||||
this.startRefreshTimer();
|
||||
@ -64,20 +59,12 @@ export class ThinkingIndicator {
|
||||
}
|
||||
}
|
||||
|
||||
/** Dismiss indicator: stops refresh timer and deletes the Telegram message */
|
||||
/** Dismiss indicator: stops refresh timer. Message is left in chat to reduce API calls. */
|
||||
async dismiss(): Promise<void> {
|
||||
if (this.dismissed) return;
|
||||
this.dismissed = true;
|
||||
this.stopRefreshTimer();
|
||||
const msgId = this.msgId;
|
||||
this.msgId = undefined;
|
||||
if (msgId) {
|
||||
try {
|
||||
await this.api.deleteMessage(this.chatId, msgId);
|
||||
} catch {
|
||||
// Message may already be deleted
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Reset for a new prompt cycle */
|
||||
@ -128,7 +115,7 @@ export class ToolCard {
|
||||
private msgId?: number;
|
||||
private lastSentText?: string;
|
||||
private flushPromise: Promise<void> = Promise.resolve();
|
||||
private overflowCount = 0;
|
||||
private overflowMsgIds: number[] = [];
|
||||
|
||||
constructor(
|
||||
private api: Bot["api"],
|
||||
@ -217,18 +204,29 @@ export class ToolCard {
|
||||
if (result) this.msgId = result.message_id;
|
||||
}
|
||||
|
||||
// Overflow chunks: always send as new messages
|
||||
// Overflow chunks: edit existing overflow messages or send new ones
|
||||
for (let i = 1; i < chunks.length; i++) {
|
||||
// Only send overflow chunks that haven't been sent yet
|
||||
if (i > this.overflowCount) {
|
||||
const overflowIdx = i - 1; // index into overflowMsgIds
|
||||
if (overflowIdx < this.overflowMsgIds.length) {
|
||||
// Edit existing overflow message
|
||||
await this.sendQueue.enqueue(() =>
|
||||
this.api.editMessageText(
|
||||
this.chatId,
|
||||
this.overflowMsgIds[overflowIdx],
|
||||
chunks[i],
|
||||
{ parse_mode: "HTML" },
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Send new overflow message
|
||||
const result = await this.sendQueue.enqueue(() =>
|
||||
this.api.sendMessage(this.chatId, chunks[i], {
|
||||
message_thread_id: this.threadId,
|
||||
parse_mode: "HTML",
|
||||
disable_notification: true,
|
||||
}),
|
||||
);
|
||||
this.overflowCount = i;
|
||||
if (result) this.overflowMsgIds.push(result.message_id);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@ -243,6 +241,7 @@ export class ActivityTracker {
|
||||
private isFirstEvent = true;
|
||||
private thinking: ThinkingIndicator;
|
||||
private toolCard: ToolCard;
|
||||
private previousToolCard?: ToolCard;
|
||||
private verbosity: DisplayVerbosity;
|
||||
|
||||
constructor(
|
||||
@ -303,6 +302,9 @@ export class ActivityTracker {
|
||||
private async sealToolCardIfNeeded(): Promise<void> {
|
||||
if (!this.toolCard.hasContent()) return;
|
||||
await this.toolCard.finalize();
|
||||
// Keep reference so late tool_updates (e.g. last tool completing after text starts)
|
||||
// can still reach the sealed card and update its status.
|
||||
this.previousToolCard = this.toolCard;
|
||||
this.toolCard = new ToolCard(
|
||||
this.api,
|
||||
this.chatId,
|
||||
@ -319,6 +321,9 @@ export class ActivityTracker {
|
||||
viewerFilePath?: string,
|
||||
): Promise<void> {
|
||||
this.toolCard.updateTool(id, status, viewerLinks, viewerFilePath);
|
||||
// Forward to previous sealed card — the tool may belong there if text/thought
|
||||
// started before this tool's completion update arrived.
|
||||
this.previousToolCard?.updateTool(id, status, viewerLinks, viewerFilePath);
|
||||
}
|
||||
|
||||
async onPlan(entries: PlanEntry[]): Promise<void> {
|
||||
|
||||
@ -847,6 +847,16 @@ export class TelegramAdapter extends MessagingAdapter {
|
||||
|
||||
// --- MessagingAdapter overrides ---
|
||||
|
||||
/**
|
||||
* Per-session serial dispatch queues.
|
||||
* SessionBridge fires sendMessage() as fire-and-forget, so multiple events
|
||||
* (tool_call, tool_update, text) can arrive concurrently. Without serialization,
|
||||
* fast handlers (tool_update) overtake slow ones (tool_call with draftManager.finalize),
|
||||
* causing out-of-order processing where a tool's completion update is processed before
|
||||
* its creation event. This queue ensures events are processed in the order they arrive.
|
||||
*/
|
||||
private _dispatchQueues = new Map<string, Promise<void>>();
|
||||
|
||||
async sendMessage(
|
||||
sessionId: string,
|
||||
content: OutgoingMessage,
|
||||
@ -869,13 +879,20 @@ export class TelegramAdapter extends MessagingAdapter {
|
||||
return;
|
||||
}
|
||||
|
||||
// Store threadId for handlers to use (keyed by sessionId for concurrency safety)
|
||||
this._sessionThreadIds.set(sessionId, threadId);
|
||||
try {
|
||||
await super.sendMessage(sessionId, content);
|
||||
} finally {
|
||||
this._sessionThreadIds.delete(sessionId);
|
||||
}
|
||||
// Serialize dispatch per session to preserve event ordering
|
||||
const prev = this._dispatchQueues.get(sessionId) ?? Promise.resolve();
|
||||
const next = prev.then(async () => {
|
||||
this._sessionThreadIds.set(sessionId, threadId);
|
||||
try {
|
||||
await super.sendMessage(sessionId, content);
|
||||
} finally {
|
||||
this._sessionThreadIds.delete(sessionId);
|
||||
}
|
||||
}).catch((err) => {
|
||||
log.warn({ err, sessionId }, "Dispatch queue error");
|
||||
});
|
||||
this._dispatchQueues.set(sessionId, next);
|
||||
await next;
|
||||
}
|
||||
|
||||
protected async handleThought(
|
||||
@ -893,13 +910,10 @@ export class TelegramAdapter extends MessagingAdapter {
|
||||
content: OutgoingMessage,
|
||||
): Promise<void> {
|
||||
const threadId = this.getThreadId(sessionId);
|
||||
// CRITICAL: This handler must be fully synchronous to preserve text ordering.
|
||||
// sendMessage() is not awaited in wireSessionEvents, so multiple text events
|
||||
// run concurrently. Any await here creates a gap where subsequent text events
|
||||
// process first, causing out-of-order buffer accumulation.
|
||||
// Per-session dispatch queue serializes all events, so we can safely await here.
|
||||
if (!this.draftManager.hasDraft(sessionId)) {
|
||||
const tracker = this.getOrCreateTracker(sessionId, threadId);
|
||||
tracker.onTextStart().catch(() => {}); // Fire-and-forget, no await
|
||||
await tracker.onTextStart();
|
||||
}
|
||||
const draft = this.draftManager.getOrCreate(sessionId, threadId);
|
||||
draft.append(content.text);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user