Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix: hand off AI assistant to the project page in org view (#49477)

Monica Khouryd5ee11bea0cb
diff --git a/apps/studio/components/interfaces/Support/ProjectAndPlanInfo.tsx b/apps/studio/components/interfaces/Support/ProjectAndPlanInfo.tsx
index 5f0fa748e0b..344a85671b3 100644
--- a/apps/studio/components/interfaces/Support/ProjectAndPlanInfo.tsx
+++ b/apps/studio/components/interfaces/Support/ProjectAndPlanInfo.tsx
@@ -22,7 +22,8 @@ interface ProjectAndPlanProps {
form: UseFormReturn<SupportFormValues>
orgSlug: string | null
projectRef: string | null
- category: ExtendedSupportCategories
+ // Unused — kept optional so SupportFormV2 (which still passes it) doesn't need updating.
+ category?: ExtendedSupportCategories
subscriptionPlanId: string | undefined
}
@@ -30,7 +31,6 @@ export function ProjectAndPlanInfo({
form,
orgSlug,
projectRef,
- category: _category,
subscriptionPlanId: _subscriptionPlanId,
}: ProjectAndPlanProps) {
const hasProjectSelected = projectRef && projectRef !== NO_PROJECT_MARKER
@@ -61,7 +61,7 @@ function ProjectSelector({ form, orgSlug, projectRef }: ProjectSelectorProps) {
name="projectRef"
control={form.control}
render={({ field }) => (
- <FormItemLayout hideMessage layout="vertical" label="Which project is affected?">
+ <FormItemLayout layout="vertical" label="Which project is affected?">
<FormControl>
<OrganizationProjectSelector
key={orgSlug}
@@ -74,7 +74,6 @@ function ProjectSelector({ form, orgSlug, projectRef }: ProjectSelectorProps) {
const hasSelectedProject = !!projectRef && projectRef !== NO_PROJECT_MARKER
const hasRouteProjectInList =
!!routeProjectRef && projects.some((project) => project.ref === routeProjectRef)
-
if (!hasRouteProjectInList && !hasSelectedProject) {
field.onChange(projects[0]?.ref ?? NO_PROJECT_MARKER)
}
diff --git a/apps/studio/components/interfaces/Support/SupportAssistant.utils.test.ts b/apps/studio/components/interfaces/Support/SupportAssistant.utils.test.ts
index 775b25a90ae..0ae1f599251 100644
--- a/apps/studio/components/interfaces/Support/SupportAssistant.utils.test.ts
+++ b/apps/studio/components/interfaces/Support/SupportAssistant.utils.test.ts
@@ -1,7 +1,12 @@
import { SupportCategories } from '@supabase/shared-types/out/constants'
-import { describe, expect, it } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { buildSupportAssistantPrompt, parseSupportAssistantPrompt } from './SupportAssistant.utils'
+import {
+ buildSupportAssistantPrompt,
+ consumeAssistantHandoff,
+ parseSupportAssistantPrompt,
+ storeAssistantHandoff,
+} from './SupportAssistant.utils'
import type { SubmittedSupportRequest } from './SupportForm.state'
const supportRequest: SubmittedSupportRequest = {
@@ -18,6 +23,10 @@ const supportRequest: SubmittedSupportRequest = {
}
describe('SupportAssistant utils', () => {
+ beforeEach(() => {
+ sessionStorage.clear()
+ })
+
it('formats support requests as tagged assistant prompts', () => {
const prompt = buildSupportAssistantPrompt(supportRequest)
@@ -65,4 +74,57 @@ describe('SupportAssistant utils', () => {
expect(parseSupportAssistantPrompt('Help me debug this issue')).toBeNull()
expect(parseSupportAssistantPrompt('<support></support>')).toBeNull()
})
+
+ it('round-trips a request through store/consume', () => {
+ storeAssistantHandoff('token-1', supportRequest)
+
+ expect(consumeAssistantHandoff('token-1')).toEqual(supportRequest)
+ })
+
+ it('preserves literal percent characters in the message (no URL encoding involved)', () => {
+ const request = { ...supportRequest, message: '100% CPU, literal %20 text' }
+ storeAssistantHandoff('token-1', request)
+
+ expect(consumeAssistantHandoff('token-1')?.message).toBe('100% CPU, literal %20 text')
+ })
+
+ it('removes the entry after consuming it, so it cannot be replayed', () => {
+ storeAssistantHandoff('token-1', supportRequest)
+
+ expect(consumeAssistantHandoff('token-1')).toEqual(supportRequest)
+ expect(consumeAssistantHandoff('token-1')).toBeNull()
+ })
+
+ it('returns null for a token that was never stored', () => {
+ expect(consumeAssistantHandoff('unknown-token')).toBeNull()
+ })
+
+ it('returns null for malformed JSON', () => {
+ sessionStorage.setItem('assistant-handoff:token-1', '{not valid json')
+
+ expect(consumeAssistantHandoff('token-1')).toBeNull()
+ })
+
+ it('returns null for validly-shaped JSON that does not match the expected schema', () => {
+ sessionStorage.setItem('assistant-handoff:token-1', JSON.stringify({ foo: 'bar' }))
+ expect(consumeAssistantHandoff('token-1')).toBeNull()
+
+ sessionStorage.setItem(
+ 'assistant-handoff:token-2',
+ JSON.stringify({ ...supportRequest, allowSupportAccess: 'yes' })
+ )
+ expect(consumeAssistantHandoff('token-2')).toBeNull()
+ })
+
+ it('still returns the parsed value when cleanup (removeItem) throws', () => {
+ storeAssistantHandoff('token-1', supportRequest)
+
+ const removeItemSpy = vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => {
+ throw new Error('storage unavailable')
+ })
+
+ expect(consumeAssistantHandoff('token-1')).toEqual(supportRequest)
+
+ removeItemSpy.mockRestore()
+ })
})
diff --git a/apps/studio/components/interfaces/Support/SupportAssistant.utils.ts b/apps/studio/components/interfaces/Support/SupportAssistant.utils.ts
index cbdf414dbbd..2cbf4030a61 100644
--- a/apps/studio/components/interfaces/Support/SupportAssistant.utils.ts
+++ b/apps/studio/components/interfaces/Support/SupportAssistant.utils.ts
@@ -1,3 +1,6 @@
+import { SupportCategories } from '@supabase/shared-types/out/constants'
+import { z } from 'zod'
+
import type { SubmittedSupportRequest } from './SupportForm.state'
const SUPPORT_ASSISTANT_FIELD_LABELS = {
@@ -54,6 +57,67 @@ export function buildSupportAssistantPrompt(request: SubmittedSupportRequest) {
].join('\n')
}
+export const ASSISTANT_HANDOFF_QUERY_PARAM = 'assistantHandoff'
+
+// Not typed as z.ZodType<SubmittedSupportRequest>: zod always models "may be undefined"
+// as an optional key, while SubmittedSupportRequest declares organizationSlug/projectRef
+// as required keys whose value may be undefined — a distinction JSON can't carry anyway,
+// since JSON.stringify drops undefined-valued keys entirely.
+const AssistantHandoffSchema = z.object({
+ organizationSlug: z.string().optional(),
+ projectRef: z.string().optional(),
+ category: z.union([
+ z.nativeEnum(SupportCategories),
+ z.literal('Plan_upgrade'),
+ z.literal('Others'),
+ ]),
+ severity: z.string(),
+ subject: z.string(),
+ message: z.string(),
+ affectedServices: z.string(),
+ allowSupportAccess: z.boolean(),
+ library: z.string().optional(),
+ dashboardLogs: z.string().optional(),
+ threadRef: z.string().optional(),
+ frontConversationId: z.string().optional(),
+})
+
+const ASSISTANT_HANDOFF_STORAGE_PREFIX = 'assistant-handoff:'
+
+// The handoff URL only ever carries an opaque token — the actual ticket content (subject,
+// message, any attached log links) is kept out of the URL entirely (browser history,
+// referrer headers, server logs, a copy-pasted link) by round-tripping it through
+// sessionStorage instead, scoped to this one tab and gone once it's been read or the tab closes.
+export function storeAssistantHandoff(token: string, request: SubmittedSupportRequest): void {
+ try {
+ sessionStorage.setItem(ASSISTANT_HANDOFF_STORAGE_PREFIX + token, JSON.stringify(request))
+ } catch {
+ // Handoff will just fail closed (no context) on the receiving end — not worth
+ // surfacing an error for a private-browsing/storage-full edge case.
+ }
+}
+
+export function consumeAssistantHandoff(token: string): SubmittedSupportRequest | null {
+ const key = ASSISTANT_HANDOFF_STORAGE_PREFIX + token
+
+ try {
+ const raw = sessionStorage.getItem(key)
+ if (!raw) return null
+
+ const parsed = AssistantHandoffSchema.safeParse(JSON.parse(raw))
+ return parsed.success ? (parsed.data as SubmittedSupportRequest) : null
+ } catch {
+ return null
+ } finally {
+ try {
+ sessionStorage.removeItem(key)
+ } catch {
+ // Best-effort cleanup — a failure here shouldn't override the value (or null)
+ // already produced above.
+ }
+ }
+}
+
export function parseSupportAssistantPrompt(text: string): ParsedSupportAssistantPrompt | null {
const supportMatch = text.match(/<support>([\s\S]*?)<\/support>/i)
if (!supportMatch) return null
diff --git a/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx b/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx
index 544d407176a..c7440cc5706 100644
--- a/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx
+++ b/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx
@@ -68,6 +68,14 @@ vi.mock('@/lib/telemetry/track', () => ({
useTrack: () => mockTrack,
}))
+let mockCurrentProjectRef: string | undefined = 'project-1'
+
+vi.mock('@/hooks/misc/useSelectedProject', () => ({
+ useSelectedProjectQuery: () => ({
+ data: mockCurrentProjectRef ? { ref: mockCurrentProjectRef } : undefined,
+ }),
+}))
+
const supportRequest: SubmittedSupportRequest = {
organizationSlug: 'org-1',
projectRef: 'project-1',
@@ -107,6 +115,8 @@ describe('SupportAssistantSuccessCard', () => {
mockTrack.mockReset()
nextChatMessages = []
emitChatMessagesChange = undefined
+ mockCurrentProjectRef = 'project-1'
+ sessionStorage.clear()
mockNewChat.mockImplementation(() => {
chatInstances['chat-1'] = createMockChat(nextChatMessages)
@@ -264,4 +274,45 @@ describe('SupportAssistantSuccessCard', () => {
expect(screen.queryByText(/assistant response/i)).not.toBeInTheDocument()
expect(mockNewChat).not.toHaveBeenCalled()
})
+
+ describe('when not already on the ticket project page', () => {
+ beforeEach(() => {
+ mockCurrentProjectRef = undefined
+ })
+
+ it('renders a handoff link with an opaque token, keeping the ticket content out of the URL', async () => {
+ render(<SupportAssistantSuccessCard request={supportRequest} />)
+
+ expect(await screen.findByRole('heading', { name: 'While you wait' })).toBeInTheDocument()
+ const link = screen.getByRole('link', { name: /open assistant in project/i })
+ expect(link).toHaveAttribute('href', expect.stringContaining('/project/project-1?'))
+
+ const href = link.getAttribute('href') ?? ''
+ const token = new URL(href, 'https://example.com').searchParams.get('assistantHandoff')
+ expect(token).toBeTruthy()
+ // The message (and the rest of the ticket) must never appear in the URL itself.
+ expect(href).not.toContain(encodeURIComponent(supportRequest.message))
+
+ // The actual ticket content is stashed in sessionStorage instead, keyed by that token.
+ expect(sessionStorage.getItem(`assistant-handoff:${token}`)).toBe(
+ JSON.stringify(supportRequest)
+ )
+ expect(mockNewChat).not.toHaveBeenCalled()
+ })
+
+ it('tracks the click and does not touch the sidebar manager directly', async () => {
+ const user = userEvent.setup()
+ render(<SupportAssistantSuccessCard request={supportRequest} />)
+
+ const link = await screen.findByRole('link', { name: /open assistant in project/i })
+ await user.click(link)
+
+ expect(mockTrack).toHaveBeenCalledWith(
+ 'support_assistant_follow_up_card_clicked',
+ { ticketCategory: SupportCategories.PROBLEM },
+ { project: 'project-1', organization: 'org-1' }
+ )
+ expect(mockOpenSidebar).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/apps/studio/components/interfaces/Support/SupportFormV3.tsx b/apps/studio/components/interfaces/Support/SupportFormV3.tsx
index d3d86d97e68..9fea44e52bf 100644
--- a/apps/studio/components/interfaces/Support/SupportFormV3.tsx
+++ b/apps/studio/components/interfaces/Support/SupportFormV3.tsx
@@ -251,7 +251,6 @@ export const SupportFormV3 = ({
orgSlug={selectedOrgSlug}
projectRef={currentProjectRef}
subscriptionPlanId={subscriptionPlanId}
- category={category}
/>
<CategoryAndSeverityInfo
form={form}
diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx
index 7f3b5b486d2..cafd03d28ea 100644
--- a/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx
@@ -57,7 +57,6 @@ export const LayoutSidebarProvider = ({ children }: PropsWithChildren) => {
router.query.ref as string | undefined
)
- const sidebarURLParamRef = useLatest(sidebarURLParam)
const sidebarLocalStorageRef = useLatest(sidebarLocalStorage)
useRegisterSidebar(SIDEBAR_KEYS.AI_ASSISTANT, () => <AIAssistant />, {}, !!project)
@@ -102,18 +101,16 @@ export const LayoutSidebarProvider = ({ children }: PropsWithChildren) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeSidebar])
- // Handle toggling of sidebars on page init
// Prioritize URL params first, then local storage
useEffect(() => {
if (router.isReady && isLoadedLocalStorage) {
if (
- typeof sidebarURLParamRef.current === 'string' &&
+ typeof sidebarURLParam === 'string' &&
Object.values(SIDEBAR_KEYS).includes(
- sidebarURLParamRef.current as (typeof SIDEBAR_KEYS)[keyof typeof SIDEBAR_KEYS]
+ sidebarURLParam as (typeof SIDEBAR_KEYS)[keyof typeof SIDEBAR_KEYS]
)
) {
- console.log('Open sidebar based on URL')
- openSidebar(sidebarURLParamRef.current)
+ openSidebar(sidebarURLParam)
} else if (
!!sidebarLocalStorageRef.current &&
Object.values(SIDEBAR_KEYS).includes(
@@ -124,7 +121,7 @@ export const LayoutSidebarProvider = ({ children }: PropsWithChildren) => {
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [router.isReady, isLoadedLocalStorage])
+ }, [router.isReady, isLoadedLocalStorage, sidebarURLParam])
return <>{children}</>
}
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.test.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.test.tsx
new file mode 100644
index 00000000000..3539e200861
--- /dev/null
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.test.tsx
@@ -0,0 +1,186 @@
+import { SupportCategories } from '@supabase/shared-types/out/constants'
+import { render, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { AIAssistant } from './AIAssistant'
+import {
+ ASSISTANT_HANDOFF_QUERY_PARAM,
+ storeAssistantHandoff,
+} from '@/components/interfaces/Support/SupportAssistant.utils'
+import type { SubmittedSupportRequest } from '@/components/interfaces/Support/SupportForm.state'
+
+// Every hook this component depends on is mocked directly below (no React Query hooks,
+// no network calls) — this targets the handoff effect's internal logic, not data fetching,
+// so plain `render` is used here rather than `customRender`/`addAPIMock` (same pattern as
+// the neighboring SupportAssistantSuccessCard.test.tsx).
+const {
+ chats,
+ mockNewChat,
+ mockSelectChat,
+ mockRouterReplace,
+ mockSyncSupportChatToFront,
+ mockToastError,
+ routerQuery,
+ routeRef,
+} = vi.hoisted(() => ({
+ chats: {} as Record<string, { supportMetadata?: unknown }>,
+ mockNewChat: vi.fn(),
+ mockSelectChat: vi.fn(),
+ mockRouterReplace: vi.fn(),
+ mockSyncSupportChatToFront: vi.fn(),
+ mockToastError: vi.fn(),
+ routerQuery: {} as Record<string, string>,
+ routeRef: { current: 'project-a' as string | undefined },
+}))
+
+vi.mock('sonner', () => ({
+ toast: { error: mockToastError },
+}))
+
+vi.mock('next/router', () => ({
+ useRouter: () => ({
+ query: routerQuery,
+ pathname: '/project/[ref]',
+ replace: mockRouterReplace,
+ }),
+}))
+
+vi.mock('common/hooks', () => ({
+ useParams: () => ({ id: undefined, source: undefined, ref: routeRef.current }),
+}))
+
+vi.mock('@/state/ai-assistant-state', () => ({
+ useAiAssistantStateSnapshot: () => ({
+ activeChatId: undefined,
+ isInitialized: true,
+ initialInput: '',
+ sqlSnippets: undefined,
+ suggestions: undefined,
+ }),
+ useAiAssistantState: () => ({
+ chats,
+ newChat: mockNewChat,
+ selectChat: mockSelectChat,
+ branchChat: vi.fn(),
+ setSqlSnippets: vi.fn(),
+ clearSqlSnippets: vi.fn(),
+ sqlSnippets: undefined,
+ }),
+}))
+
+vi.mock('@/state/ai-chat-front-sync', () => ({
+ syncSupportChatToFront: mockSyncSupportChatToFront,
+}))
+
+vi.mock('@/state/sql-editor/sql-editor-state', () => ({
+ useSqlEditorV2StateSnapshot: () => ({ snippets: {} }),
+}))
+
+vi.mock('@/state/sidebar-manager-state', () => ({
+ useSidebarManagerSnapshot: () => ({ activeSidebar: undefined, closeSidebar: vi.fn() }),
+}))
+
+vi.mock('@/state/shortcuts/useShortcut', () => ({
+ useShortcut: () => {},
+}))
+
+vi.mock('./AssistantChat', () => ({
+ AssistantChat: () => null,
+}))
+
+const supportRequest: SubmittedSupportRequest = {
+ organizationSlug: 'org-1',
+ projectRef: 'project-a',
+ category: SupportCategories.PROBLEM,
+ severity: 'Normal',
+ subject: 'API requests fail',
+ message: 'Requests fail with 500s',
+ affectedServices: 'api',
+ library: 'javascript',
+ allowSupportAccess: true,
+ dashboardLogs: undefined,
+ threadRef: 'thread-ref-1',
+ frontConversationId: 'front-conversation-1',
+}
+
+describe('AIAssistant handoff', () => {
+ beforeEach(() => {
+ Object.keys(routerQuery).forEach((key) => delete routerQuery[key])
+ Object.keys(chats).forEach((key) => delete chats[key])
+ mockNewChat.mockReset()
+ mockSelectChat.mockReset()
+ mockRouterReplace.mockReset()
+ mockSyncSupportChatToFront.mockReset()
+ mockToastError.mockReset()
+ routeRef.current = 'project-a'
+ sessionStorage.clear()
+
+ mockNewChat.mockImplementation(() => {
+ chats['chat-1'] = {}
+ return 'chat-1'
+ })
+ })
+
+ it('creates and selects the chat when the handoff project matches the route', async () => {
+ storeAssistantHandoff('token-1', supportRequest)
+ routerQuery[ASSISTANT_HANDOFF_QUERY_PARAM] = 'token-1'
+
+ render(<AIAssistant />)
+
+ await waitFor(() => {
+ expect(mockNewChat).toHaveBeenCalledTimes(1)
+ })
+
+ expect(mockSelectChat).toHaveBeenCalledWith('chat-1')
+ expect(chats['chat-1'].supportMetadata).toMatchObject({
+ projectRef: 'project-a',
+ isSupportChat: true,
+ })
+ expect(mockRouterReplace).toHaveBeenCalledWith(
+ { pathname: '/project/[ref]', query: {} },
+ undefined,
+ { shallow: true }
+ )
+ })
+
+ it('starts a new chat and shows a toast when the handoff project does not match the route', async () => {
+ routeRef.current = 'project-b'
+ storeAssistantHandoff('token-1', supportRequest)
+ routerQuery[ASSISTANT_HANDOFF_QUERY_PARAM] = 'token-1'
+
+ render(<AIAssistant />)
+
+ await waitFor(() => {
+ expect(mockRouterReplace).toHaveBeenCalledTimes(1)
+ })
+
+ expect(mockNewChat).toHaveBeenCalledWith()
+ expect(mockSelectChat).not.toHaveBeenCalled()
+ expect(mockToastError).toHaveBeenCalledWith(
+ "Couldn't load your ticket context here — started a new chat instead."
+ )
+ })
+
+ it('does nothing when there is no handoff param', () => {
+ render(<AIAssistant />)
+
+ expect(mockNewChat).not.toHaveBeenCalled()
+ expect(mockRouterReplace).not.toHaveBeenCalled()
+ })
+
+ it('cleans up the URL and falls back to a new chat with a toast when the token has no matching sessionStorage entry (e.g. link opened in a new tab)', async () => {
+ routerQuery[ASSISTANT_HANDOFF_QUERY_PARAM] = 'token-never-stored'
+
+ render(<AIAssistant />)
+
+ await waitFor(() => {
+ expect(mockRouterReplace).toHaveBeenCalledTimes(1)
+ })
+
+ expect(mockNewChat).toHaveBeenCalledWith()
+ expect(mockSelectChat).not.toHaveBeenCalled()
+ expect(mockToastError).toHaveBeenCalledWith(
+ "Couldn't load your ticket context here — started a new chat instead."
+ )
+ })
+})
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
index 8b2b0b1776f..bae0b3c71e0 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
@@ -1,11 +1,17 @@
import type { UIMessage as MessageType } from '@ai-sdk/react'
import { useParams } from 'common/hooks'
import { useRouter } from 'next/router'
-import { useEffect } from 'react'
+import { useEffect, useEffectEvent } from 'react'
+import { toast } from 'sonner'
import { AIAssistantHeader } from './AIAssistantHeader'
import { AssistantChat } from './AssistantChat'
import { resolveSnippetSource } from '@/components/interfaces/SQLEditor/querySource'
+import {
+ ASSISTANT_HANDOFF_QUERY_PARAM,
+ buildSupportAssistantPrompt,
+ consumeAssistantHandoff,
+} from '@/components/interfaces/Support/SupportAssistant.utils'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { useAiAssistantState, useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
import type { SqlSnippet } from '@/state/ai-assistant-state'
@@ -29,7 +35,7 @@ const isSameSnippet = (snippet: SqlSnippet, currentQuery: CurrentQuerySnippet) =
export const AIAssistant = ({ className }: AIAssistantProps) => {
const router = useRouter()
- const { id: entityId, source: sourceParam } = useParams()
+ const { id: entityId, source: sourceParam, ref: routeRef } = useParams()
const snap = useAiAssistantStateSnapshot()
const state = useAiAssistantState()
const { snippets } = useSqlEditorV2StateSnapshot()
@@ -49,6 +55,71 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
? resolveSnippetSource(snippet?.snippet, sourceParam)
: undefined
+ const processAssistantHandoff = useEffectEvent((handoffToken: string) => {
+ const request = consumeAssistantHandoff(handoffToken)
+
+ // A handoff link binds its target project to `request.projectRef`. Reject (and still
+ // clean up) any handoff that ends up on a different project's page — a stale link, or
+ // one edited/replayed by hand — rather than creating a chat tagged with the wrong project.
+ if (request && request.projectRef === routeRef) {
+ const newChatId = state.newChat({
+ name: 'Support request',
+ initialMessage: buildSupportAssistantPrompt(request),
+ })
+
+ const chat = state.chats[newChatId]
+ if (chat) {
+ chat.supportMetadata = {
+ subject: request.subject,
+ category: request.category,
+ severity: request.severity,
+ organizationSlug: request.organizationSlug,
+ projectRef: request.projectRef,
+ library: request.library,
+ affectedServices: request.affectedServices,
+ allowSupportAccess: request.allowSupportAccess,
+ frontConversationId: request.frontConversationId,
+ threadRef: request.threadRef,
+ isSupportChat: true,
+ lifecycleStatus: 'bot_active',
+ lastSyncedMessageCount: 0,
+ isSyncing: false,
+ isLifecycleSyncing: false,
+ }
+
+ void import('@/state/ai-chat-front-sync')
+ .then(({ syncSupportChatToFront }) => syncSupportChatToFront(newChatId, state))
+ .catch(() => {})
+ }
+
+ state.selectChat(newChatId)
+ } else {
+ // The token didn't resolve (e.g. the link was opened in a new tab, so this tab's
+ // sessionStorage never had it) or belonged to a different project. Start a new chat
+ // rather than silently leaving whichever chat happened to be active for this project —
+ // landing on an unrelated older conversation with no indication anything went wrong
+ // is worse than an empty one.
+ state.newChat()
+ toast.error("Couldn't load your ticket context here — started a new chat instead.")
+ }
+
+ const { [ASSISTANT_HANDOFF_QUERY_PARAM]: _handledParam, ...restQuery } = router.query
+ router.replace({ pathname: router.pathname, query: restQuery }, undefined, { shallow: true })
+ })
+
+ // Picks up a support chat handed off from an org-level support page. Waits for
+ // `isInitialized` since the assistant state's IndexedDB restore overwrites
+ // `state.chats`/`activeChatId` wholesale once it resolves, which would wipe out a chat
+ // created here if this ran first.
+ useEffect(() => {
+ if (!snap.isInitialized) return
+
+ const handoffToken = router.query[ASSISTANT_HANDOFF_QUERY_PARAM]
+ if (typeof handoffToken !== 'string') return
+
+ processAssistantHandoff(handoffToken)
+ }, [snap.isInitialized, router.query[ASSISTANT_HANDOFF_QUERY_PARAM]])
+
useEffect(() => {
if (!shortcutsEnabled || !isInSQLEditor || !snippetContent) return
diff --git a/apps/studio/components/ui/AIAssistantPanel/SupportAssistantSuccessCardContent.tsx b/apps/studio/components/ui/AIAssistantPanel/SupportAssistantSuccessCardContent.tsx
index 8438a6d3f34..c01db7e5ce6 100644
--- a/apps/studio/components/ui/AIAssistantPanel/SupportAssistantSuccessCardContent.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/SupportAssistantSuccessCardContent.tsx
@@ -1,11 +1,13 @@
import type { UIMessage as MessageType } from '@ai-sdk/react'
import { ArrowUpRight } from 'lucide-react'
import dynamic from 'next/dynamic'
+import Link from 'next/link'
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
import type { JSX } from 'react'
import type { StreamdownProps } from 'streamdown'
import {
AiIconAnimation,
+ Button,
Card,
CardContent,
CardDescription,
@@ -15,10 +17,15 @@ import {
Skeleton,
} from 'ui'
-import { buildSupportAssistantPrompt } from '@/components/interfaces/Support/SupportAssistant.utils'
+import {
+ ASSISTANT_HANDOFF_QUERY_PARAM,
+ buildSupportAssistantPrompt,
+ storeAssistantHandoff,
+} from '@/components/interfaces/Support/SupportAssistant.utils'
import type { SubmittedSupportRequest } from '@/components/interfaces/Support/SupportForm.state'
import { NO_PROJECT_MARKER } from '@/components/interfaces/Support/SupportForm.utils'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useTrack } from '@/lib/telemetry/track'
import {
useAiAssistantState,
@@ -50,6 +57,11 @@ export function SupportAssistantSuccessCardContent({
className,
}: SupportAssistantSuccessCardContentProps) {
const hasAssistantContext = hasProjectScopedAssistantContext(request.projectRef)
+ const { data: currentProject } = useSelectedProjectQuery()
+ // The ticket's resolved project isn't the one in the current URL — hand off to that
+ // project's own page instead of faking assistant context in place.
+ const isProjectHandoffRequired = hasAssistantContext && currentProject?.ref !== request.projectRef
+
const aiAssistant = useAiAssistantStateSnapshot()
const aiAssistantState = useAiAssistantState()
const { openSidebar } = useSidebarManagerSnapshot()
@@ -60,8 +72,18 @@ export function SupportAssistantSuccessCardContent({
const assistantPrompt = useMemo(() => buildSupportAssistantPrompt(request), [request])
+ // An opaque token for the handoff URL — the actual ticket content never touches the URL
+ // (browser history, referrer headers, a copy-pasted link); it's stashed in sessionStorage
+ // instead, scoped to this tab and consumed (removed) the moment the destination page reads it.
+ const [handoffToken] = useState(() => crypto.randomUUID())
+
useEffect(() => {
- if (!hasAssistantContext) return
+ if (!isProjectHandoffRequired) return
+ storeAssistantHandoff(handoffToken, request)
+ }, [isProjectHandoffRequired, handoffToken, request])
+
+ useEffect(() => {
+ if (!hasAssistantContext || isProjectHandoffRequired) return
if (createdChatIdRef.current) return
const newChatId = aiAssistant.newChat({
@@ -71,7 +93,7 @@ export function SupportAssistantSuccessCardContent({
createdChatIdRef.current = newChatId
setChatId(newChatId)
- }, [aiAssistant, assistantPrompt, hasAssistantContext])
+ }, [aiAssistant, assistantPrompt, hasAssistantContext, isProjectHandoffRequired])
const handleOpenAssistant = () => {
track(
@@ -122,6 +144,45 @@ export function SupportAssistantSuccessCardContent({
if (!hasAssistantContext) return null
+ if (isProjectHandoffRequired) {
+ return (
+ <Card className={cn('bg-muted/50', className)}>
+ <CardHeader className="flex-row items-center justify-between gap-4 space-y-0">
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-background">
+ <AiIconAnimation size={14} />
+ </div>
+ <div className="min-w-0 space-y-1">
+ <CardTitle>While you wait</CardTitle>
+ <CardDescription>Continue with the Assistant in your project</CardDescription>
+ </div>
+ </div>
+ </CardHeader>
+ <CardContent>
+ <Button
+ asChild
+ variant="default"
+ size="tiny"
+ iconRight={<ArrowUpRight size={14} strokeWidth={1.5} />}
+ >
+ <Link
+ href={`/project/${request.projectRef}?sidebar=ai-assistant&${ASSISTANT_HANDOFF_QUERY_PARAM}=${handoffToken}`}
+ onClick={() =>
+ track(
+ 'support_assistant_follow_up_card_clicked',
+ { ticketCategory: request.category },
+ { project: request.projectRef, organization: request.organizationSlug }
+ )
+ }
+ >
+ Open Assistant in project
+ </Link>
+ </Button>
+ </CardContent>
+ </Card>
+ )
+ }
+
return (
<Card
role="button"