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): accept a typed answer in a multi-select intervention question (#19399)

Arvin Xu99fbd13ba0f7
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts
index 164737ad2ca..f5cfd1a5494 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts
@@ -464,6 +464,29 @@ describe('aiAgentRouter — remote Human-in-the-loop', () => {
);
});
+ it('answers a rejected source resolution with a client error instead of a 500', async () => {
+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000031';
+ await insertPendingTool({
+ batchId: 'batch-invalid',
+ messageId: 'message-invalid',
+ operationId: 'operation-invalid',
+ toolCallId: 'call-invalid',
+ });
+ businessV2.resolveAgentInterventionBySource.mockRejectedValueOnce(
+ new Error('AGENT_INTERVENTION_INVALID_ACTION'),
+ );
+
+ await expect(
+ userCaller().resolveAgentInterventionBySource({
+ action: { result: { mode: ['safe'] }, type: 'submit_answers' },
+ batchId: 'batch-invalid',
+ operationId: 'operation-invalid',
+ resolutionRequestId,
+ targets: [{ toolCallId: 'call-invalid', toolMessageId: 'message-invalid' }],
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
it('does not dispatch again when another surface already won the source claim', async () => {
businessV2.resolveAgentInterventionBySource.mockResolvedValueOnce({
contractVersion: 2,
diff --git a/apps/server/src/routers/lambda/_helpers/agentInterventionError.test.ts b/apps/server/src/routers/lambda/_helpers/agentInterventionError.test.ts
new file mode 100644
index 00000000000..9f0c2a18595
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/agentInterventionError.test.ts
@@ -0,0 +1,41 @@
+import { TRPCError } from '@trpc/server';
+import { describe, expect, it } from 'vitest';
+
+import { mapAgentInterventionTRPCError } from './agentInterventionError';
+
+describe('mapAgentInterventionTRPCError', () => {
+ it('maps a rejected response to a client error', () => {
+ const cause = new Error('AGENT_INTERVENTION_INVALID_ACTION');
+ const mapped = mapAgentInterventionTRPCError(cause);
+
+ expect(mapped).toBeInstanceOf(TRPCError);
+ expect(mapped).toMatchObject({ cause, code: 'BAD_REQUEST' });
+ });
+
+ it('maps a lost race to a conflict', () => {
+ expect(
+ mapAgentInterventionTRPCError(new Error('AGENT_INTERVENTION_RESOLUTION_CONFLICT')),
+ ).toMatchObject({ code: 'CONFLICT' });
+ expect(
+ mapAgentInterventionTRPCError(new Error('AGENT_INTERVENTION_REVIEW_STALE')),
+ ).toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it('maps an unavailable review to a forbidden error', () => {
+ expect(
+ mapAgentInterventionTRPCError(new Error('AGENT_INTERVENTION_REVIEW_UNAVAILABLE')),
+ ).toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('keeps an existing tRPC error untouched', () => {
+ const error = new TRPCError({ code: 'NOT_FOUND' });
+
+ expect(mapAgentInterventionTRPCError(error)).toBe(error);
+ });
+
+ it('leaves an unrecognized failure alone so genuine faults stay 500', () => {
+ const error = new Error('Connection terminated unexpectedly');
+
+ expect(mapAgentInterventionTRPCError(error)).toBe(error);
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/agentInterventionError.ts b/apps/server/src/routers/lambda/_helpers/agentInterventionError.ts
new file mode 100644
index 00000000000..2621021efb2
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/agentInterventionError.ts
@@ -0,0 +1,121 @@
+import { TRPCError } from '@trpc/server';
+
+/**
+ * Contract failures raised while claiming an intervention, mapped to the tRPC
+ * code the caller should see.
+ *
+ * A rejected resolution is a statement about the request, not a server fault,
+ * so none of these may surface as a 500. The first group is thrown by
+ * `AgentInterventionModel` in `@lobechat/database`; the rest are thrown by the
+ * Cloud resolution service ahead of the model and are matched by name because
+ * OSS cannot import them.
+ */
+const INTERVENTION_ERROR_CODES: Record<string, { code: TRPCError['code']; message: string }> = {
+ AGENT_INTERVENTION_CUSTOM_CONTEXT_MISSING: {
+ code: 'BAD_REQUEST',
+ message: 'This interaction is missing the context needed to resolve it.',
+ },
+ AGENT_INTERVENTION_DETAIL_REQUIRED: {
+ code: 'BAD_REQUEST',
+ message: 'This interaction is missing the context needed to resolve it.',
+ },
+ AGENT_INTERVENTION_IDENTITY_CONFLICT: {
+ code: 'CONFLICT',
+ message: 'This approval was already resolved by another request.',
+ },
+ AGENT_INTERVENTION_INVALID_ACTION: {
+ code: 'BAD_REQUEST',
+ message: 'This response does not match what the agent asked for.',
+ },
+ AGENT_INTERVENTION_INVALID_ANSWER_KEY: {
+ code: 'BAD_REQUEST',
+ message: 'This response does not match what the agent asked for.',
+ },
+ AGENT_INTERVENTION_INVALID_BATCH: {
+ code: 'BAD_REQUEST',
+ message: 'This approval request is no longer valid.',
+ },
+ AGENT_INTERVENTION_INVALID_EDIT: {
+ code: 'BAD_REQUEST',
+ message: 'This response does not match what the agent asked for.',
+ },
+ AGENT_INTERVENTION_INVALID_REQUEST_REVISION_HASH: {
+ code: 'CONFLICT',
+ message: 'The request changed since this card was rendered. Reload and try again.',
+ },
+ AGENT_INTERVENTION_INVALID_REVIEW_TOKEN_HASH: {
+ code: 'BAD_REQUEST',
+ message: 'This approval request is no longer valid.',
+ },
+ AGENT_INTERVENTION_INVALID_SELECTION: {
+ code: 'BAD_REQUEST',
+ message: 'This response does not match what the agent asked for.',
+ },
+ AGENT_INTERVENTION_INVALID_STOP_SCOPE: {
+ code: 'BAD_REQUEST',
+ message: 'This response does not match what the agent asked for.',
+ },
+ AGENT_INTERVENTION_REMEMBER_REQUIRES_ALLOW_LIST: {
+ code: 'BAD_REQUEST',
+ message: 'Remembering this approval is not available here.',
+ },
+ AGENT_INTERVENTION_REMEMBER_REQUIRES_SINGLE_ITEM: {
+ code: 'BAD_REQUEST',
+ message: 'Remembering this approval is not available here.',
+ },
+ AGENT_INTERVENTION_RESOLUTION_CONFLICT: {
+ code: 'CONFLICT',
+ message: 'This approval was already resolved by another request.',
+ },
+ AGENT_INTERVENTION_RESOLUTION_IDENTITY_MISMATCH: {
+ code: 'CONFLICT',
+ message: 'This approval was already resolved by another request.',
+ },
+ AGENT_INTERVENTION_RESOLUTION_REQUEST_REUSED: {
+ code: 'CONFLICT',
+ message: 'This approval was already resolved by another request.',
+ },
+ AGENT_INTERVENTION_REVIEW_STALE: {
+ code: 'CONFLICT',
+ message: 'The request changed since this card was rendered. Reload and try again.',
+ },
+ AGENT_INTERVENTION_REVIEW_UNAVAILABLE: {
+ code: 'FORBIDDEN',
+ message: 'This approval is not available to you.',
+ },
+ AGENT_INTERVENTION_SOURCE_TRANSITION_MISMATCH: {
+ code: 'CONFLICT',
+ message: 'This approval was already resolved by another request.',
+ },
+ AGENT_INTERVENTION_STALE_BATCH: {
+ code: 'CONFLICT',
+ message: 'The request changed since this card was rendered. Reload and try again.',
+ },
+ AGENT_INTERVENTION_UNSUPPORTED_DETAIL: {
+ code: 'BAD_REQUEST',
+ message: 'This interaction cannot be resolved from here.',
+ },
+};
+
+/**
+ * Maps an intervention resolution failure to its public tRPC representation.
+ *
+ * Use when:
+ * - A procedure claims an intervention on behalf of a Review / approval client
+ *
+ * Expects:
+ * - An error caught from the resolution slot, including an existing tRPC error
+ *
+ * Returns:
+ * - The original tRPC error, a contract-aware tRPC error retaining the original
+ * cause, or the error unchanged when it is not an intervention contract failure
+ */
+export const mapAgentInterventionTRPCError = (error: unknown): unknown => {
+ if (error instanceof TRPCError) return error;
+ if (!(error instanceof Error)) return error;
+
+ const mapped = INTERVENTION_ERROR_CODES[error.message];
+ if (!mapped) return error;
+
+ return new TRPCError({ cause: error, code: mapped.code, message: mapped.message });
+};
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 685d3e8fd11..93ed7c83d68 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -68,6 +68,7 @@ import {
resolveServerDefaultHeterogeneousModel,
SERVER_DEFAULT_HETEROGENEOUS_AGENT_TYPES,
} from '@/server/modules/ModelRuntime';
+import { mapAgentInterventionTRPCError } from '@/server/routers/lambda/_helpers/agentInterventionError';
import {
assertCanUseMessageTargets,
assertCanUseTopicTargets,
@@ -3280,6 +3281,8 @@ export const aiAgentRouter = router({
workspaceId: ctx.workspaceId,
});
+ // A rejected resolution describes the submitted response, not a server
+ // fault, so map the contract failure instead of letting it become a 500.
const resolution = await resolveAgentInterventionBySource({
action: input.action,
actorUserId: ctx.userId,
@@ -3288,6 +3291,8 @@ export const aiAgentRouter = router({
resolutionRequestId: input.resolutionRequestId,
targets: input.targets,
workspaceId: ctx.workspaceId ?? undefined,
+ }).catch((error: unknown) => {
+ throw mapAgentInterventionTRPCError(error);
});
if (!resolution.handled) {
@@ -3335,6 +3340,8 @@ export const aiAgentRouter = router({
reviewToken: input.reviewToken,
userId: ctx.userId,
workspaceId: ctx.workspaceId ?? undefined,
+ }).catch((error: unknown) => {
+ throw mapAgentInterventionTRPCError(error);
});
if (!resolution.handled) {
@@ -3393,6 +3400,8 @@ export const aiAgentRouter = router({
target: { reviewToken: input.reviewToken },
userId: ctx.userId,
workspaceId: ctx.workspaceId ?? undefined,
+ }).catch((error: unknown) => {
+ throw mapAgentInterventionTRPCError(error);
});
if (!resolution.handled) return { status: 'unavailable' as const, success: false as const };
diff --git a/packages/database/src/models/__tests__/agentIntervention.test.ts b/packages/database/src/models/__tests__/agentIntervention.test.ts
index 60dac1123e7..b9fc9fb4cb0 100644
--- a/packages/database/src/models/__tests__/agentIntervention.test.ts
+++ b/packages/database/src/models/__tests__/agentIntervention.test.ts
@@ -1321,6 +1321,67 @@ describe('AgentInterventionModel', () => {
).rejects.toThrow(AGENT_INTERVENTION_INVALID_ACTION);
});
+ it('accepts a typed answer inside a multi-select question that allows custom answers', async () => {
+ const multiRows = await createQuestionBatch({
+ batchId: 'multi-custom-answer-batch',
+ items: [
+ questionItem({
+ sanitizedRequest: {
+ answerPolicy: { allowFreeform: true, allowSupplement: true },
+ apiName: 'askUserQuestion',
+ questions: [
+ {
+ allowCustomAnswer: true,
+ id: 'modules',
+ multiSelect: true,
+ options: [
+ { id: 'chaos', label: 'Chaos engineering' },
+ { id: 'harness', label: 'Harness proof' },
+ ],
+ question: 'Which modules?',
+ },
+ ],
+ },
+ toolCallId: 'multi-custom-answer-tool',
+ }),
+ ],
+ });
+ expect(
+ (
+ await claim(multiRows, {
+ answers: { modules: ['chaos', 'one I typed myself'] },
+ type: 'submit_answers',
+ })
+ ).outcome,
+ ).toBe('applied');
+
+ const strictRows = await createQuestionBatch({
+ batchId: 'multi-strict-answer-batch',
+ items: [
+ questionItem({
+ sanitizedRequest: {
+ apiName: 'askUserQuestion',
+ questions: [
+ {
+ id: 'modules',
+ multiSelect: true,
+ options: [
+ { id: 'chaos', label: 'Chaos engineering' },
+ { id: 'harness', label: 'Harness proof' },
+ ],
+ question: 'Which modules?',
+ },
+ ],
+ },
+ toolCallId: 'multi-strict-answer-tool',
+ }),
+ ],
+ });
+ await expect(
+ claim(strictRows, { answers: { modules: ['chaos', 'forged'] }, type: 'submit_answers' }),
+ ).rejects.toThrow(AGENT_INTERVENTION_INVALID_ACTION);
+ });
+
it('validates exact provider option ids and only producer ACK completes heterogeneous rows', async () => {
const rows = await model.createBatch({
activityKey: 'provider-activity',
diff --git a/packages/database/src/models/agentIntervention.ts b/packages/database/src/models/agentIntervention.ts
index 8c7145dca6e..e3261960cab 100644
--- a/packages/database/src/models/agentIntervention.ts
+++ b/packages/database/src/models/agentIntervention.ts
@@ -277,8 +277,13 @@ const hasValidAnswers = (
}
if (definition.multi) {
if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) return false;
+ // A multi-select question with "write your own" enabled carries the typed
+ // answer as one more entry in the array, exactly as the single-select
+ // branch below carries it as the scalar value. Whitelist the options only
+ // when the question forbids custom answers.
if (
definition.options.size > 0 &&
+ !definition.allowCustomAnswer &&
value.some((item) => !definition.options.has(item as string))
) {
return false;