Skip to content

The open alternative to Salesforce, designed for AI.

Close a thread's pending question through one function (#27559)

Félix Malfaitdbfc2ea1336a
diff --git a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
index 3a1ca46872c..96648366c22 100644
--- a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
+++ b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
@@ -233,7 +233,6 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
upgradeFence as never,
),
chatThreadService,
- {} as never,
upgradeFence as never,
);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-suspension.service.close-awaited-calls.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-suspension.service.close-awaited-calls.spec.ts
new file mode 100644
index 00000000000..196735f57d0
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-suspension.service.close-awaited-calls.spec.ts
@@ -0,0 +1,88 @@
+import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
+import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
+
+const buildService = ({
+ pendingQuestionMessageId = 'question-message-id' as string | null,
+ isAwaitedByCaller = true,
+} = {}) => {
+ const threadRepository = {
+ findOne: jest
+ .fn()
+ .mockResolvedValue(
+ pendingQuestionMessageId === null
+ ? null
+ : { id: 'thread-id', pendingQuestionMessageId },
+ ),
+ };
+ const messagePartRepository = {
+ query: jest.fn().mockResolvedValue(undefined),
+ find: jest.fn().mockResolvedValue([
+ {
+ toolOutput: {
+ result: { status: 'pending' },
+ awaitedByCaller: isAwaitedByCaller,
+ },
+ },
+ ]),
+ };
+ const threadLifecycleService = {
+ closePendingQuestion: jest.fn().mockResolvedValue(undefined),
+ };
+
+ const service = new AgentRunSuspensionService(
+ {} as never,
+ threadRepository as never,
+ messagePartRepository as never,
+ threadLifecycleService as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ );
+
+ return { service, threadLifecycleService };
+};
+
+describe('AgentRunSuspensionService closeAwaitedCalls', () => {
+ it('closes the question a dropped run waited on, cancelling the turn that asked it', async () => {
+ const { service, threadLifecycleService } = buildService();
+
+ await service.closeAwaitedCalls({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ });
+
+ expect(threadLifecycleService.closePendingQuestion).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ messageId: 'question-message-id',
+ activeStreamId: null,
+ turnStatus: AgentTurnStatus.CANCELLED,
+ });
+ });
+
+ it('keeps open a question the member asked of their own', async () => {
+ const { service, threadLifecycleService } = buildService({
+ isAwaitedByCaller: false,
+ });
+
+ await service.closeAwaitedCalls({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ });
+
+ expect(threadLifecycleService.closePendingQuestion).not.toHaveBeenCalled();
+ });
+
+ it('does nothing when the conversation waits on no question', async () => {
+ const { service, threadLifecycleService } = buildService({
+ pendingQuestionMessageId: null,
+ });
+
+ await service.closeAwaitedCalls({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ });
+
+ expect(threadLifecycleService.closePendingQuestion).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts
index 144ebfd1375..29f75fa3116 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts
@@ -13,7 +13,6 @@ import { PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/se
import { CONTINUE_AGENT_RUN_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/continue-agent-run-job-name.constant';
import { AgentRunSuspensionEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-run-suspension.entity';
import { AGENT_WAIT_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/agent-wait-tool-names.constant';
-import { closeOpenToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util';
import { readProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-proposed-tool-call-answer.util';
import { buildWaitOutcomeToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-outcome-tool-output.util';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
@@ -22,12 +21,11 @@ import { type AgentRunCallerOutcome } from 'src/engine/metadata-modules/ai/ai-ag
import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
import { type ContinueAgentRunJobData } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/continue-agent-run-job-data.type';
import { isToolOutputAwaitedByCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/is-tool-output-awaited-by-caller.util';
-import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service';
+import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service';
import { isUniqueViolationError } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-unique-violation-error.util';
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
-import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
import {
@@ -47,8 +45,7 @@ export class AgentRunSuspensionService {
private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
@InjectAgentHistoryRepository('agentMessagePart')
private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
- private readonly threadRecordEventService: AgentChatThreadRecordEventService,
- private readonly turnRecorderService: AgentTurnRecorderService,
+ private readonly threadLifecycleService: AgentChatThreadLifecycleService,
private readonly pendingWakeUpService: PendingWakeUpService,
private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
@InjectMessageQueue(MessageQueue.aiQueue)
@@ -331,33 +328,12 @@ export class AgentRunSuspensionService {
return;
}
- const { affected } = await this.threadRepository.update(
- workspaceId,
- { id: threadId, pendingQuestionMessageId, activeStreamId: IsNull() },
- { pendingQuestionMessageId: null },
- );
-
- if (affected === 0) {
- return;
- }
-
- await this.threadRecordEventService.emitPendingQuestionCleared({
+ await this.threadLifecycleService.closePendingQuestion({
workspaceId,
threadId,
messageId: pendingQuestionMessageId,
- });
-
- // the question is already cleared, so its calls must close before anything else can fail
- await closeOpenToolParts({
- messagePartRepository: this.messagePartRepository,
- messageId: pendingQuestionMessageId,
- workspaceId,
- });
-
- await this.turnRecorderService.endWaitingTurn({
- workspaceId,
- messageId: pendingQuestionMessageId,
- status: AgentTurnStatus.CANCELLED,
+ activeStreamId: null,
+ turnStatus: AgentTurnStatus.CANCELLED,
});
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts
index fdb7217cbe6..40329c38595 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts
@@ -77,7 +77,6 @@ const buildResolver = () => {
recordEvents as never,
{} as never,
threadService,
- {} as never,
{ hasUpgradedAgentHistory: jest.fn().mockResolvedValue(true) } as never,
);
const streaming = {
@@ -99,6 +98,7 @@ const buildResolver = () => {
{} as never,
recordEvents as never,
{} as never,
+ {} as never,
);
const resolver = new AgentChatResolver(
chatService,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
index 5263566c1f2..4a98528e32e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
@@ -1,8 +1,7 @@
-import { IsNull } from 'typeorm';
-
import { AgentChatStreamRecoveryService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';
const QUESTIONS = [
@@ -81,7 +80,6 @@ describe('AgentChatStreamingService claim & reap', () => {
addMessage: jest
.fn()
.mockResolvedValue({ id: 'user-message-id', turnId: 'turn-id' }),
- closePendingToolCalls: jest.fn().mockResolvedValue(undefined),
getMessagesForThread: jest.fn().mockResolvedValue([]),
getThreadContexts: jest.fn().mockResolvedValue([]),
getQueuedMessages: jest.fn().mockResolvedValue(queuedMessages),
@@ -92,6 +90,9 @@ describe('AgentChatStreamingService claim & reap', () => {
promoteQueuedMessage: jest.fn().mockResolvedValue('turn-id'),
deleteQueuedMessage: jest.fn().mockResolvedValue(true),
};
+ const threadLifecycleService = {
+ closePendingQuestion: jest.fn().mockResolvedValue(undefined),
+ };
const messagePartRepository = {
find: jest.fn().mockResolvedValue([
{
@@ -157,6 +158,7 @@ describe('AgentChatStreamingService claim & reap', () => {
assertConversationNotSuspended: jest.fn().mockResolvedValue(undefined),
} as never,
{ withThreadLockForMessage: jest.fn(({ work }) => work()) } as never,
+ threadLifecycleService as never,
);
return {
@@ -173,6 +175,7 @@ describe('AgentChatStreamingService claim & reap', () => {
threadRepository,
messageQueueService,
agentChatService,
+ threadLifecycleService,
eventPublisherService,
streamHeartbeatService,
publishedEvents,
@@ -267,26 +270,33 @@ describe('AgentChatStreamingService claim & reap', () => {
};
it('closes the pending call as skipped before streaming, unless an answer holds the stream', async () => {
- const { send, agentChatService, messageQueueService } = buildService({
- thread: waitingThread,
- });
+ const { send, threadLifecycleService, messageQueueService } =
+ buildService({
+ thread: waitingThread,
+ });
const result = await send();
expect(result.queued).toBe(false);
- expect(agentChatService.closePendingToolCalls).toHaveBeenCalledWith({
+ expect(threadLifecycleService.closePendingQuestion).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
threadId: 'thread-id',
messageId: 'question-message-id',
- workspaceId: 'workspace-id',
- where: { activeStreamId: IsNull() },
+ activeStreamId: null,
+ turnStatus: AgentTurnStatus.COMPLETED,
});
expect(
- agentChatService.closePendingToolCalls.mock.invocationCallOrder[0],
+ threadLifecycleService.closePendingQuestion.mock.invocationCallOrder[0],
).toBeLessThan(messageQueueService.add.mock.invocationCallOrder[0]);
});
it('refuses a message while a caller waits on the pending call', async () => {
- const { send, agentChatService, messageQueueService } = buildService({
+ const {
+ send,
+ agentChatService,
+ threadLifecycleService,
+ messageQueueService,
+ } = buildService({
thread: waitingThread,
pendingToolOutput: {
result: { questions: QUESTIONS, status: 'pending' },
@@ -297,7 +307,9 @@ describe('AgentChatStreamingService claim & reap', () => {
await expect(send()).rejects.toMatchObject({
code: AiExceptionCode.THREAD_AWAITING_ANSWER,
});
- expect(agentChatService.closePendingToolCalls).not.toHaveBeenCalled();
+ expect(
+ threadLifecycleService.closePendingQuestion,
+ ).not.toHaveBeenCalled();
expect(agentChatService.addMessage).not.toHaveBeenCalled();
expect(agentChatService.queueMessage).not.toHaveBeenCalled();
expect(messageQueueService.add).not.toHaveBeenCalled();
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.opening-turn.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.opening-turn.spec.ts
index af42ee4a1f6..517b1ef11bb 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.opening-turn.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.opening-turn.spec.ts
@@ -71,6 +71,7 @@ describe('AgentChatStreamingService.startOpeningTurn', () => {
{} as never,
{} as never,
{} as never,
+ {} as never,
);
return {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts
index 009a60aa0bf..7b75df6185e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts
@@ -113,6 +113,7 @@ describe('AgentChatStreamingService.retryLastFailedTurn', () => {
turnRecorderService as never,
{} as never,
{} as never,
+ {} as never,
);
return {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts
index ddbcd5a547c..e640920a7f7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts
@@ -66,6 +66,7 @@ const build = () => {
{} as never,
{} as never,
{} as never,
+ {} as never,
);
return { service, threads, queue, chat, actors, heartbeat };
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-thread-lifecycle.service.close-pending-question.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-thread-lifecycle.service.close-pending-question.spec.ts
new file mode 100644
index 00000000000..4937ca978e0
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-thread-lifecycle.service.close-pending-question.spec.ts
@@ -0,0 +1,153 @@
+import { IsNull } from 'typeorm';
+
+import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service';
+import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
+
+const QUESTION = {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+};
+
+const buildService = ({ claimAffected = 1 } = {}) => {
+ const steps: string[] = [];
+ const threadRepository = {
+ update: jest.fn(async () => {
+ steps.push('clear question');
+
+ return { affected: claimAffected };
+ }),
+ };
+ const threadRecordEventService = {
+ emitPendingQuestionCleared: jest.fn(async () => {
+ steps.push('emit');
+ }),
+ };
+ const turnRecorderService = {
+ endWaitingTurn: jest.fn(async () => {
+ steps.push('end turn');
+ }),
+ };
+ const writePart = jest.fn(async () => {
+ steps.push('close part');
+ });
+ const messagePartRepository = {
+ find: jest.fn().mockResolvedValue([
+ {
+ id: 'part-id',
+ toolName: 'ask_question',
+ toolInput: QUESTION,
+ toolOutput: { result: { question: QUESTION, status: 'pending' } },
+ },
+ ]),
+ query: jest.fn(async (_workspaceId, run) =>
+ run({ table: (name: string) => name, manager: { query: writePart } }),
+ ),
+ };
+
+ const service = new AgentChatThreadLifecycleService(
+ threadRepository as never,
+ {} as never,
+ {} as never,
+ threadRecordEventService as never,
+ turnRecorderService as never,
+ messagePartRepository as never,
+ );
+
+ return {
+ service,
+ steps,
+ threadRepository,
+ writePart,
+ threadRecordEventService,
+ turnRecorderService,
+ };
+};
+
+const closeArguments = {
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ messageId: 'question-message-id',
+ activeStreamId: null,
+ turnStatus: AgentTurnStatus.CANCELLED,
+} as const;
+
+describe('AgentChatThreadLifecycleService closePendingQuestion', () => {
+ it('closes the pending call as skipped and ends the waiting turn with the status given', async () => {
+ const { service, writePart, turnRecorderService } = buildService();
+
+ await service.closePendingQuestion(closeArguments);
+
+ const [[closeQuery, [partId, closedToolOutput, expectedStatus]]] = writePart
+ .mock.calls as unknown as [[string, [string, string, string]]];
+
+ expect(closeQuery).toContain(`"toolOutput"->'result'->>'status' = $3`);
+ expect({ partId, expectedStatus }).toEqual({
+ partId: 'part-id',
+ expectedStatus: 'pending',
+ });
+ expect(JSON.parse(closedToolOutput).result).toEqual({
+ question: QUESTION,
+ status: 'skipped',
+ });
+ expect(turnRecorderService.endWaitingTurn).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ messageId: 'question-message-id',
+ status: AgentTurnStatus.CANCELLED,
+ });
+ });
+
+ it('tells open chat lists last, once the calls and the turn are closed', async () => {
+ const { service, steps, threadRecordEventService } = buildService();
+
+ await service.closePendingQuestion(closeArguments);
+
+ expect(steps).toEqual(['clear question', 'close part', 'end turn', 'emit']);
+ expect(
+ threadRecordEventService.emitPendingQuestionCleared,
+ ).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ messageId: 'question-message-id',
+ });
+ });
+
+ it('only claims the question while no stream, or the stream given, holds the thread', async () => {
+ const { service, threadRepository } = buildService();
+
+ await service.closePendingQuestion(closeArguments);
+ await service.closePendingQuestion({
+ ...closeArguments,
+ activeStreamId: 'stream-id',
+ });
+
+ expect(threadRepository.update.mock.calls).toEqual([
+ [
+ 'workspace-id',
+ {
+ id: 'thread-id',
+ pendingQuestionMessageId: 'question-message-id',
+ activeStreamId: IsNull(),
+ },
+ { pendingQuestionMessageId: null },
+ ],
+ [
+ 'workspace-id',
+ {
+ id: 'thread-id',
+ pendingQuestionMessageId: 'question-message-id',
+ activeStreamId: 'stream-id',
+ },
+ { pendingQuestionMessageId: null },
+ ],
+ ]);
+ });
+
+ it('leaves the calls as they are when another caller already closed the question', async () => {
+ const { service, steps } = buildService({ claimAffected: 0 });
+
+ await service.closePendingQuestion(closeArguments);
+
+ expect(steps).toEqual(['clear question']);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.ts
deleted file mode 100644
index 1b88a8e5319..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-import { IsNull } from 'typeorm';
-
-import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
-import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
-
-const QUESTIONS = [
- {
- header: 'Plan',
- question: 'Which plan?',
- options: [{ label: 'Pro' }, { label: 'Team' }],
- },
-];
-
-const buildService = ({ claimAffected = 1 } = {}) => {
- const threadRepository = {
- update: jest.fn().mockResolvedValue({ affected: claimAffected }),
- };
- const threadRecordEventService = {
- emitPendingQuestionCleared: jest.fn().mockResolvedValue(undefined),
- };
- const turnRecorderService = {
- endWaitingTurn: jest.fn().mockResolvedValue(undefined),
- };
- const messagePartRepository = {
- find: jest.fn().mockResolvedValue([
- {
- id: 'part-id',
- toolName: 'ask_question',
- toolInput: QUESTIONS[0],
- toolOutput: { result: { question: QUESTIONS[0], status: 'pending' } },
- },
- ]),
- writePart: jest.fn(),
- query: jest.fn(),
- };
-
- messagePartRepository.query.mockImplementation(async (_workspaceId, run) =>
- run({
- table: (name: string) => name,
- manager: { query: messagePartRepository.writePart },
- }),
- );
-
- const service = new AgentChatService(
- threadRepository as never,
- {} as never,
- {} as never,
- messagePartRepository as never,
- {} as never,
- {} as never,
- {} as never,
- threadRecordEventService as never,
- {} as never,
- {} as never,
- turnRecorderService as never,
- { hasUpgradedAgentHistory: jest.fn().mockResolvedValue(true) } as never,
- );
-
- return {
- service,
- threadRepository,
- messagePartRepository,
- threadRecordEventService,
- turnRecorderService,
- };
-};
-
-const closeArguments = {
- threadId: 'thread-id',
- messageId: 'question-message-id',
- workspaceId: 'workspace-id',
- where: { activeStreamId: IsNull() },
-};
-
-describe('AgentChatService closePendingToolCalls', () => {
- it('stops waiting and closes the pending call as skipped', async () => {
- const {
- service,
- threadRepository,
- messagePartRepository,
- turnRecorderService,
- } = buildService();
-
- await service.closePendingToolCalls(closeArguments);
-
- expect(turnRecorderService.endWaitingTurn).toHaveBeenCalledWith({
- workspaceId: 'workspace-id',
- messageId: 'question-message-id',
- status: AgentTurnStatus.COMPLETED,
- });
-
- expect(threadRepository.update).toHaveBeenCalledWith(
- 'workspace-id',
- {
- id: 'thread-id',
- pendingQuestionMessageId: 'question-message-id',
- activeStreamId: IsNull(),
- },
- { pendingQuestionMessageId: null },
- );
- const [[closeQuery, [partId, closedToolOutput, expectedStatus]]] =
- messagePartRepository.writePart.mock.calls;
-
- expect(closeQuery).toContain(`"toolOutput"->'result'->>'status' = $3`);
-
- expect({ partId, expectedStatus }).toEqual({
- partId: 'part-id',
- expectedStatus: 'pending',
- });
- expect(JSON.parse(closedToolOutput).result).toEqual({
- question: QUESTIONS[0],
- status: 'skipped',
- });
- });
-
- it('tells open chat lists the conversation no longer waits on an answer', async () => {
- const { service, threadRecordEventService } = buildService();
-
- await service.closePendingToolCalls(closeArguments);
-
- expect(
- threadRecordEventService.emitPendingQuestionCleared,
- ).toHaveBeenCalledTimes(1);
- expect(
- threadRecordEventService.emitPendingQuestionCleared,
- ).toHaveBeenCalledWith({
- workspaceId: 'workspace-id',
- threadId: 'thread-id',
- messageId: 'question-message-id',
- });
- });
-
- it('leaves the call as it is when an answer holds the conversation', async () => {
- const { service, messagePartRepository, threadRecordEventService } =
- buildService({
- claimAffected: 0,
- });
-
- await service.closePendingToolCalls(closeArguments);
-
- expect(messagePartRepository.writePart).not.toHaveBeenCalled();
- expect(
- threadRecordEventService.emitPendingQuestionCleared,
- ).not.toHaveBeenCalled();
- });
-});
-
-describe('AgentChatService recordToolCallAnswer', () => {
- const answerArguments = {
- threadId: 'thread-id',
- messageId: 'question-message-id',
- partId: 'part-id',
- toolOutput: { result: { status: 'answered' } },
- workspaceId: 'workspace-id',
- };
-
- it('tells open chat lists once the last answer stops the wait', async () => {
- const { service, messagePartRepository, threadRecordEventService } =
- buildService();
-
- messagePartRepository.writePart
- .mockResolvedValueOnce(undefined)
- .mockResolvedValueOnce([{ id: 'thread-id' }]);
-
- await service.recordToolCallAnswer({
- ...answerArguments,
- isLastAnswer: true,
- });
-
- expect(
- threadRecordEventService.emitPendingQuestionCleared,
- ).toHaveBeenCalledTimes(1);
- });
-
- it('stays quiet when another caller already stopped the wait', async () => {
- const { service, messagePartRepository, threadRecordEventService } =
- buildService();
-
- messagePartRepository.writePart
- .mockResolvedValueOnce(undefined)
- .mockResolvedValueOnce([]);
-
- await service.recordToolCallAnswer({
- ...answerArguments,
- isLastAnswer: true,
- });
-
- expect(
- threadRecordEventService.emitPendingQuestionCleared,
- ).not.toHaveBeenCalled();
- });
-
- it('stays quiet while other calls still wait on an answer', async () => {
- const { service, threadRecordEventService } = buildService();
-
- await service.recordToolCallAnswer({
- ...answerArguments,
- isLastAnswer: false,
- });
-
- expect(
- threadRecordEventService.emitPendingQuestionCleared,
- ).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.record-tool-call-answer.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.record-tool-call-answer.spec.ts
new file mode 100644
index 00000000000..8ed8cd906b5
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.record-tool-call-answer.spec.ts
@@ -0,0 +1,93 @@
+import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+
+const buildService = () => {
+ const threadRecordEventService = {
+ emitPendingQuestionCleared: jest.fn().mockResolvedValue(undefined),
+ };
+ const messagePartRepository = {
+ writePart: jest.fn(),
+ query: jest.fn(),
+ };
+
+ messagePartRepository.query.mockImplementation(async (_workspaceId, run) =>
+ run({
+ table: (name: string) => name,
+ manager: { query: messagePartRepository.writePart },
+ }),
+ );
+
+ const service = new AgentChatService(
+ {} as never,
+ {} as never,
+ {} as never,
+ messagePartRepository as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ threadRecordEventService as never,
+ {} as never,
+ {} as never,
+ { hasUpgradedAgentHistory: jest.fn().mockResolvedValue(true) } as never,
+ );
+
+ return { service, messagePartRepository, threadRecordEventService };
+};
+
+describe('AgentChatService recordToolCallAnswer', () => {
+ const answerArguments = {
+ threadId: 'thread-id',
+ messageId: 'question-message-id',
+ partId: 'part-id',
+ toolOutput: { result: { status: 'answered' } },
+ workspaceId: 'workspace-id',
+ };
+
+ it('tells open chat lists once the last answer stops the wait', async () => {
+ const { service, messagePartRepository, threadRecordEventService } =
+ buildService();
+
+ messagePartRepository.writePart
+ .mockResolvedValueOnce(undefined)
+ .mockResolvedValueOnce([{ id: 'thread-id' }]);
+
+ await service.recordToolCallAnswer({
+ ...answerArguments,
+ isLastAnswer: true,
+ });
+
+ expect(
+ threadRecordEventService.emitPendingQuestionCleared,
+ ).toHaveBeenCalledTimes(1);
+ });
+
+ it('stays quiet when another caller already stopped the wait', async () => {
+ const { service, messagePartRepository, threadRecordEventService } =
+ buildService();
+
+ messagePartRepository.writePart
+ .mockResolvedValueOnce(undefined)
+ .mockResolvedValueOnce([]);
+
+ await service.recordToolCallAnswer({
+ ...answerArguments,
+ isLastAnswer: true,
+ });
+
+ expect(
+ threadRecordEventService.emitPendingQuestionCleared,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('stays quiet while other calls still wait on an answer', async () => {
+ const { service, threadRecordEventService } = buildService();
+
+ await service.recordToolCallAnswer({
+ ...answerArguments,
+ isLastAnswer: false,
+ });
+
+ expect(
+ threadRecordEventService.emitPendingQuestionCleared,
+ ).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.thread-contexts.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.thread-contexts.spec.ts
index ede72e84671..dba7bdf7bca 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.thread-contexts.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.thread-contexts.spec.ts
@@ -35,7 +35,6 @@ const buildService = () => {
{} as never,
{} as never,
{} as never,
- {} as never,
{ hasUpgradedAgentHistory: jest.fn().mockResolvedValue(true) } as never,
);
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 d85bc92b9fc..db93f3c48fc 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
@@ -44,6 +44,7 @@ import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/a
import { AgentChatStreamHeartbeatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-heartbeat.service';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service';
import { AiChatFileAttachment } from 'src/engine/metadata-modules/ai/ai-chat/types/ai-chat-file-attachment.type';
import { formatErrorWithCause } from 'src/engine/metadata-modules/ai/ai-chat/utils/format-error-with-cause.util';
import { mapErrorToStreamError } from 'src/engine/metadata-modules/ai/ai-history/utils/map-error-to-stream-error.util';
@@ -97,6 +98,7 @@ export class AgentChatStreamingService {
private readonly turnRecorderService: AgentTurnRecorderService,
private readonly agentRunSuspensionService: AgentRunSuspensionService,
private readonly agentRunConversationService: AgentRunConversationService,
+ private readonly threadLifecycleService: AgentChatThreadLifecycleService,
) {}
async tryClaimStream({
@@ -662,11 +664,13 @@ export class AgentChatStreamingService {
return;
}
- await this.agentChatService.closePendingToolCalls({
+ // the member moved on from the question, which ends the turn that asked it
+ await this.threadLifecycleService.closePendingQuestion({
+ workspaceId,
threadId: thread.id,
messageId,
- workspaceId,
- where: { activeStreamId: IsNull() },
+ activeStreamId: null,
+ turnStatus: AgentTurnStatus.COMPLETED,
});
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts
index 37788d37587..d1912f76a3b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts
@@ -8,11 +8,13 @@ import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-a
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { CodeInterpreterService } from 'src/engine/core-modules/code-interpreter/code-interpreter.service';
import { RedisClientService } from 'src/engine/core-modules/redis-client/redis-client.service';
+import { closeOpenToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util';
import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service';
import { getCancelChannel } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-cancel-channel.util';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
+import { AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
@@ -27,6 +29,8 @@ export class AgentChatThreadLifecycleService {
private readonly codeInterpreterService: CodeInterpreterService,
private readonly threadRecordEventService: AgentChatThreadRecordEventService,
private readonly turnRecorderService: AgentTurnRecorderService,
+ @InjectAgentHistoryRepository('agentMessagePart')
+ private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
) {}
async cancelStream({
@@ -176,4 +180,53 @@ export class AgentChatThreadLifecycleService {
});
}
}
+
+ // Clearing the marker is the claim, so only one caller closes the calls, and only while the
+ // thread is held by the stream given, or by none. The event goes last so listeners read the
+ // closed calls and the ended turn
+ async closePendingQuestion({
+ workspaceId,
+ threadId,
+ messageId,
+ activeStreamId,
+ turnStatus,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ messageId: string;
+ activeStreamId: string | null;
+ turnStatus: AgentTurnStatus.COMPLETED | AgentTurnStatus.CANCELLED;
+ }): Promise<void> {
+ const { affected } = await this.threadRepository.update(
+ workspaceId,
+ {
+ id: threadId,
+ pendingQuestionMessageId: messageId,
+ activeStreamId: activeStreamId ?? IsNull(),
+ },
+ { pendingQuestionMessageId: null },
+ );
+
+ if (!affected) {
+ return;
+ }
+
+ await closeOpenToolParts({
+ messagePartRepository: this.messagePartRepository,
+ messageId,
+ workspaceId,
+ });
+
+ await this.turnRecorderService.endWaitingTurn({
+ workspaceId,
+ messageId,
+ status: turnStatus,
+ });
+
+ await this.threadRecordEventService.emitPendingQuestionCleared({
+ workspaceId,
+ threadId,
+ messageId,
+ });
+ }
}
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 5595dee6e3d..c5a1138944a 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
@@ -12,7 +12,7 @@ import {
isNonEmptyArray,
isNonEmptyString,
} from 'twenty-shared/utils';
-import { type FindOptionsWhere, In, Like, Not } from 'typeorm';
+import { In, Like, Not } from 'typeorm';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
@@ -20,13 +20,11 @@ import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enum
import { AgentMessageStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-status.enum';
import { AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
-import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
import { buildEndWaitingAgentTurnQuery } from 'src/engine/metadata-modules/ai/ai-history/utils/build-end-waiting-agent-turn-query.util';
import { buildActorMetadataFromAuthContext } from 'src/engine/core-modules/actor/utils/build-actor-metadata-from-auth-context.util';
import { AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity';
import { mapUIMessagePartsToDBParts } from 'src/engine/metadata-modules/ai/ai-history/utils/map-ui-message-parts-to-db-parts.util';
import { findAwaitingPausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool.util';
-import { closeOpenToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util';
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
@@ -56,7 +54,6 @@ export class AgentChatService {
private readonly threadRecordEventService: AgentChatThreadRecordEventService,
private readonly conversationWriterService: AgentConversationWriterService,
private readonly threadService: AgentChatThreadService,
- private readonly turnRecorderService: AgentTurnRecorderService,
private readonly upgradeFenceService: AgentHistoryUpgradeFenceService,
) {}
@@ -610,47 +607,6 @@ export class AgentChatService {
}
}
- // clearing the marker is the claim, so only one caller closes the calls
- async closePendingToolCalls({
- threadId,
- messageId,
- workspaceId,
- where = {},
- }: {
- threadId: string;
- messageId: string;
- workspaceId: string;
- where?: FindOptionsWhere<AgentChatThreadWorkspaceEntity>;
- }): Promise<void> {
- const claim = await this.threadRepository.update(
- workspaceId,
- { id: threadId, pendingQuestionMessageId: messageId, ...where },
- { pendingQuestionMessageId: null },
- );
-
- if (!claim.affected) {
- return;
- }
-
- await this.turnRecorderService.endWaitingTurn({
- workspaceId,
- messageId,
- status: AgentTurnStatus.COMPLETED,
- });
-
- await closeOpenToolParts({
- messagePartRepository: this.messagePartRepository,
- messageId,
- workspaceId,
- });
-
- await this.threadRecordEventService.emitPendingQuestionCleared({
- workspaceId,
- threadId,
- messageId,
- });
- }
-
async restoreThread({
threadId,
workspaceMemberId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.ts
index 1b959887574..5695afa118d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.ts
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { ToolProviderModule } from 'src/engine/core-modules/tool-provider/tool-provider.module';
import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';
+import { AgentChatThreadLifecycleModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module';
import { AgentChatStreamStateModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-stream-state.module';
import { AiChatModule } from 'src/engine/metadata-modules/ai/ai-chat/ai-chat.module';
import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
@@ -16,6 +17,7 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permi
AiAgentExecutionModule,
AiChatModule,
AgentChatStreamStateModule,
+ AgentChatThreadLifecycleModule,
PermissionsModule,
ToolProviderModule,
],
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
index 4dcf3439f99..bd2c5c7098b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
@@ -19,6 +19,7 @@ import { AgentChatActorService } from 'src/engine/metadata-modules/ai/ai-chat/se
import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service';
import { AgentChatStreamRecoveryService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service';
import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';
+import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service';
import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
import { AgentChatTurnPreflightService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
@@ -72,6 +73,7 @@ export class ToolCallAnswerService {
private readonly agentActorContextService: AgentActorContextService,
private readonly toolRegistryService: ToolRegistryService,
private readonly conversationReaderService: AgentConversationReaderService,
+ private readonly threadLifecycleService: AgentChatThreadLifecycleService,
) {}
async answer(args: AnswerToolCallArgs): Promise<AnswerToolCallOutcome> {
@@ -186,10 +188,13 @@ export class ToolCallAnswerService {
}
if (waitingState.status === 'GONE') {
- await this.agentChatService.closePendingToolCalls({
+ // the run waiting on the call was dropped, as when its suspension is released
+ await this.threadLifecycleService.closePendingQuestion({
+ workspaceId,
threadId,
messageId: toolPart.messageId,
- workspaceId,
+ activeStreamId: streamId,
+ turnStatus: AgentTurnStatus.CANCELLED,
});
await this.agentRunSuspensionService.release({
@@ -247,12 +252,13 @@ export class ToolCallAnswerService {
// a call claimed as running cannot be answered again, so it closes as interrupted and the
// run or turn fails, instead of leaving the call waiting on an outcome
if (isClaimedAsRunning) {
- await this.agentChatService
- .closePendingToolCalls({
+ await this.threadLifecycleService
+ .closePendingQuestion({
+ workspaceId,
threadId,
messageId: toolPart.messageId,
- workspaceId,
- where: { activeStreamId: streamId },
+ activeStreamId: streamId,
+ turnStatus: AgentTurnStatus.COMPLETED,
})
.catch((closeError: unknown) =>
this.logger.warn(