Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/app/managers/question-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import type { Question, QuestionState, QuestionAnswer } from "../types/question.
import { logger } from "../../utils/logger.js";

class QuestionManager {
private resolvedRequestIDs = new Set<string>();

private state: QuestionState = {
questions: [],
currentIndex: 0,
Expand Down Expand Up @@ -201,6 +203,15 @@ class QuestionManager {
isActive: false,
requestID: null,
};
this.resolvedRequestIDs.clear();
}

markResolved(requestID: string): void {
this.resolvedRequestIDs.add(requestID);
}

isResolved(requestID: string): boolean {
return this.resolvedRequestIDs.has(requestID);
}

getAllAnswers(): QuestionAnswer[] {
Expand Down
32 changes: 29 additions & 3 deletions src/app/managers/summary-aggregation-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ type ToolFileCallback = (fileInfo: ToolFileInfo) => void;

type QuestionCallback = (questions: Question[], requestID: string, sessionId: string) => void;

type QuestionResolvedCallback = (sessionId: string, requestID: string) => void | Promise<void>;

type QuestionErrorCallback = () => void;

type ThinkingCallback = (update: ThinkingUpdate) => void;
Expand Down Expand Up @@ -295,6 +297,7 @@ class SummaryAggregator {
private onRootToolUpdateCallback: RootToolUpdateCallback | null = null;
private onToolFileCallback: ToolFileCallback | null = null;
private onQuestionCallback: QuestionCallback | null = null;
private onQuestionResolvedCallback: QuestionResolvedCallback | null = null;
private onQuestionErrorCallback: QuestionErrorCallback | null = null;
private onThinkingCallback: ThinkingCallback | null = null;
private onThinkingFinishedCallback: ThinkingFinishedCallback | null = null;
Expand Down Expand Up @@ -369,6 +372,10 @@ class SummaryAggregator {
this.onQuestionCallback = callback;
}

setOnQuestionResolved(callback: QuestionResolvedCallback): void {
this.onQuestionResolvedCallback = callback;
}

setOnQuestionError(callback: QuestionErrorCallback): void {
this.onQuestionErrorCallback = callback;
}
Expand Down Expand Up @@ -523,10 +530,8 @@ class SummaryAggregator {
this.handleQuestionAsked(event);
break;
case "question.replied":
logger.info(`[Aggregator] Question replied: requestID=${event.properties.requestID}`);
break;
case "question.rejected":
logger.info(`[Aggregator] Question rejected: requestID=${event.properties.requestID}`);
this.handleQuestionResolved(event);
break;
case "session.diff":
this.handleSessionDiff(event);
Expand Down Expand Up @@ -2308,6 +2313,27 @@ class SummaryAggregator {
});
}
}

private handleQuestionResolved(
event: Event & {
type: "question.replied" | "question.rejected";
},
): void {
const { sessionID, requestID } = event.properties;

logger.info(`[Aggregator] Question resolved: requestID=${requestID}`);

if (this.onQuestionResolvedCallback) {
const callback = this.onQuestionResolvedCallback;
setImmediate(async () => {
try {
await callback(sessionID, requestID);
} catch (err) {
logger.error("[Aggregator] Error in question resolved callback:", err);
}
});
}
}
}

export const summaryAggregator = new SummaryAggregator();
13 changes: 13 additions & 0 deletions src/bot/menus/question-menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ export async function showCurrentQuestion(bot: Context["api"], chatId: number):

logger.debug(`[QuestionHandler] Sending message with keyboard, chatId=${chatId}`);

const requestID = questionManager.getRequestID();

try {
const { messageId } = await sendRenderedBotPart({
api: bot,
Expand All @@ -136,6 +138,17 @@ export async function showCurrentQuestion(bot: Context["api"], chatId: number):
reply_markup: keyboard,
},
});

if (!questionManager.isActive() || questionManager.getRequestID() !== requestID) {
logger.info(
`[QuestionHandler] Discarding question message resolved while it was being sent: messageId=${messageId}`,
);
await bot.deleteMessage(chatId, messageId).catch((err) => {
logger.warn(`[QuestionHandler] Failed to delete stale question message ${messageId}:`, err);
});
return;
}

questionManager.addMessageId(messageId);

