Skip to content

The open alternative to Salesforce, designed for AI.

fix(ai-chat) - fix AI chat questions stuck on 'already been answered' after interrupted streams (#25175)

Etiennef7420443883c
diff --git a/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts b/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts
index e505f923b43..3223033cad5 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts
@@ -15,10 +15,12 @@ import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/a
import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
import { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';
import { agentChatUploadedFilesState } from '@/ai/states/agentChatUploadedFilesState';
+import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
import { markQuestionAnswered } from '@/ai/utils/markQuestionAnswered';
import { markQuestionPending } from '@/ai/utils/markQuestionPending';
import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';
import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
+import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
export const useSubmitQuestionAnswer = () => {
const apolloClient = useApolloClient();
@@ -94,18 +96,23 @@ export const useSubmitQuestionAnswer = () => {
dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);
} catch (error) {
- const currentMessages = store.get(messagesAtom);
-
store.set(isAwaitingFirstChunkAtom, false);
- store.set(
- messagesAtom,
- markQuestionPending(currentMessages, messageId, toolCallId),
- );
store.set(agentChatUploadedFilesState.atom, (currentUploadedFiles) => [
...uploadedFiles,
...currentUploadedFiles,
]);
+ if (isGraphqlErrorOfType(error, AiChatErrorCode.QUESTION_NOT_PENDING)) {
+ dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);
+ } else {
+ const currentMessages = store.get(messagesAtom);
+
+ store.set(
+ messagesAtom,
+ markQuestionPending(currentMessages, messageId, toolCallId),
+ );
+ }
+
enqueueErrorSnackBar({
apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,
});
diff --git a/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts b/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts
index bb534f76deb..e12d2783a39 100644
--- a/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts
+++ b/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts
@@ -3,4 +3,5 @@ export const AiChatErrorCode = {
CONTEXT_WINDOW_EXCEEDED: 'CONTEXT_WINDOW_EXCEEDED',
API_KEY_NOT_CONFIGURED: 'API_KEY_NOT_CONFIGURED',
CONNECTION_LOST: 'CONNECTION_LOST',
+ QUESTION_NOT_PENDING: 'QUESTION_NOT_PENDING',
} as const;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
index 28f1ceb4414..115ab0aa399 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
@@ -546,6 +546,15 @@ export class AgentChatStreamingService {
modelId?: string;
fileAttachments?: AiChatFileAttachment[];
}): Promise<{ streamId: string; turnId: string | null }> {
+ const thread = await this.threadRepository.findOne(workspace.id, {
+ where: { id: threadId },
+ select: ['id', 'activeStreamId'],
+ });
+
+ if (isDefined(thread)) {
+ await this.reapDeadStream({ thread, workspaceId: workspace.id });
+ }
+
const streamId = generateId();
await this.streamHeartbeatService.markClaimed(streamId);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
index 97b673c6e4e..a42f948682d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
@@ -713,14 +713,27 @@ export class AgentChatService {
const claim = await this.threadRepository.update(
workspaceId,
{ id: threadId, pendingQuestionMessageId: messageId },
- { pendingQuestionMessageId: null, activeStreamId: streamId },
+ {
+ pendingQuestionMessageId: null,
+ activeStreamId: streamId,
+ lastStreamError: null,
+ },
);
if ((claim.affected ?? 0) === 0) {
- throw new AiException(
- 'No pending question to answer',
- AiExceptionCode.QUESTION_NOT_PENDING,
- );
+ const adopted = await this.claimOrphanedQuestion({
+ threadId,
+ messageId,
+ streamId,
+ workspaceId,
+ });
+
+ if (!adopted) {
+ throw new AiException(
+ 'No pending question to answer',
+ AiExceptionCode.QUESTION_NOT_PENDING,
+ );
+ }
}
try {
@@ -757,6 +770,47 @@ export class AgentChatService {
};
}
+ private async claimOrphanedQuestion({
+ threadId,
+ messageId,
+ streamId,
+ workspaceId,
+ }: {
+ threadId: string;
+ messageId: string;
+ streamId: string;
+ workspaceId: string;
+ }): Promise<boolean> {
+ const latestAssistantMessage = await this.messageRepository.findOne(
+ workspaceId,
+ {
+ where: { threadId, role: AgentMessageRole.ASSISTANT },
+ order: {
+ processedAt: { direction: 'DESC', nulls: 'LAST' },
+ createdAt: 'DESC',
+ id: 'DESC',
+ },
+ select: ['id'],
+ },
+ );
+
+ if (latestAssistantMessage?.id !== messageId) {
+ return false;
+ }
+
+ const claim = await this.threadRepository.update(
+ workspaceId,
+ {
+ id: threadId,
+ pendingQuestionMessageId: IsNull(),
+ activeStreamId: IsNull(),
+ },
+ { activeStreamId: streamId, lastStreamError: null },
+ );
+
+ return (claim.affected ?? 0) > 0;
+ }
+
async restorePendingQuestion({
threadId,
messageId,