The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): preserve assistant tool previews after completion (#49352)
Saxon Fletcherf0cb02413925
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsxindex d78769f65eb..8612987d991 100644--- a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx@@ -14,7 +14,10 @@ import { Confirm } from './Confirm'import { type ConfirmFooterApprovalState } from './Confirm.utils'import { QueryEditor } from '@/components/interfaces/Explorer/QueryEditor'import { type QueryDisplay, type QueryResult } from '@/components/interfaces/Explorer/types'-import { type QuerySourceBinding } from '@/data/query-sources/query-source-registry'+import {+ type QuerySourceBinding,+ type QuerySourceTag,+} from '@/data/query-sources/query-source-registry'import { useTrack } from '@/lib/telemetry/track'import { useLocalRoleImpersonationState } from '@/state/role-impersonation-state'@@ -36,6 +39,22 @@ interface AssistantQueryCellProps {const DEFAULT_SOURCE: QuerySourceBinding = { _tag: 'database' }+const QUERY_OUTCOME_MESSAGES: Record<+ QuerySourceTag,+ { success: string; error: string; denied: string }+> = {+ database: {+ success: 'Query executed',+ error: 'Failed to execute SQL',+ denied: 'Skipped query',+ },+ logs: {+ success: 'Query executed',+ error: 'Failed to query logs',+ denied: 'Skipped query',+ },+}+/** Assistant adapter around the shared QueryEditor. Local state only — nothing is persisted. */export const AssistantQueryCell = ({id,@@ -123,6 +142,7 @@ export const AssistantQueryCell = ({}const isConfirming = confirmState !== undefined+ const outcomeMessages = QUERY_OUTCOME_MESSAGES[source._tag]return (<Confirm@@ -133,6 +153,9 @@ export const AssistantQueryCell = ({cancelLabel="Skip"confirmLabel="Run query"confirmLabelLoading="Running..."+ successMessage={outcomeMessages.success}+ errorMessage={outcomeMessages.error}+ deniedMessage={outcomeMessages.denied}onCancel={onDeny}onConfirm={onApprove}>diff --git a/apps/studio/components/ui/AIAssistantPanel/Confirm.test.tsx b/apps/studio/components/ui/AIAssistantPanel/Confirm.test.tsxnew file mode 100644index 00000000000..4cec084cc32--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/Confirm.test.tsx@@ -0,0 +1,51 @@+import { screen } from '@testing-library/react'+import { describe, expect, it } from 'vitest'++import { Confirm } from './Confirm'+import { customRender as render } from '@/tests/lib/custom-render'++describe('Confirm', () => {+ it('keeps its content visible and replaces actions with a success status', () => {+ render(+ <Confirm state="success" message="Run query" successMessage="Query executed">+ <div>Query preview</div>+ </Confirm>+ )++ expect(screen.getByText('Query preview')).toBeInTheDocument()+ expect(screen.getByText('Query executed')).toBeInTheDocument()+ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })++ it('keeps its content visible and replaces actions with an error status', () => {+ render(+ <Confirm state="error" message="Run query" errorMessage="Failed to execute SQL">+ <div>Query preview</div>+ </Confirm>+ )++ expect(screen.getByText('Query preview')).toBeInTheDocument()+ expect(screen.getByText('Failed to execute SQL')).toBeInTheDocument()+ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })++ it('announces outcome updates in the existing status region', () => {+ const { rerender } = render(+ <Confirm state="approval-requested" message="Run query" successMessage="Query executed">+ <div>Query preview</div>+ </Confirm>+ )+ const status = screen.getByRole('status')++ expect(status).toHaveTextContent('Run query')++ rerender(+ <Confirm state="success" message="Run query" successMessage="Query executed">+ <div>Query preview</div>+ </Confirm>+ )++ expect(screen.getByRole('status')).toBe(status)+ expect(status).toHaveTextContent('Query executed')+ })+})diff --git a/apps/studio/components/ui/AIAssistantPanel/Confirm.tsx b/apps/studio/components/ui/AIAssistantPanel/Confirm.tsxindex a3a7d26c975..bdd6d4e283d 100644--- a/apps/studio/components/ui/AIAssistantPanel/Confirm.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/Confirm.tsx@@ -1,7 +1,8 @@-import { type PropsWithChildren } from 'react'+import { Check, X } from 'lucide-react'+import { type PropsWithChildren, type ReactNode } from 'react'import { Button, cn } from 'ui'-import { getConfirmFooterBar } from './Confirm.utils'+import { getConfirmFooterBar, type ConfirmFooterApprovalState } from './Confirm.utils'interface ConfirmFooterProps {message: string@@ -10,6 +11,9 @@ interface ConfirmFooterProps {confirmLabelLoading?: stringisLoading?: booleanisDisabled?: boolean+ outcome?: 'success' | 'error' | 'denied'+ showActions?: boolean+ action?: ReactNode/** Omit the confirm button so only Skip remains (unparseable / unapplyable previews). */denyOnly?: boolean/** Escape hatch for consumers that attach the bar directly under their own frame. */@@ -26,6 +30,9 @@ export const ConfirmFooter = ({confirmLabelLoading = 'Working...',isLoading = false,isDisabled = false,+ outcome,+ showActions = true,+ action,denyOnly = false,className,onCancel,@@ -41,17 +48,28 @@ export const ConfirmFooter = ({className)}>- <div className="min-w-0 flex-1">{message}</div>- <div className="flex shrink-0 items-center gap-2">- <Button size="tiny" variant="outline" onClick={onCancel} disabled={isInactive}>- {cancelLabel}- </Button>- {!denyOnly && (- <Button size="tiny" variant="primary" onClick={onConfirm} disabled={isInactive}>- {isLoading ? confirmLabelLoading : confirmLabel}- </Button>- )}+ <div role="status" className="min-w-0 flex flex-1 items-center gap-2">+ {outcome === 'success' && <Check className="size-3.5 shrink-0 text-brand" />}+ {outcome === 'error' && <X className="size-3.5 shrink-0 text-danger" />}+ <span>{message}</span></div>+ {(showActions || action) && (+ <div className="flex shrink-0 items-center gap-2">+ {showActions && (+ <>+ <Button size="tiny" variant="outline" onClick={onCancel} disabled={isInactive}>+ {cancelLabel}+ </Button>+ {!denyOnly && (+ <Button size="tiny" variant="primary" onClick={onConfirm} disabled={isInactive}>+ {isLoading ? confirmLabelLoading : confirmLabel}+ </Button>+ )}+ </>+ )}+ {action}+ </div>+ )}</div>)}@@ -61,11 +79,15 @@ interface ConfirmProps {* Result of `getManualToolApprovalConfirmState`. Interactive buttons only for* `approval-requested`; `approval-responded` is the post-approve loading morph.*/- state?: string+ state?: ConfirmFooterApprovalStatemessage: stringcancelLabel?: stringconfirmLabel?: stringconfirmLabelLoading?: string+ successMessage?: string+ errorMessage?: string+ deniedMessage?: string+ footerAction?: ReactNodeextraLoading?: booleanisLoading?: boolean/**@@ -93,6 +115,10 @@ export const Confirm = ({cancelLabel = 'Skip',confirmLabel = 'Confirm',confirmLabelLoading = 'Working...',+ successMessage,+ errorMessage,+ deniedMessage,+ footerAction,extraLoading = false,isLoading = false,fill = false,@@ -104,6 +130,12 @@ export const Confirm = ({const bar = getConfirmFooterBar(state)const showLoading = bar.isLoading || extraLoading || isLoadingconst isApprovalRequested = state === 'approval-requested'+ const outcomeMessages = {+ success: successMessage,+ error: errorMessage,+ denied: deniedMessage,+ }+ const footerMessage = bar.outcome ? (outcomeMessages[bar.outcome] ?? message) : messagereturn (<div@@ -120,12 +152,15 @@ export const Confirm = ({</div>{bar.show && (<ConfirmFooter- message={message}+ message={footerMessage}cancelLabel={cancelLabel}confirmLabel={confirmLabel}confirmLabelLoading={confirmLabelLoading}isLoading={showLoading}isDisabled={!isApprovalRequested}+ outcome={bar.outcome}+ showActions={isApprovalRequested}+ action={footerAction}denyOnly={denyOnly}onCancel={onCancel}onConfirm={onConfirm}diff --git a/apps/studio/components/ui/AIAssistantPanel/Confirm.utils.test.ts b/apps/studio/components/ui/AIAssistantPanel/Confirm.utils.test.tsindex 933e5c0c64c..cadfe23d5e1 100644--- a/apps/studio/components/ui/AIAssistantPanel/Confirm.utils.test.ts+++ b/apps/studio/components/ui/AIAssistantPanel/Confirm.utils.test.ts@@ -21,10 +21,22 @@ describe('getConfirmFooterBar', () => {expect(getConfirmFooterBar('approval-responded')).toEqual({ show: true, isLoading: true })})- it('hides the bar for every other tool state', () => {- expect(getConfirmFooterBar('input-available')).toEqual({ show: false, isLoading: false })- expect(getConfirmFooterBar('output-available')).toEqual({ show: false, isLoading: false })- expect(getConfirmFooterBar('output-denied')).toEqual({ show: false, isLoading: false })+ it('shows a terminal outcome after a completed approval', () => {+ expect(getConfirmFooterBar('success')).toEqual({+ show: true,+ isLoading: false,+ outcome: 'success',+ })+ expect(getConfirmFooterBar('error')).toEqual({+ show: true,+ isLoading: false,+ outcome: 'error',+ })+ expect(getConfirmFooterBar('denied')).toEqual({+ show: true,+ isLoading: false,+ outcome: 'denied',+ })})})@@ -47,6 +59,27 @@ describe('getManualToolApprovalConfirmState', () => {).toBe('approval-responded')})+ it('keeps a terminal footer after a manual tool completes', () => {+ expect(+ getManualToolApprovalConfirmState({+ state: 'output-available',+ approval: { id: 'approval-1', approved: true },+ })+ ).toBe('success')+ expect(+ getManualToolApprovalConfirmState({+ state: 'output-error',+ approval: { id: 'approval-1', approved: true },+ })+ ).toBe('error')+ expect(+ getManualToolApprovalConfirmState({+ state: 'output-denied',+ approval: { id: 'approval-1', approved: false },+ })+ ).toBe('denied')+ })+it('hides the footer for automatic approvals', () => {expect(getManualToolApprovalConfirmState({@@ -71,9 +104,10 @@ describe('getManualToolApprovalConfirmState', () => {).toBeUndefined()})- it('ignores non-approval tool states', () => {+ it('ignores terminal states that were not manually approved', () => {expect(getManualToolApprovalConfirmState({ state: 'input-available' })).toBeUndefined()expect(getManualToolApprovalConfirmState({ state: 'output-available' })).toBeUndefined()+ expect(getManualToolApprovalConfirmState({ state: 'output-error' })).toBeUndefined()expect(getManualToolApprovalConfirmState({ state: 'output-denied' })).toBeUndefined()})})diff --git a/apps/studio/components/ui/AIAssistantPanel/Confirm.utils.ts b/apps/studio/components/ui/AIAssistantPanel/Confirm.utils.tsindex 9ce728c9294..d6061f4620e 100644--- a/apps/studio/components/ui/AIAssistantPanel/Confirm.utils.ts+++ b/apps/studio/components/ui/AIAssistantPanel/Confirm.utils.ts@@ -1,4 +1,9 @@-export type ConfirmFooterApprovalState = 'approval-requested' | 'approval-responded'+export type ConfirmFooterApprovalState =+ | 'approval-requested'+ | 'approval-responded'+ | 'success'+ | 'error'+ | 'denied'/** Sent with Skip so the model sees a user choice, not the SDK default "Tool execution denied." */export const USER_SKIPPED_TOOL_REASON = 'The user skipped this action.'@@ -11,20 +16,27 @@ export type ToolApprovalFields = {}/**- * Whether the confirm bar should render, and whether it is in the post-approve loading- * morph. Driven by the AI SDK tool approval state; any other state hides the bar.+ * Whether the confirm bar should render, and whether it is loading or in a terminal state.+ * Driven by the AI SDK tool approval state; any other state hides the bar.*/-export function getConfirmFooterBar(state?: string): { show: boolean; isLoading: boolean } {+export function getConfirmFooterBar(state?: ConfirmFooterApprovalState): {+ show: boolean+ isLoading: boolean+ outcome?: 'success' | 'error' | 'denied'+} {if (state === 'approval-requested') return { show: true, isLoading: false }if (state === 'approval-responded') return { show: true, isLoading: true }+ if (state === 'success' || state === 'error' || state === 'denied') {+ return { show: true, isLoading: false, outcome: state }+ }return { show: false, isLoading: false }}/*** Maps a tool part onto the confirm footer. Follows the AI SDK `useChat` rule:* interactive Approve/Deny only for `approval-requested` when `!approval.isAutomatic`.- * `approval-responded` keeps a loading morph after a manual approve; denials and- * automatic decisions hide the bar.+ * `approval-responded` keeps a loading morph after a manual approve. Completed manual+ * approvals stay visible as a terminal outcome; automatic decisions never get a footer.** @see https://ai-sdk.dev/docs/agents/tool-approvals*/@@ -38,6 +50,9 @@ export function getManualToolApprovalConfirmState({if (approval?.isAutomatic) return undefinedif (state === 'approval-requested') return 'approval-requested'if (state === 'approval-responded' && approval?.approved !== false) return 'approval-responded'+ if (state === 'output-available' && approval?.approved === true) return 'success'+ if (state === 'output-error' && approval?.approved === true) return 'error'+ if (state === 'output-denied' && approval?.approved === false) return 'denied'return undefined}diff --git a/apps/studio/components/ui/AIAssistantPanel/EdgeFunctionRenderer.tsx b/apps/studio/components/ui/AIAssistantPanel/EdgeFunctionRenderer.tsxindex d22e46c9cd5..5b866559f45 100644--- a/apps/studio/components/ui/AIAssistantPanel/EdgeFunctionRenderer.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/EdgeFunctionRenderer.tsx@@ -16,6 +16,7 @@ interface EdgeFunctionRendererProps {onDeny?: () => voidisDeploying?: booleaninitialIsDeployed?: boolean+ errorText?: stringconfirmState?: ConfirmFooterApprovalState}@@ -27,6 +28,7 @@ export const EdgeFunctionRenderer = ({onDeny,isDeploying = false,initialIsDeployed,+ errorText,confirmState,}: EdgeFunctionRendererProps) => {const { ref } = useParams()@@ -85,6 +87,9 @@ export const EdgeFunctionRenderer = ({cancelLabel="Skip"confirmLabel="Deploy"confirmLabelLoading="Deploying..."+ successMessage="Edge Function deployed"+ errorMessage="Failed to deploy Edge Function"+ deniedMessage="Skipped Edge Function deployment"isLoading={isDeploying}onCancel={onDeny}onConfirm={handleDeploy}@@ -97,6 +102,7 @@ export const EdgeFunctionRenderer = ({disabled={isConfirming}isDeploying={isDeploying}isDeployed={initialIsDeployed}+ errorText={errorText}functionUrl={functionUrl}deploymentDetailsUrl={deploymentDetailsUrl}downloadCommand={downloadCommand}diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsxindex b3b4fe25584..821f1d7cbfa 100644--- a/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx@@ -110,24 +110,17 @@ function ToolDisplayExecuteSqlLoading({ label = 'Writing SQL...' }: { label?: st)}-function ToolDisplayExecuteSqlFailure() {- return <div className="text-xs text-danger">Failed to execute SQL.</div>-}-function MessagePartExecuteSql({ toolPart }: { toolPart: ToolUIPart }) {const { id } = useMessageInfoContext()const { addToolApprovalResponse } = useMessageActionsContext()- const { toolCallId, state, input, output } = toolPart+ const { toolCallId, state, input: submittedInput, output } = toolPart+ const input = state === 'output-error' ? (submittedInput ?? toolPart.rawInput) : submittedInputif (state === 'input-streaming') {return <ToolDisplayExecuteSqlLoading />}- if (state === 'output-error') {- return <ToolDisplayExecuteSqlFailure />- }-const { data: chart, success } = parseExecuteSqlChartResult(input)if (!success) return null@@ -136,7 +129,8 @@ function MessagePartExecuteSql({ toolPart }: { toolPart: ToolUIPart }) {state === 'approval-requested' ||state === 'approval-responded' ||state === 'output-denied' ||- state === 'output-available'+ state === 'output-available' ||+ state === 'output-error') {const { confirmState, onApprove, onDeny } = getManualToolApprovalHandlers({state,@@ -150,7 +144,11 @@ function MessagePartExecuteSql({ toolPart }: { toolPart: ToolUIPart }) {id={`${id}-${toolCallId}`}sql={chart.sql}title={chart.label}- initialResult={toAssistantQueryResult(output)}+ initialResult={+ state === 'output-error'+ ? { rows: [], error: { message: toolPart.errorText ?? 'Failed to execute SQL' } }+ : toAssistantQueryResult(output)+ }view={chart.view}xAxis={chart.xAxis}yAxis={chart.yAxis}@@ -171,10 +169,12 @@ const TOOL_DEPLOY_EDGE_FUNCTION_STATES_WITH_INPUT = new Set(['approval-responded','output-denied','output-available',+ 'output-error',])function MessagePartDeployEdgeFunction({ toolPart }: { toolPart: ToolUIPart }) {- const { state, input, output } = toolPart+ const { state, input: submittedInput, output } = toolPart+ const input = state === 'output-error' ? (submittedInput ?? toolPart.rawInput) : submittedInputconst { addToolApprovalResponse } = useMessageActionsContext()if (state === 'input-streaming') {@@ -186,10 +186,6 @@ function MessagePartDeployEdgeFunction({ toolPart }: { toolPart: ToolUIPart }) {)}- if (state === 'output-error') {- return <p className="text-xs text-danger">Failed to deploy Edge Function.</p>- }-if (!TOOL_DEPLOY_EDGE_FUNCTION_STATES_WITH_INPUT.has(state)) return nullconst parsedInput = deployEdgeFunctionInputSchema.safeParse(input)@@ -213,6 +209,7 @@ function MessagePartDeployEdgeFunction({ toolPart }: { toolPart: ToolUIPart }) {confirmState={confirmState}isDeploying={confirmState === 'approval-responded'}initialIsDeployed={isInitiallyDeployed}+ errorText={state === 'output-error' ? toolPart.errorText : undefined}onApprove={onApprove}onDeny={onDeny}/>@@ -224,11 +221,6 @@ const NOTEBOOK_DRAFTING_LABEL: Record<NotebookProposalMode, string> = {update: 'Drafting notebook update...',}-const NOTEBOOK_FAILED_LABEL: Record<NotebookProposalMode, string> = {- create: 'Failed to create notebook.',- update: 'Failed to update notebook.',-}-function MessagePartNotebookProposal({toolPart,mode,@@ -236,7 +228,8 @@ function MessagePartNotebookProposal({toolPart: ToolUIPartmode: NotebookProposalMode}) {- const { state, input, output } = toolPart+ const { state, input: submittedInput, output } = toolPart+ const input = state === 'output-error' ? (submittedInput ?? toolPart.rawInput) : submittedInputconst { addToolApprovalResponse } = useMessageActionsContext()if (state === 'input-streaming') {@@ -248,10 +241,6 @@ function MessagePartNotebookProposal({)}- if (state === 'output-error') {- return <p className="text-xs text-danger px-4">{NOTEBOOK_FAILED_LABEL[mode]}</p>- }-const { confirmState, onApprove, onDeny } = getManualToolApprovalHandlers({state,approval: toolPart.approval,diff --git a/apps/studio/components/ui/AIAssistantPanel/MessagePartQueryLogs.test.tsx b/apps/studio/components/ui/AIAssistantPanel/MessagePartQueryLogs.test.tsxnew file mode 100644index 00000000000..9eac304587a--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/MessagePartQueryLogs.test.tsx@@ -0,0 +1,52 @@+import { screen } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'++import { MessageProvider } from './Message.Context'+import { MessagePartQueryLogs } from './MessagePartQueryLogs'+import { customRender as render } from '@/tests/lib/custom-render'++vi.mock('./AssistantQueryCell', () => ({+ AssistantQueryCell: ({+ sql,+ initialResult,+ }: {+ sql: string+ initialResult?: { error?: Error }+ }) => (+ <div>+ <span>{sql}</span>+ <span>{initialResult?.error?.message}</span>+ </div>+ ),+}))++type QueryLogsToolPart = Parameters<typeof MessagePartQueryLogs>[0]['toolPart']++describe('MessagePartQueryLogs', () => {+ it('renders an output error using raw input when submitted input is unavailable', () => {+ const toolPart = {+ toolCallId: 'query-logs-1',+ state: 'output-error',+ input: undefined,+ rawInput: { sql: 'select count(*) from edge_logs' },+ errorText: 'Log query timed out',+ } as QueryLogsToolPart++ render(+ <MessageProvider+ messageInfo={{ id: 'message-1', isLoading: false, state: 'idle' }}+ messageActions={{+ onDelete: vi.fn(),+ onEdit: vi.fn(),+ onBranch: vi.fn(),+ onCancelEdit: vi.fn(),+ }}+ >+ <MessagePartQueryLogs toolPart={toolPart} />+ </MessageProvider>+ )++ expect(screen.getByText('select count(*) from edge_logs')).toBeInTheDocument()+ expect(screen.getByText('Log query timed out')).toBeInTheDocument()+ })+})diff --git a/apps/studio/components/ui/AIAssistantPanel/MessagePartQueryLogs.tsx b/apps/studio/components/ui/AIAssistantPanel/MessagePartQueryLogs.tsxindex 9c3976f79d4..006dfbcc9d2 100644--- a/apps/studio/components/ui/AIAssistantPanel/MessagePartQueryLogs.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/MessagePartQueryLogs.tsx@@ -10,15 +10,14 @@ import {toQueryLogsResult,} from './MessagePartQueryLogs.utils'-type QueryLogsToolPart = Pick<ToolUIPart, 'toolCallId' | 'state' | 'input' | 'output'>--function QueryLogsFailure() {- return <div className="text-xs text-danger">Failed to query logs.</div>-}+type QueryLogsToolPart = Pick<+ ToolUIPart,+ 'toolCallId' | 'state' | 'input' | 'output' | 'errorText'+> & { rawInput?: unknown }export function MessagePartQueryLogs({ toolPart }: { toolPart: QueryLogsToolPart }) {const { id } = useMessageInfoContext()- const { toolCallId, state, input, output } = toolPart+ const { toolCallId, state, input: submittedInput, rawInput, output } = toolPartif (state === 'input-streaming' || state === 'input-available') {return (@@ -29,14 +28,16 @@ export function MessagePartQueryLogs({ toolPart }: { toolPart: QueryLogsToolPart)}- if (state === 'output-error') return <QueryLogsFailure />- if (state !== 'output-available') return null+ if (state !== 'output-available' && state !== 'output-error') return null- const parsedInput = parseQueryLogsInput(input)- const result = toQueryLogsResult(output)- if (!parsedInput.success || !result) {- return <QueryLogsFailure />- }+ const parsedInput = parseQueryLogsInput(submittedInput ?? rawInput)+ if (!parsedInput.success) return null++ const result =+ state === 'output-error'+ ? { rows: [], error: { message: toolPart.errorText ?? 'Failed to query logs' } }+ : toQueryLogsResult(output)+ if (!result) return nullreturn (<div className="w-auto overflow-x-hidden my-4 space-y-2">@@ -52,6 +53,7 @@ export function MessagePartQueryLogs({ toolPart }: { toolPart: QueryLogsToolPart),}}initialResult={result}+ confirmState={state === 'output-error' ? 'error' : undefined}/></div>)diff --git a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsxindex df86f4795e2..e7e08152e71 100644--- a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx@@ -151,18 +151,97 @@ describe('NotebookProposalRenderer', () => {expect(onApprove).not.toHaveBeenCalled()})- it('renders an Open notebook link once output is available', () => {+ it('keeps the create preview and marks it successful once output is available', () => {render(<NotebookProposalRenderermode="create"state="output-available"- input={{}}+ confirmState="success"+ input={{+ name: 'Signup funnel',+ content: {+ schema_version: 1,+ cells: [{ _tag: 'markdown_cell', text: 'hello' }],+ },+ }}+ output={{ id: NOTEBOOK_ID, name: 'Signup funnel' }}+ />+ )++ expect(screen.getByRole('toolbar', { name: 'Notebook toolbar' })).toBeInTheDocument()+ expect(screen.getByText('Signup funnel')).toBeInTheDocument()+ expect(screen.getByText('Notebook created')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Create' })).not.toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'Open notebook' })).toHaveAttribute(+ 'href',+ `/project/default/explorer/notebook/${NOTEBOOK_ID}`+ )+ })++ it('shows the notebook action after an automatic create succeeds', () => {+ render(+ <NotebookProposalRenderer+ mode="create"+ state="output-available"+ input={{+ name: 'Signup funnel',+ content: {+ schema_version: 1,+ cells: [{ _tag: 'markdown_cell', text: 'hello' }],+ },+ }}+ output={{ id: NOTEBOOK_ID, name: 'Signup funnel' }}+ />+ )++ expect(screen.getByRole('link', { name: 'Open notebook' })).toHaveAttribute(+ 'href',+ `/project/default/explorer/notebook/${NOTEBOOK_ID}`+ )+ })++ it('shows the notebook action after an automatic update succeeds', async () => {+ mockContentItem(mockNotebookRow())++ render(+ <NotebookProposalRenderer+ mode="update"+ state="output-available"+ input={{+ id: NOTEBOOK_ID,+ expected_updated_at: '2024-01-01T00:00:00.000Z',+ operations: [{ _tag: 'delete_cell', cell_id: 'cell-1' }],+ }}output={{ id: NOTEBOOK_ID, name: 'Signup funnel' }}/>)- const link = screen.getByRole('link', { name: 'Open notebook' })- expect(link).toHaveAttribute('href', `/project/default/explorer/notebook/${NOTEBOOK_ID}`)+ expect(await screen.findByRole('link', { name: 'Open notebook' })).toHaveAttribute(+ 'href',+ `/project/default/explorer/notebook/${NOTEBOOK_ID}`+ )+ })++ it('keeps the create preview and marks it failed when the tool errors', () => {+ render(+ <NotebookProposalRenderer+ mode="create"+ state="output-error"+ confirmState="error"+ input={{+ name: 'New notebook',+ content: {+ schema_version: 1,+ cells: [{ _tag: 'markdown_cell', text: 'hello' }],+ },+ }}+ output={undefined}+ />+ )++ expect(screen.getByRole('toolbar', { name: 'Notebook toolbar' })).toBeInTheDocument()+ expect(screen.getByText('New notebook')).toBeInTheDocument()+ expect(screen.getByText('Failed to create notebook')).toBeInTheDocument()})it('keeps the preview in the message after skip', () => {diff --git a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsxindex e59c5d6aa06..2e136d3315c 100644--- a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx@@ -1,7 +1,7 @@import { useParams } from 'common'import { Loader2 } from 'lucide-react'import Link from 'next/link'-import { type PropsWithChildren } from 'react'+import { type PropsWithChildren, type ReactNode } from 'react'import { Button } from 'ui'import { Admonition } from 'ui-patterns/Admonition'import { CodeBlock } from 'ui-patterns/CodeBlock'@@ -25,14 +25,13 @@ import { toWireNotebook } from '@/data/content/notebooks/notebook-schema'export type NotebookProposalMode = 'create' | 'update'-// input-streaming and output-error are handled by the caller before this component is-// rendered — see MessagePartNotebookProposal in Message.Parts.tsx.export type NotebookProposalState =| 'input-available'| 'approval-requested'| 'approval-responded'| 'output-denied'| 'output-available'+ | 'output-error'export interface NotebookProposalRendererProps {mode: NotebookProposalMode@@ -45,7 +44,12 @@ export interface NotebookProposalRendererProps {onDeny?: () => void}-type NotebookProposalStepProps = Omit<NotebookProposalRendererProps, 'mode' | 'output' | 'state'>+type NotebookProposalStepProps = Omit<+ NotebookProposalRendererProps,+ 'mode' | 'output' | 'state'+> & {+ footerAction?: ReactNode+}const MODE_COPY = {create: {@@ -69,48 +73,42 @@ const MODE_COPY = {* same way `AssistantQueryCell` wraps `QueryEditor`.*/export const NotebookProposalRenderer = (props: NotebookProposalRendererProps) => {- const { mode, state, output } = props-- if (state === 'output-available') {- return <NotebookOutputSummary mode={mode} output={output} />- }-- const { input, confirmState, onApprove, onDeny } = props- return mode === 'create' ? (- <CreateNotebookProposal- input={input}- confirmState={confirmState}- onApprove={onApprove}- onDeny={onDeny}- />- ) : (- <UpdateNotebookProposal- input={input}- confirmState={confirmState}- onApprove={onApprove}- onDeny={onDeny}- />- )-}--function NotebookOutputSummary({ mode, output }: { mode: NotebookProposalMode; output: unknown }) {const { ref } = useParams()+ const { mode, state, input, output, confirmState, onApprove, onDeny } = propsconst parsedOutput = notebookToolOutputSchema.safeParse(output)- const label = MODE_COPY[mode].outputLabel+ const footerAction =+ state === 'output-available' && parsedOutput.success && ref ? (+ <Button asChild variant="default" size="tiny">+ <Link href={`/project/${ref}/explorer/notebook/${parsedOutput.data.id}`}>+ Open notebook+ </Link>+ </Button>+ ) : undefined++ const proposal =+ mode === 'create' ? (+ <CreateNotebookProposal+ input={input}+ confirmState={confirmState}+ footerAction={confirmState === undefined ? undefined : footerAction}+ onApprove={onApprove}+ onDeny={onDeny}+ />+ ) : (+ <UpdateNotebookProposal+ input={input}+ confirmState={confirmState}+ footerAction={confirmState === undefined ? undefined : footerAction}+ onApprove={onApprove}+ onDeny={onDeny}+ />+ )return (- <div className="flex items-center justify-between gap-2 my-2 mx-4 px-3 py-1.5 text-sm border rounded-md bg-surface-75">- <span className="text-foreground-light truncate">- {parsedOutput.success ? `${label}: ${parsedOutput.data.name}` : label}- </span>- {parsedOutput.success && ref && (- <Button asChild variant="default" size="tiny">- <Link href={`/project/${ref}/explorer/notebook/${parsedOutput.data.id}`}>- Open notebook- </Link>- </Button>- )}- </div>+ <>+ {proposal}+ {confirmState === undefined && footerAction}+ </>)}@@ -122,6 +120,7 @@ interface NotebookConfirmProps {confirmLabelLoading?: stringextraLoading?: booleandenyOnly?: boolean+ footerAction?: ReactNodeonApprove?: () => voidonDeny?: () => void}@@ -135,6 +134,7 @@ function NotebookConfirm({confirmLabelLoading,extraLoading,denyOnly,+ footerAction,onApprove,onDeny,children,@@ -149,6 +149,10 @@ function NotebookConfirm({cancelLabel="Skip"confirmLabel={confirmLabel ?? copy.confirmLabel}confirmLabelLoading={confirmLabelLoading ?? copy.confirmLabelLoading}+ successMessage={copy.outputLabel}+ errorMessage={`Failed to ${mode} notebook`}+ deniedMessage={`Skipped notebook ${mode === 'create' ? 'creation' : 'update'}`}+ footerAction={footerAction}extraLoading={extraLoading}denyOnly={denyOnly}onCancel={onDeny}@@ -188,6 +192,7 @@ function NotebookParseFailure({function CreateNotebookProposal({input,confirmState,+ footerAction,onApprove,onDeny,}: NotebookProposalStepProps) {@@ -216,6 +221,7 @@ function CreateNotebookProposal({<NotebookConfirmmode="create"confirmState={confirmState}+ footerAction={footerAction}onApprove={onApprove}onDeny={onDeny}>@@ -227,6 +233,7 @@ function CreateNotebookProposal({function UpdateNotebookProposal({input,confirmState,+ footerAction,onApprove,onDeny,}: NotebookProposalStepProps) {@@ -308,6 +315,7 @@ function UpdateNotebookProposal({<NotebookConfirmmode="update"confirmState={confirmState}+ footerAction={footerAction}message={`Assistant wants to update "${notebook.name}"`}onApprove={onApprove}onDeny={onDeny}