logger.debug(`[QuestionHandler] Message sent, messageId=${messageId}`);
Expand Down
99 changes: 98 additions & 1 deletion src/bot/services/event-subscription-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,13 @@ import {
import { buildBackgroundSessionOpenKeyboard } from "../menus/session-selection-menu.js";
import { questionManager } from "../../app/managers/question-manager.js";
import { permissionManager } from "../../app/managers/permission-manager.js";
import { showCurrentQuestion } from "../menus/question-menu.js";
import { clearQuestionInteraction, showCurrentQuestion } from "../menus/question-menu.js";
import { showPermissionRequest, syncPermissionInteractionState } from "../menus/permission-menu.js";
import {
clearAllInteractionState,
interactionManager,
} from "../../app/managers/interaction-manager.js";
import { opencodeClient } from "../../opencode/client.js";
import { stopEventListening, subscribeToEvents } from "../../opencode/events.js";

const TELEGRAM_DOCUMENT_CAPTION_MAX_LENGTH = 1024;
Expand Down Expand Up @@ -510,6 +511,82 @@ class EventSubscriptionService implements BotEventSubscriptionService {
}
}

private async clearResolvedQuestion(requestID: string, reason: string): Promise<void> {
const isActivePoll = questionManager.getRequestID() === requestID;
const messageIds: number[] = [];

if (isActivePoll) {
messageIds.push(...questionManager.getMessageIds());
// Clear the local state before touching Telegram: if the deletion hangs,
// the command guard is already released (same order as permissions).
clearQuestionInteraction(reason);
questionManager.clear();
}

// Always remember the request as resolved so a late delivery of the same
// question (message still in flight, or asked event arriving after the
// resolution) is discarded instead of resurrecting a stale poll.
questionManager.markResolved(requestID);

if (messageIds.length > 0 && this.botInstance && this.chatIdInstance) {
const api = this.botInstance.api;
const chatId = this.chatIdInstance;
await Promise.all(
messageIds.map((messageId) =>
api.deleteMessage(chatId, messageId).catch((err) => {
logger.warn(`[Bot] Failed to delete resolved question message ${messageId}:`, err);
}),
),
);
}

if (isActivePoll) {
logger.info(
`[Bot] Cleared resolved question: requestID=${requestID}, messages=${messageIds.length}, reason=${reason}`,
);
}
}

private async reconcileStaleQuestionOnIdle(sessionId: string): Promise<void> {
if (!questionManager.isActive()) {
return;
}

const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
return;
}

const requestID = questionManager.getRequestID();
if (!requestID) {
return;
}

// Verify against the server before clearing: a genuinely pending question
// keeps the session busy, but a lost `question.replied`/`question.rejected`
// SSE event would otherwise leave a stale poll blocking every command.
const { data, error } = await opencodeClient.question.list({
directory: currentSession.directory,
});

if (error || !data) {
// Do not clear on a failed lookup: without server confirmation we cannot
// tell a stale poll from a live one, and clearing a live card would be a
// regression.
logger.warn(
`[Bot] Could not verify pending question on session idle; keeping poll: requestID=${requestID}`,
error,
);
return;
}

if (data.some((request) => request.id === requestID)) {
return;
}

await this.clearResolvedQuestion(requestID, "question_stale_on_session_idle");
}

private appendToolDuration(message: string, sessionId: string, callId: string): string {
const cacheKey = this.getToolCacheKey(sessionId, callId);
const durationMs = this.completedToolDurations.get(cacheKey);
Expand Down Expand Up @@ -957,6 +1034,13 @@ class EventSubscriptionService implements BotEventSubscriptionService {
this.toolCallStreamer.flushSession(currentSession.id, "question_asked"),
]);

if (questionManager.isResolved(requestID)) {
logger.info(
`[Bot] Skipping already resolved question: requestID=${requestID}, reason=question_resolved_before_asked`,
);
return;
}

if (questionManager.isActive()) {
logger.warn("[Bot] Replacing active poll with a new one");

Expand Down Expand Up @@ -988,6 +1072,10 @@ class EventSubscriptionService implements BotEventSubscriptionService {
clearAllInteractionState("question_error");
});

summaryAggregator.setOnQuestionResolved(async (_sessionId, requestID) => {
await this.clearResolvedQuestion(requestID, "question_resolved_externally");
});

summaryAggregator.setOnPermission(async (request) => {
const generation = permissionManager.getGeneration();

Expand Down Expand Up @@ -1176,6 +1264,15 @@ class EventSubscriptionService implements BotEventSubscriptionService {
});

summaryAggregator.setOnSessionIdle(async (sessionId) => {
// Background task: `question.list` has no timeout, so awaiting it here
// would block the whole idle finalization (finishRun, tool flush, footer,
// queue) if the server hangs. A throw inside the callback must not
// truncate the idle either.
safeBackgroundTask({
taskName: "question.reconcileOnSessionIdle",
task: () => this.reconcileStaleQuestionOnIdle(sessionId),
});

// Runs before the early returns below: the fallback must apply even when
// the session is no longer the current one when it eventually renames.
safeBackgroundTask({
Expand Down
Loading
Loading