Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(agent): normalize heterogeneous review inputs (#18878)

Tsuki1655b2a3473c
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index e34b7b063c4..caf96a48c59 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -1324,6 +1324,20 @@ export class HeterogeneousPersistenceHandler {
const summary = interventionSummary(intent.request);
const reviewRequest = sanitizeAgentInterventionRequestForReview(intent.request);
+ const transitionKey = `${state.operationId}:${intent.toolCallId}:${intent.transition}`;
+ const pendingTransitionKey = `${state.operationId}:${intent.toolCallId}:pending`;
+ const requiresPendingReviewNotification =
+ !!this.deps.userId &&
+ !state.notifiedInterventionTransitions.has(transitionKey) &&
+ !state.notifiedInterventionTransitions.has(pendingTransitionKey);
+ if (
+ requiresPendingReviewNotification &&
+ (!reviewRequest?.interactionKind || !reviewRequest.provider)
+ ) {
+ throw new Error(
+ `Unsafe heterogeneous intervention review payload toolCallId=${intent.toolCallId}`,
+ );
+ }
const durableState: StoredHeterogeneousIntervention = {
deadline: intent.request?.deadline,
interactionKind: intent.request?.interactionKind,
@@ -1342,10 +1356,8 @@ export class HeterogeneousPersistenceHandler {
[HETEROGENEOUS_INTERVENTION_STATE_KEY]: durableState,
});
- const transitionKey = `${state.operationId}:${intent.toolCallId}:${intent.transition}`;
if (!this.deps.userId || state.notifiedInterventionTransitions.has(transitionKey)) return;
- const pendingTransitionKey = `${state.operationId}:${intent.toolCallId}:pending`;
if (!state.notifiedInterventionTransitions.has(pendingTransitionKey)) {
if (!reviewRequest?.interactionKind || !reviewRequest.provider) {
throw new Error(
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
index d95978aa3dd..8e057ed36ad 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
@@ -68,6 +68,7 @@ const createHarness = (
operationId?: string;
topicAgentId?: string | null;
topicId?: string;
+ userId?: string | null;
} = {},
) => {
const operationId = params.operationId ?? 'op-test';
@@ -215,7 +216,7 @@ const createHarness = (
messageModel: messageModel as any,
threadModel: threadModel as any,
topicModel: topicModel as any,
- userId: 'user-test',
+ userId: params.userId === null ? undefined : (params.userId ?? 'user-test'),
});
return {
@@ -950,6 +951,153 @@ describe('HeterogeneousPersistenceHandler β€” event branch coverage', () => {
});
describe('agent_intervention producer ACK', () => {
+ const materializeAskUserTool = async (
+ h: ReturnType<typeof createHarness>,
+ toolCallId: string,
+ ) =>
+ ingest(h, [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ id: toolCallId,
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ],
+ }),
+ ]);
+
+ const missingProviderRequest = (toolCallId: string) =>
+ buildEvent('agent_intervention_request', 1, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Question',
+ options: [{ label: 'Continue' }, { label: 'Stop' }],
+ question: 'Proceed?',
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
+ interactionKind: 'question',
+ toolCallId,
+ });
+
+ it('rejects an invalid first Cloud review before any intervention side effect', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+ const toolCallId = 'invalid-cloud-question';
+ await materializeAskUserTool(h, toolCallId);
+ h.messageModel.updateMessagePlugin.mockClear();
+ h.messageModel.updatePluginState.mockClear();
+
+ await expect(ingest(h, [missingProviderRequest(toolCallId)])).rejects.toThrow(
+ `Unsafe heterogeneous intervention review payload toolCallId=${toolCallId}`,
+ );
+
+ expect(h.messageModel.updateMessagePlugin).not.toHaveBeenCalled();
+ expect(h.messageModel.updatePluginState).not.toHaveBeenCalled();
+ expect(notifyAgentInterventionRequired).not.toHaveBeenCalled();
+ expect(acknowledgeAgentInterventionProducerResolution).not.toHaveBeenCalled();
+ const toolMessage = [...h.messages.values()].find(
+ (message) => message.tool_call_id === toolCallId,
+ );
+ expect(toolMessage?.plugin).not.toHaveProperty('intervention');
+ expect(toolMessage?.pluginState).toBeUndefined();
+ });
+
+ it('preserves legacy intervention persistence without a userId', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test', userId: null });
+ const toolCallId = 'legacy-question';
+ await materializeAskUserTool(h, toolCallId);
+ h.messageModel.updateMessagePlugin.mockClear();
+ h.messageModel.updatePluginState.mockClear();
+
+ await expect(ingest(h, [missingProviderRequest(toolCallId)])).resolves.toBeUndefined();
+
+ expect(h.messageModel.updateMessagePlugin).toHaveBeenCalledTimes(1);
+ expect(h.messageModel.updatePluginState).toHaveBeenCalledTimes(1);
+ expect(notifyAgentInterventionRequired).not.toHaveBeenCalled();
+ expect(acknowledgeAgentInterventionProducerResolution).not.toHaveBeenCalled();
+ const toolMessage = [...h.messages.values()].find(
+ (message) => message.tool_call_id === toolCallId,
+ );
+ expect(toolMessage?.plugin?.intervention).toEqual({ status: 'pending' });
+ expect(toolMessage?.pluginState?.heterogeneousIntervention).toMatchObject({
+ transition: 'pending',
+ });
+ });
+
+ it('canonicalizes an omitted Claude multiSelect before durable review notification', async () => {
+ const h = createHarness({ topicAgentId: 'agent-test' });
+
+ await ingest(h, [
+ buildEvent('agent_intervention_request', 0, {
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Producer ACK E2E',
+ options: [
+ { description: 'Proceed with validation.', label: 'Continue' },
+ { description: 'Halt validation.', label: 'Stop' },
+ ],
+ question: 'Continue read only validation?',
+ },
+ ],
+ }),
+ deadline: 1_900_000_000_000,
+ identifier: 'claude-code',
+ interactionKind: 'question',
+ provider: 'claude-code',
+ toolCallId: 'claude-question-1',
+ }),
+ ]);
+
+ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
+ expect(notifyAgentInterventionRequired.mock.calls[0][0].items[0]).toMatchObject({
+ detail: {
+ questions: [
+ {
+ header: 'Producer ACK E2E',
+ id: 'question_1',
+ multiple: false,
+ options: [
+ {
+ description: 'Proceed with validation.',
+ id: 'Continue',
+ label: 'Continue',
+ },
+ {
+ description: 'Halt validation.',
+ id: 'Stop',
+ label: 'Stop',
+ },
+ ],
+ question: 'Continue read only validation?',
+ },
+ ],
+ title: 'Producer ACK E2E',
+ type: 'question',
+ },
+ interactionKind: 'question',
+ provider: 'claude-code',
+ });
+ expect(h.messageModel.updatePluginState).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ heterogeneousIntervention: expect.objectContaining({
+ interactionKind: 'question',
+ provider: 'claude-code',
+ }),
+ }),
+ );
+ });
+
it('notifies pending once, ignores the publish leg, and notifies terminal only on ACK', async () => {
const h = createHarness({ topicAgentId: 'agent-test' });
const requestId = '018fbd8e-7baf-7c6d-8000-000000000001';
@@ -1040,14 +1188,14 @@ describe('HeterogeneousPersistenceHandler β€” event branch coverage', () => {
expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
expect(acknowledgeAgentInterventionProducerResolution).not.toHaveBeenCalled();
- await ingest(h, [
- buildEvent('agent_intervention_response', 2, {
- producerAck: true,
- resolutionRequestId: requestId,
- result: { 'Run command?': 'allow' },
- toolCallId: 'permission-1',
- }),
- ]);
+ const producerAck = buildEvent('agent_intervention_response', 2, {
+ producerAck: true,
+ resolutionRequestId: requestId,
+ result: { 'Run command?': 'allow' },
+ toolCallId: 'permission-1',
+ });
+ await ingest(h, [producerAck]);
+ await ingest(h, [{ ...producerAck, timestamp: producerAck.timestamp + 1 }]);
expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);
expect(acknowledgeAgentInterventionProducerResolution).toHaveBeenCalledTimes(1);
diff --git a/packages/agent-gateway-client/src/intervention.test.ts b/packages/agent-gateway-client/src/intervention.test.ts
index c61b0455055..2e542333b0f 100644
--- a/packages/agent-gateway-client/src/intervention.test.ts
+++ b/packages/agent-gateway-client/src/intervention.test.ts
@@ -79,6 +79,121 @@ describe('sanitizeAgentInterventionRequestForReview', () => {
expect(sanitizeAgentInterventionRequestForReview(duplicateIds)).toBeUndefined();
});
+ it('defaults an omitted multiSelect to false but rejects explicit non-boolean values', () => {
+ const omittedMultiSelect = request({
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Question',
+ options: [{ label: 'Continue' }, { label: 'Stop' }],
+ question: 'Proceed?',
+ },
+ ],
+ }),
+ interactionKind: 'question',
+ });
+ expect(
+ JSON.parse(sanitizeAgentInterventionRequestForReview(omittedMultiSelect)!.arguments),
+ ).toMatchObject({ questions: [{ multiSelect: false }] });
+
+ for (const invalidMultiSelect of ['false', null]) {
+ const invalidRequest = request({
+ arguments: JSON.stringify({
+ questions: [
+ {
+ header: 'Question',
+ multiSelect: invalidMultiSelect,
+ options: [{ label: 'Continue' }, { label: 'Stop' }],
+ question: 'Proceed?',
+ },
+ ],
+ }),
+ interactionKind: 'question',
+ });
+
+ expect(sanitizeAgentInterventionRequestForReview(invalidRequest)).toBeUndefined();
+ }
+ });
+
+ it('fails closed when permission or plan requests are ambiguous', () => {
+ for (const interactionKind of ['permission', 'plan'] as const) {
+ const questions = [
+ {
+ header: 'Review',
+ multiSelect: false,
+ options: [{ id: 'allow', label: 'Allow' }],
+ question: 'Proceed?',
+ },
+ {
+ header: 'Review again',
+ multiSelect: false,
+ options: [{ id: 'allow', label: 'Allow' }],
+ question: 'Proceed again?',
+ },
+ ];
+
+ const omittedMultiSelect = sanitizeAgentInterventionRequestForReview(
+ request({
+ arguments: JSON.stringify({ questions: [{ ...questions[0], multiSelect: undefined }] }),
+ interactionKind,
+ }),
+ );
+
+ expect(JSON.parse(omittedMultiSelect!.arguments)).toMatchObject({
+ questions: [{ multiSelect: false }],
+ });
+ expect(
+ sanitizeAgentInterventionRequestForReview(
+ request({ arguments: JSON.stringify({ questions }), interactionKind }),
+ ),
+ ).toBeUndefined();
+ expect(
+ sanitizeAgentInterventionRequestForReview(
+ request({
+ arguments: JSON.stringify({
+ questions: [{ ...questions[0], multiSelect: true }],
+ }),
+ interactionKind,
+ }),
+ ),
+ ).toBeUndefined();
+ }
+ });
+
+ it('keeps distinct multi-select questions but rejects duplicate question text', () => {
+ const questions = [
+ {
+ header: 'First',
+ multiSelect: true,
+ options: [{ label: 'One' }, { label: 'Two' }],
+ question: 'Choose values?',
+ },
+ {
+ header: 'Second',
+ multiSelect: false,
+ options: [{ label: 'Continue' }],
+ question: 'Continue?',
+ },
+ ];
+ const sanitized = sanitizeAgentInterventionRequestForReview(
+ request({ arguments: JSON.stringify({ questions }), interactionKind: 'question' }),
+ );
+
+ expect(JSON.parse(sanitized!.arguments)).toMatchObject({
+ questions: [{ multiSelect: true }, { multiSelect: false }],
+ });
+ expect(
+ sanitizeAgentInterventionRequestForReview(
+ request({
+ arguments: JSON.stringify({
+ questions: [questions[0], { ...questions[1], question: questions[0].question }],
+ }),
+ interactionKind: 'question',
+ }),
+ ),
+ ).toBeUndefined();
+ });
+
it('requires explicit provider and interaction kind for durable review', () => {
expect(
sanitizeAgentInterventionRequestForReview(request({ provider: undefined })),
diff --git a/packages/agent-gateway-client/src/intervention.ts b/packages/agent-gateway-client/src/intervention.ts
index 57f0f5ed5fd..7c7794ee0cc 100644
--- a/packages/agent-gateway-client/src/intervention.ts
+++ b/packages/agent-gateway-client/src/intervention.ts
@@ -51,8 +51,10 @@ export const sanitizeAgentInterventionRequestForReview = (
const rawQuestions = asRecord(parsed)?.questions;
if (!Array.isArray(rawQuestions) || rawQuestions.length < 1 || rawQuestions.length > 4) return;
+ if (request.interactionKind !== 'question' && rawQuestions.length !== 1) return;
const questions: AgentInterventionRenderArguments['questions'] = [];
+ const questionTexts = new Set<string>();
for (const rawQuestion of rawQuestions) {
const questionRecord = asRecord(rawQuestion);
if (!questionRecord) return;
@@ -63,13 +65,17 @@ export const sanitizeAgentInterventionRequestForReview = (
if (
question === undefined ||
header === undefined ||
- typeof questionRecord.multiSelect !== 'boolean' ||
+ (questionRecord.multiSelect !== undefined &&
+ typeof questionRecord.multiSelect !== 'boolean') ||
+ (request.interactionKind !== 'question' && questionRecord.multiSelect === true) ||
!Array.isArray(rawOptions) ||
rawOptions.length < 1 ||
rawOptions.length > 16
) {
return;
}
+ if (questionTexts.has(question)) return;
+ questionTexts.add(question);
const options: AgentInterventionRenderOption[] = [];
const optionIds = new Set<string>();