Files
supabase/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
Alaister YoungandAlaister Young c59821fde6 [FE-5109] (part 2) refactor(studio): migrate shared UI components off next/router (#54054)
Part 2 of a 6-PR stack migrating all `next/router` and
`next/compat/router` imports in `apps/studio` onto TanStack Router hooks
and removing the router shims.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`,
`data/prefetchers/**` |
| **2** | **#54054 ← this PR** | **`components/ui/**`** |
| 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` |
| 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer,
SQL Editor, Storage, Table Editor |
| 5 | #54057 | Remaining `components/interfaces/**` and
`QueryInsightsTable` router events |
| 6 | #54058 | Remove `next/router` & `next/compat/router` shims,
`_router-events.ts`, Vite aliases, and test mocks |

Migrates all 15 `apps/studio/components/ui/**` files off `next/router`.

**Changed:**

- Replaced `useRouter` across `AIAssistantPanel` (`AIAssistant`,
`ModelSelector`), `Charts/ComposedChartHandler`, `EditorPanel`,
`ErrorBoundary` (`ClientSideExceptionHandler`,
`GlobalErrorBoundaryState`, `InsertBeforeRemoveChildErrorHandler`),
`GlobalShortcuts/ShortcutsReferenceSheet`, `HelpPanel`
(`HelpOptionsList`, `HelpPanel`), `ProductMenu/ProductMenuShortcuts`,
`QueryBlock/EditQueryButton`, and `ResourceExhaustionWarningBanner` with
TanStack's `useNavigate`, `useLocation`, `useRoutePattern`, and
`useParams` from `common`
- Updated `AIAssistant.test.tsx`, `HelpOptionsList.test.tsx`, and
`ProductMenuShortcuts.test.tsx` to use TanStack Router instead of
`next/router` mocks

**Simplified:**

- `EditQueryButton` and `ShortcutsReferenceSheet` match against
`useRoutePattern()` instead of the real pathname, as `router.pathname`
did before. A ref or slug containing `sql` or `advisors` no longer
misfires.
- Removed the unused `restrictToRoutes` field from
`ResourceExhaustionWarningBanner` (no warning sets it)
- `AIAssistant` clears the handoff param with `navigate({ to: '.' })`,
dropping a pathname subscription and an `AnyRouter` cast
- `ProductMenuShortcuts` inlines its handler (`useShortcut` always calls
the latest callback)
- Moved the `AdvisorsNavigationShortcuts.test.tsx` fix into this PR so
it passes on its own
- Tests use the shared `createTestRouter` and `customRender` router

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [ ] AI Assistant panel links, model selector navigation, and "Edit in
SQL Editor" (`EditQueryButton`) navigate cleanly
- [ ] Keyboard shortcuts in `ProductMenuShortcuts` and the shortcuts
reference sheet (`?`) match the active section and navigate as expected
- [ ] Error boundary recovery ("Reload page" / navigation actions) and
Help panel links still work
- [ ] Resource exhaustion warning banner matches project routes as
before

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-30 14:49:15 +08:00

191 lines
7.2 KiB
TypeScript

import type { UIMessage as MessageType } from '@ai-sdk/react'
import { useLocation, useNavigate } from '@tanstack/react-router'
import { useParams } from 'common/hooks'
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 { useRoutePattern } from '@/hooks/misc/useRoutePattern'
import type { SearchRecord } from '@/lib/router-search-params'
import { useAiAssistantState, useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
import type { SqlSnippet } from '@/state/ai-assistant-state'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
interface AIAssistantProps {
initialMessages?: MessageType[] | undefined
className?: string
}
type CurrentQuerySnippet = Exclude<SqlSnippet, string>
const isSameSnippet = (snippet: SqlSnippet, currentQuery: CurrentQuerySnippet) =>
typeof snippet !== 'string' &&
snippet.label === currentQuery.label &&
snippet.content === currentQuery.content &&
snippet.source === currentQuery.source
export const AIAssistant = ({ className }: AIAssistantProps) => {
const navigate = useNavigate()
const routePattern = useRoutePattern()
const handoffToken = useLocation({
select: (location) => (location.search as SearchRecord)[ASSISTANT_HANDOFF_QUERY_PARAM],
})
const { id: entityId, source: sourceParam, ref: routeRef } = useParams()
const snap = useAiAssistantStateSnapshot()
const state = useAiAssistantState()
const { snippets } = useSqlEditorV2StateSnapshot()
const { activeSidebar, closeSidebar } = useSidebarManagerSnapshot()
const shortcutsEnabled = activeSidebar?.id === SIDEBAR_KEYS.AI_ASSISTANT
const handleNewChat = () => state.newChat()
useShortcut(SHORTCUT_IDS.AI_ASSISTANT_NEW_CHAT, handleNewChat, {
enabled: shortcutsEnabled,
})
const isInSQLEditor = routePattern.includes('/sql/$id')
const snippet = snippets[entityId ?? '']
const snippetContent = snippet?.snippet?.content?.unchecked_sql
const openSnippetSource = isInSQLEditor
? 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.")
}
void navigate({
to: '.',
search: (prev: Record<string, unknown>) => {
const { [ASSISTANT_HANDOFF_QUERY_PARAM]: _handledParam, ...restSearch } = prev
return restSearch
},
replace: 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
if (typeof handoffToken !== 'string') return
processAssistantHandoff(handoffToken)
}, [snap.isInitialized, handoffToken])
useEffect(() => {
if (!shortcutsEnabled || !isInSQLEditor || !snippetContent) return
const currentQuery = {
label: 'Current Query',
content: snippetContent,
source: openSnippetSource,
}
state.setSqlSnippets([currentQuery])
return () => {
const currentSnippets = state.sqlSnippets
const remainingSnippets = currentSnippets?.filter(
(snippet) => !isSameSnippet(snippet, currentQuery)
)
if (currentSnippets && remainingSnippets?.length !== currentSnippets.length) {
state.setSqlSnippets(remainingSnippets ?? [])
}
}
}, [shortcutsEnabled, isInSQLEditor, snippetContent, openSnippetSource, state])
if (!snap.activeChatId) return null
return (
<AssistantChat
chatId={snap.activeChatId}
className={className}
shortcutsEnabled={shortcutsEnabled}
onNewChat={handleNewChat}
onSelectChat={(chatId) => state.selectChat(chatId)}
onBranchChat={(messageId) => state.branchChat(messageId)}
composerContext={{
initialInput: snap.initialInput,
sqlSnippets: snap.sqlSnippets as SqlSnippet[] | undefined,
suggestions: snap.suggestions
? {
title: snap.suggestions.title,
prompts: snap.suggestions.prompts?.map((prompt) => ({ ...prompt })),
}
: undefined,
onSetSqlSnippets: state.setSqlSnippets,
onClearSqlSnippets: state.clearSqlSnippets,
}}
renderHeader={(props) => (
<AIAssistantHeader
{...props}
shortcutsEnabled={shortcutsEnabled}
onNewChat={handleNewChat}
onCloseAssistant={() => closeSidebar(SIDEBAR_KEYS.AI_ASSISTANT)}
/>
)}
/>
)
}
export { SupportAssistantSuccessCardContent } from './SupportAssistantSuccessCardContent'