The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(assistant): prevent parallel approval-required tool calls (#47008)
Matt Rossmanc54168842b36
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsxindex 2184f94a8e0..6b8848e44d7 100644--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx@@ -39,6 +39,7 @@ import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'import { useOrgAiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { getParallelApprovalIdsToReject } from '@/lib/ai/message-utils'import {DEFAULT_ASSISTANT_BASE_MODEL_ID,defaultAssistantModelId,@@ -366,6 +367,18 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {}}, [isResubmitting, chatStatus, error])+ useEffect(() => {+ // Approval-required tools can't run in parallel. Auto-deny extras so the model reissues them sequentially.+ for (const id of getParallelApprovalIdsToReject(chatMessages)) {+ addToolApprovalResponse?.({+ id,+ approved: false,+ reason:+ 'Only one approval-required tool call is allowed per turn. Please reissue this tool call after the current one completes.',+ })+ }+ }, [chatMessages, addToolApprovalResponse])+useEffect(() => {setValue(snap.initialInput || '')if (inputRef.current && snap.initialInput) {diff --git a/apps/studio/lib/ai/message-utils.test.ts b/apps/studio/lib/ai/message-utils.test.tsindex 34502f43d2a..0125996ddc7 100644--- a/apps/studio/lib/ai/message-utils.test.ts+++ b/apps/studio/lib/ai/message-utils.test.ts@@ -1,7 +1,81 @@-import type { UIMessage } from 'ai'+import type { DynamicToolUIPart, UIMessage } from 'ai'import { describe, expect, it } from 'vitest'-import { prepareMessagesForAPI } from './message-utils'+import { getParallelApprovalIdsToReject, prepareMessagesForAPI } from './message-utils'++const makeApprovalPart = (id: string): DynamicToolUIPart => ({+ type: 'dynamic-tool',+ toolName: 'test_tool',+ toolCallId: id,+ state: 'approval-requested',+ input: {},+ approval: { id },+})++const makeResultPart = (id: string): DynamicToolUIPart => ({+ type: 'dynamic-tool',+ toolName: 'test_tool',+ toolCallId: id,+ state: 'output-available',+ input: {},+ output: {},+})++describe('getParallelApprovalIdsToReject', () => {+ it('returns [] for empty messages', () => {+ expect(getParallelApprovalIdsToReject([])).toEqual([])+ })++ it('returns [] when there are no assistant messages', () => {+ const messages: UIMessage[] = [{ id: '1', role: 'user', parts: [] }]+ expect(getParallelApprovalIdsToReject(messages)).toEqual([])+ })++ it('returns [] when last assistant message has no pending approvals', () => {+ const messages: UIMessage[] = [{ id: '1', role: 'assistant', parts: [makeResultPart('r1')] }]+ expect(getParallelApprovalIdsToReject(messages)).toEqual([])+ })++ it('returns [] when there is only one pending approval', () => {+ const messages: UIMessage[] = [{ id: '1', role: 'assistant', parts: [makeApprovalPart('a1')] }]+ expect(getParallelApprovalIdsToReject(messages)).toEqual([])+ })++ it('returns all but the first id when there are multiple pending approvals', () => {+ const messages: UIMessage[] = [+ {+ id: '1',+ role: 'assistant',+ parts: [makeApprovalPart('a1'), makeApprovalPart('a2'), makeApprovalPart('a3')],+ },+ ]+ expect(getParallelApprovalIdsToReject(messages)).toEqual(['a2', 'a3'])+ })++ it('only inspects the last assistant message', () => {+ const messages: UIMessage[] = [+ {+ id: '1',+ role: 'assistant',+ parts: [makeApprovalPart('old1'), makeApprovalPart('old2')],+ },+ { id: '2', role: 'user', parts: [] },+ { id: '3', role: 'assistant', parts: [makeApprovalPart('new1')] },+ ]+ expect(getParallelApprovalIdsToReject(messages)).toEqual([])+ })++ it('ignores non-approval tool parts', () => {+ const messages: UIMessage[] = [+ {+ id: '1',+ role: 'assistant',+ parts: [makeResultPart('r1'), makeApprovalPart('a1'), makeApprovalPart('a2')],+ },+ ]+ expect(getParallelApprovalIdsToReject(messages)).toEqual(['a2'])+ })+})describe('prepareMessagesForAPI', () => {it('should limit messages to last 7 entries', () => {diff --git a/apps/studio/lib/ai/message-utils.ts b/apps/studio/lib/ai/message-utils.tsindex 2b0cbd62924..d04e25b5c1d 100644--- a/apps/studio/lib/ai/message-utils.ts+++ b/apps/studio/lib/ai/message-utils.ts@@ -1,4 +1,4 @@-import type { UIMessage } from 'ai'+import { isToolUIPart, type UIMessage } from 'ai'/*** Prepares messages for API transmission by cleaning and limiting history@@ -23,3 +23,17 @@ export function prepareMessagesForAPI(messages: UIMessage[]): UIMessage[] {return cleanedMessages}++/**+ * Returns approval IDs to auto-deny when the model issues multiple approval-required+ * tool calls in the same turn — all but the first, so the model reissues them sequentially.+ */+export function getParallelApprovalIdsToReject(messages: UIMessage[]): string[] {+ const lastMessage = messages.findLast((m) => m.role === 'assistant')+ if (!lastMessage) return []++ const pendingIds = (lastMessage.parts ?? []).flatMap((part) =>+ isToolUIPart(part) && part.state === 'approval-requested' ? [part.approval.id] : []+ )+ return pendingIds.slice(1)+}diff --git a/apps/studio/lib/ai/prompts.ts b/apps/studio/lib/ai/prompts.tsindex 09f71fb4f5d..81c6f0435f6 100644--- a/apps/studio/lib/ai/prompts.ts+++ b/apps/studio/lib/ai/prompts.ts@@ -733,7 +733,7 @@ export const CHAT_PROMPT = `- On execution error, explain succinctly and attempt to correct if possible, validating each outcome briefly (1–2 lines) after execution.- If a user skips execution, acknowledge and suggest alternatives.- Use markdown code blocks (\`\`\`sql\`\`\`) for illustrative SQL only if requested by the user or when providing non-executable examples.-- Execute multiple queries separately via \`execute_sql\` and briefly validate outcomes.+- Never call \`execute_sql\` or \`deploy_edge_function\` in parallel within the same step. Each requires user approval, so issue one per step and wait for its result before calling the next.- After execution, summarize outcomes concisely without duplicating results, as the client will present these.## Edge Functions- Deploy Edge Functions by calling \`deploy_edge_function\` directly with \`name\` and \`code\`; the client handles confirmation and result presentation.