diff --git a/static/app/components/events/autofix/v3/nextStep.spec.tsx b/static/app/components/events/autofix/v3/nextStep.spec.tsx index bcd30188ff51..00591b53c1d8 100644 --- a/static/app/components/events/autofix/v3/nextStep.spec.tsx +++ b/static/app/components/events/autofix/v3/nextStep.spec.tsx @@ -129,7 +129,9 @@ describe('SeerDrawerNextStep', () => { jest .mocked(useSeerExplorerContext) .mockReturnValue({ + autoOpenSeerExplorer: jest.fn(), closeSeerExplorer: jest.fn(), + hideSidebar: jest.fn(), isOpen: false, openChatPrompt, openSeerExplorer: jest.fn(), @@ -137,6 +139,7 @@ describe('SeerDrawerNextStep', () => { sidebarContainerRef: {current: null}, setSidebarPosition: jest.fn(), sidebarAppendInitialQuery: false, + sidebarAutoFocus: true, sidebarInitialQuery: undefined, sidebarKey: 0, sidebarPosition: 'auto', diff --git a/static/app/utils/analytics/seerAnalyticsEvents.tsx b/static/app/utils/analytics/seerAnalyticsEvents.tsx index 35381933c35b..c9831a88ac6f 100644 --- a/static/app/utils/analytics/seerAnalyticsEvents.tsx +++ b/static/app/utils/analytics/seerAnalyticsEvents.tsx @@ -201,6 +201,7 @@ export type SeerAnalyticsEventsParameters = { run_id: SeerExplorerRunId | undefined; type: 'positive' | 'negative'; }; + 'seer.explorer.global_panel.auto_opened': Record; 'seer.explorer.global_panel.opened': {referrer: string; isDrawer?: boolean}; 'seer.explorer.global_panel.tool_link_navigation': { referrer: string; @@ -288,6 +289,7 @@ export const seerAnalyticsEventsMap: Record { describe('feedback slot', () => { const seerExplorerOpen: SeerExplorerContextValue = { + autoOpenSeerExplorer: jest.fn(), closeSeerExplorer: jest.fn(), + hideSidebar: jest.fn(), isOpen: true, openChatPrompt: jest.fn(), openSeerExplorer: jest.fn(), @@ -215,6 +217,7 @@ describe('TopBar', () => { sidebarContainerRef: {current: null}, setSidebarPosition: jest.fn(), sidebarAppendInitialQuery: false, + sidebarAutoFocus: true, sidebarInitialQuery: undefined, sidebarKey: 0, sidebarPosition: 'auto', diff --git a/static/app/views/performance/traceDetails/index.tsx b/static/app/views/performance/traceDetails/index.tsx index d795237ba2c9..83e1d87c0d05 100644 --- a/static/app/views/performance/traceDetails/index.tsx +++ b/static/app/views/performance/traceDetails/index.tsx @@ -16,6 +16,7 @@ import {isLogsEnabled} from 'sentry/views/explore/logs/isLogsEnabled'; import {canUseMetricsUI} from 'sentry/views/explore/metrics/metricsFlags'; import {useLLMContext} from 'sentry/views/seerExplorer/contexts/llmContext'; import {registerLLMContext} from 'sentry/views/seerExplorer/contexts/registerLLMContext'; +import {useAutoOpenSeerExplorer} from 'sentry/views/seerExplorer/hooks/useAutoOpenSeerExplorer'; import {useTrace} from './traceApi/useTrace'; import {useTraceMeta} from './traceApi/useTraceMeta'; @@ -63,6 +64,7 @@ const TRACE_VIEW_PREFERENCES_KEY = 'trace-waterfall-preferences'; export default function TraceView() { const params = useParams<{traceSlug?: string}>(); + useAutoOpenSeerExplorer(); const traceSlug = useMemo(() => decodeTraceSlug(params.traceSlug), [params.traceSlug]); const preferences = useMemo( diff --git a/static/app/views/seerExplorer/components/seerExplorerContent.tsx b/static/app/views/seerExplorer/components/seerExplorerContent.tsx index e54038b9d43b..3bbf055434c1 100644 --- a/static/app/views/seerExplorer/components/seerExplorerContent.tsx +++ b/static/app/views/seerExplorer/components/seerExplorerContent.tsx @@ -136,7 +136,9 @@ export function SeerExplorerContent({ getPageReferrer, initialQuery, appendInitialQuery, + autoFocusComposer = true, onClose, + onPopOut, renderHeader, sidebarPosition, onSidebarPositionChange, @@ -146,7 +148,14 @@ export function SeerExplorerContent({ onClose: () => void; /** Submit `initialQuery` into the open run rather than only an empty one. */ appendInitialQuery?: boolean; + /** Focus the composer on mount. Off when Seer opened without a user action. */ + autoFocusComposer?: boolean; initialQuery?: string; + /** + * Hides the current surface once its content moves to the popped-out window. + * Defaults to `onClose`. + */ + onPopOut?: () => void; onSidebarPositionChange?: (position: SeerExplorerSidebarPosition) => void; /** Surface chrome for the header. Defaults to the sidebar shell. */ renderHeader?: RenderHeader; @@ -191,7 +200,7 @@ export function SeerExplorerContent({ // happened to be left last time. preferInitialWindowPlacement: true, }) - .then(() => onClose()) + .then(() => (onPopOut ?? onClose)()) .catch(() => { // Failed to open the PiP window — keep the current surface open. }); @@ -734,13 +743,17 @@ export function SeerExplorerContent({ // - Scroll effects --------------------------------------------------------- + // Only the value at mount matters: it describes how this surface was opened. + const autoFocusOnMountRef = useRef(autoFocusComposer); useEffect(() => { // Scroll to bottom and focus input when drawer opens setTimeout(() => { if (scrollContainerRef.current) { scrollContainerRef.current.scrollTop = scrollContainerRef.current.scrollHeight; } - composerRef.current?.focus(); + if (autoFocusOnMountRef.current) { + composerRef.current?.focus(); + } }, 100); }, []); diff --git a/static/app/views/seerExplorer/components/sidebar/seerExplorerPanel.tsx b/static/app/views/seerExplorer/components/sidebar/seerExplorerPanel.tsx index e1561e4dea8d..a507405f9e23 100644 --- a/static/app/views/seerExplorer/components/sidebar/seerExplorerPanel.tsx +++ b/static/app/views/seerExplorer/components/sidebar/seerExplorerPanel.tsx @@ -12,6 +12,8 @@ export function SeerExplorerPanel() { const {getPageReferrer} = usePageReferrer(); const { closeSeerExplorer, + hideSidebar, + sidebarAutoFocus, sidebarPosition, setSidebarPosition, sidebarInitialQuery, @@ -30,7 +32,9 @@ export function SeerExplorerPanel() { getPageReferrer={getPageReferrer} initialQuery={sidebarInitialQuery} appendInitialQuery={sidebarAppendInitialQuery} + autoFocusComposer={sidebarAutoFocus} onClose={closeSeerExplorer} + onPopOut={hideSidebar} sidebarPosition={sidebarPosition} onSidebarPositionChange={setSidebarPosition} /> diff --git a/static/app/views/seerExplorer/hooks/useAutoOpenSeerExplorer.spec.tsx b/static/app/views/seerExplorer/hooks/useAutoOpenSeerExplorer.spec.tsx new file mode 100644 index 000000000000..25750e410a11 --- /dev/null +++ b/static/app/views/seerExplorer/hooks/useAutoOpenSeerExplorer.spec.tsx @@ -0,0 +1,155 @@ +import {Fragment} from 'react'; +import {OrganizationFixture} from 'sentry-fixture/organization'; + +import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary'; + +import {PictureInPictureProvider} from '@sentry/scraps/pictureInPicture'; + +import {SeerExplorerChatStateProvider} from 'sentry/views/seerExplorer/seerExplorerChatStateContext'; +import {SeerExplorerContextProvider} from 'sentry/views/seerExplorer/seerExplorerContextProvider'; +import {SeerExplorerSessionsProvider} from 'sentry/views/seerExplorer/seerExplorerSessionContext'; +import {useSeerExplorerContext} from 'sentry/views/seerExplorer/useSeerExplorerContext'; + +import {useAutoOpenSeerExplorer} from './useAutoOpenSeerExplorer'; + +function mockViewportWidth(width: number) { + window.matchMedia = jest.fn().mockImplementation((query: string) => { + const minWidth = /min-width:\s*(\d+)px/.exec(query)?.[1]; + return { + matches: minWidth === undefined ? false : width >= Number(minWidth), + media: query, + onchange: null, + addListener: jest.fn(), + removeListener: jest.fn(), + addEventListener: jest.fn(), + removeEventListener: jest.fn(), + dispatchEvent: jest.fn(), + }; + }); +} + +function SeerProviders({children}: {children?: React.ReactNode}) { + return ( + + + + {children} + + + + ); +} + +function AutoOpenPage() { + useAutoOpenSeerExplorer(); + return null; +} + +function SeerState() { + const {isOpen, hideSidebar, toggleSeerExplorer} = useSeerExplorerContext(); + return ( + + + + + ); +} + +function TestPage({showPage = true}: {showPage?: boolean}) { + return ( + + {showPage ? : null} + + + ); +} + +describe('useAutoOpenSeerExplorer', () => { + const organization = OrganizationFixture({ + openMembership: true, + hideAiFeatures: false, + features: ['seer-explorer', 'seer-explorer-auto-open'], + }); + + beforeEach(() => { + sessionStorage.clear(); + localStorage.clear(); + mockViewportWidth(1440); + MockApiClient.addMockResponse({ + url: `/organizations/${organization.slug}/seer/runs/`, + body: [], + }); + }); + + it('opens the sidebar on a wide viewport', async () => { + render(, {organization, additionalWrapper: SeerProviders}); + + expect(await screen.findByRole('button', {name: 'seer open'})).toBeInTheDocument(); + }); + + it('does not open on a narrow viewport', async () => { + mockViewportWidth(390); + render(, {organization, additionalWrapper: SeerProviders}); + + expect(await screen.findByRole('button', {name: 'seer closed'})).toBeInTheDocument(); + }); + + it('does not open without the feature flag', async () => { + render(, { + organization: OrganizationFixture({ + openMembership: true, + hideAiFeatures: false, + features: ['seer-explorer'], + }), + additionalWrapper: SeerProviders, + }); + + expect(await screen.findByRole('button', {name: 'seer closed'})).toBeInTheDocument(); + }); + + it('stays closed on later pages after the user closes it', async () => { + const {rerender} = render(, { + organization, + additionalWrapper: SeerProviders, + }); + + await userEvent.click(await screen.findByRole('button', {name: 'seer open'})); + expect(screen.getByRole('button', {name: 'seer closed'})).toBeInTheDocument(); + + // Leave the page and come back: the dismissal outlives the page. + rerender(); + rerender(); + + expect(screen.getByRole('button', {name: 'seer closed'})).toBeInTheDocument(); + }); + + it('does not count popping the panel out as a dismissal', async () => { + const {rerender} = render(, { + organization, + additionalWrapper: SeerProviders, + }); + + expect(await screen.findByRole('button', {name: 'seer open'})).toBeInTheDocument(); + await userEvent.click(screen.getByRole('button', {name: 'pop out'})); + expect(screen.getByRole('button', {name: 'seer closed'})).toBeInTheDocument(); + + rerender(); + rerender(); + + expect(await screen.findByRole('button', {name: 'seer open'})).toBeInTheDocument(); + }); + + it('clears the dismissal when the user opens the panel again', async () => { + localStorage.setItem('seer-explorer-sidebar-auto-open-dismissed', 'true'); + render(, {organization, additionalWrapper: SeerProviders}); + + await userEvent.click(await screen.findByRole('button', {name: 'seer closed'})); + + expect(screen.getByRole('button', {name: 'seer open'})).toBeInTheDocument(); + expect(localStorage.getItem('seer-explorer-sidebar-auto-open-dismissed')).toBeNull(); + }); +}); diff --git a/static/app/views/seerExplorer/hooks/useAutoOpenSeerExplorer.tsx b/static/app/views/seerExplorer/hooks/useAutoOpenSeerExplorer.tsx new file mode 100644 index 000000000000..c697d42a59c5 --- /dev/null +++ b/static/app/views/seerExplorer/hooks/useAutoOpenSeerExplorer.tsx @@ -0,0 +1,74 @@ +import {useEffect, useRef} from 'react'; +import {useTheme} from '@emotion/react'; + +import {trackAnalytics} from 'sentry/utils/analytics'; +import {localStorageWrapper} from 'sentry/utils/localStorage'; +import {useIsSeerExplorerSidebarEnabled} from 'sentry/utils/seer/isSeerExplorerEnabled'; +import {useOrganization} from 'sentry/utils/useOrganization'; +import {useSeerExplorerContext} from 'sentry/views/seerExplorer/useSeerExplorerContext'; +import {usePageRouteString} from 'sentry/views/seerExplorer/utils'; + +const AUTO_OPEN_DISMISSED_KEY = 'seer-explorer-sidebar-auto-open-dismissed'; + +/** + * Remembers whether the user last closed or opened the sidebar, so a closed + * panel stays closed on every page and tab until the user opens it again. + */ +export function setSeerExplorerAutoOpenDismissed(dismissed: boolean) { + try { + if (dismissed) { + localStorageWrapper.setItem(AUTO_OPEN_DISMISSED_KEY, 'true'); + } else { + localStorageWrapper.removeItem(AUTO_OPEN_DISMISSED_KEY); + } + } catch { + // Best effort: without storage the panel can still auto-open again. + } +} + +function isSeerExplorerAutoOpenDismissed() { + return localStorageWrapper.getItem(AUTO_OPEN_DISMISSED_KEY) === 'true'; +} + +/** + * Opens the Seer Explorer sidebar when the page mounts, for pages where Seer + * helps people get started. It only ever opens the panel, and the open state is + * shared across pages, so browsing between pages never flips it on and off. + * + * Skipped below the `lg` breakpoint, where the panel docks to the bottom or + * crowds the page, and once the user has closed the panel. + */ +export function useAutoOpenSeerExplorer() { + const organization = useOrganization(); + const isSidebarMode = useIsSeerExplorerSidebarEnabled(); + const {isOpen, autoOpenSeerExplorer} = useSeerExplorerContext(); + const routeString = usePageRouteString(); + const theme = useTheme(); + const hasAutoOpen = organization.features.includes('seer-explorer-auto-open'); + + // Decide once per page visit. Re-deciding when `isOpen` changes would reopen + // the panel right after the user closes it. + const hasDecidedRef = useRef(false); + useEffect(() => { + if (hasDecidedRef.current) { + return; + } + hasDecidedRef.current = true; + if (!hasAutoOpen || !isSidebarMode || isOpen || isSeerExplorerAutoOpenDismissed()) { + return; + } + if (!window.matchMedia?.(`(min-width: ${theme.breakpoints.lg})`).matches) { + return; + } + autoOpenSeerExplorer({referrer: routeString}); + trackAnalytics('seer.explorer.global_panel.auto_opened', {organization}); + }, [ + hasAutoOpen, + isSidebarMode, + isOpen, + autoOpenSeerExplorer, + organization, + routeString, + theme, + ]); +} diff --git a/static/app/views/seerExplorer/seerExplorerContextProvider.tsx b/static/app/views/seerExplorer/seerExplorerContextProvider.tsx index 6b297eb94944..c99d11f49890 100644 --- a/static/app/views/seerExplorer/seerExplorerContextProvider.tsx +++ b/static/app/views/seerExplorer/seerExplorerContextProvider.tsx @@ -25,6 +25,7 @@ import { } from './components/drawer/useSeerExplorerDrawer'; import {SeerExplorerContent} from './components/seerExplorerContent'; import {SeerExplorerErrorBoundary} from './components/seerExplorerErrorBoundary'; +import {setSeerExplorerAutoOpenDismissed} from './hooks/useAutoOpenSeerExplorer'; import {useSeerExplorerPolling} from './hooks/useSeerExplorerPolling'; import {serializeChatPromptContext} from './chatPrompt'; import { @@ -77,6 +78,7 @@ export function SeerExplorerContextProvider({children}: {children: ReactNode}) { undefined ); const [sidebarKey, setSidebarKey] = useState(0); + const [sidebarAutoFocus, setSidebarAutoFocus] = useState(true); const [sidebarPosition, setSidebarPositionState] = useLocalStorageState( 'seer-explorer-sidebar-position', @@ -106,14 +108,19 @@ export function SeerExplorerContextProvider({children}: {children: ReactNode}) { const {pipWindow, closePipWindow} = usePictureInPicture(); const isPoppedOut = pipWindow !== null; - const openSidebar = useCallback(() => { - setIsSidebarOpen(true); - trackAnalytics('seer.explorer.global_panel.opened', { - referrer: getPageReferrer(), - organization, - isDrawer: false, - }); - }, [getPageReferrer, organization, setIsSidebarOpen]); + const openSidebar = useCallback( + ({autoFocus = true, referrer}: {autoFocus?: boolean; referrer?: string} = {}) => { + setIsSidebarOpen(true); + setSidebarAutoFocus(autoFocus); + setSeerExplorerAutoOpenDismissed(false); + trackAnalytics('seer.explorer.global_panel.opened', { + referrer: referrer ?? getPageReferrer(), + organization, + isDrawer: false, + }); + }, + [getPageReferrer, organization, setIsSidebarOpen] + ); // Re-open the active surface (sidebar or drawer) whenever the PiP window closes // (native controls, dock button, or programmatically) — unless a full close @@ -143,6 +150,8 @@ export function SeerExplorerContextProvider({children}: {children: ReactNode}) { } isRedockingRef.current = true; if (isSidebarMode) { + // Redocking reacts to the PiP window closing, an external event. + // oxlint-disable-next-line react/set-state-in-effect openSidebar(); } else { openSeerExplorerDrawer(); @@ -229,6 +238,18 @@ export function SeerExplorerContextProvider({children}: {children: ReactNode}) { ] ); + const autoOpenSeerExplorer = useCallback( + ({referrer}: {referrer: string}) => { + if (!isSidebarMode || isSidebarOpenRef.current || pipWindow) { + return; + } + // The page's own effects run before the provider's referrer ref catches up + // with a client-side navigation, so the page passes its route explicitly. + openSidebar({autoFocus: false, referrer}); + }, + [isSidebarMode, pipWindow, openSidebar] + ); + const openChatPrompt = useCallback( ({prompt, context}: {prompt: string; context?: unknown}) => { openSeerExplorer({ @@ -250,6 +271,15 @@ export function SeerExplorerContextProvider({children}: {children: ReactNode}) { [openSeerExplorer] ); + const hideSidebar = useCallback(() => { + setIsSidebarOpen(false); + // Tie the forwarded query to a single open lifecycle so a remount on + // reopen (toggle / re-dock) doesn't auto-submit it again. + setSidebarInitialQuery(undefined); + setSidebarAppendInitialQuery(false); + setLastViewedAt(Date.now()); + }, [setIsSidebarOpen]); + const closeSeerExplorer = useCallback(() => { if (pipWindow) { suppressRedockRef.current = true; @@ -257,22 +287,12 @@ export function SeerExplorerContextProvider({children}: {children: ReactNode}) { return; } if (isSidebarMode) { - setIsSidebarOpen(false); - // Tie the forwarded query to a single open lifecycle so a remount on - // reopen (toggle / re-dock) doesn't auto-submit it again. - setSidebarInitialQuery(undefined); - setSidebarAppendInitialQuery(false); - setLastViewedAt(Date.now()); + hideSidebar(); + setSeerExplorerAutoOpenDismissed(true); return; } closeSeerExplorerDrawer(); - }, [ - pipWindow, - isSidebarMode, - closePipWindow, - setIsSidebarOpen, - closeSeerExplorerDrawer, - ]); + }, [pipWindow, isSidebarMode, closePipWindow, hideSidebar, closeSeerExplorerDrawer]); const toggleSeerExplorer = useCallback(() => { if (pipWindow) { @@ -288,6 +308,7 @@ export function SeerExplorerContextProvider({children}: {children: ReactNode}) { setSidebarInitialQuery(undefined); setSidebarAppendInitialQuery(false); setIsSidebarOpen(false); + setSeerExplorerAutoOpenDismissed(true); } else { openSidebar(); } @@ -397,14 +418,17 @@ export function SeerExplorerContextProvider({children}: {children: ReactNode}) { const contextValue = useMemo( () => ({ + autoOpenSeerExplorer, isOpen, openChatPrompt, openSeerExplorer, closeSeerExplorer, + hideSidebar, toggleSeerExplorer, sessionState, sidebarContainerRef, sidebarAppendInitialQuery, + sidebarAutoFocus, sidebarInitialQuery, sidebarKey, sidebarPosition, @@ -412,13 +436,16 @@ export function SeerExplorerContextProvider({children}: {children: ReactNode}) { unreadCount, }), [ + autoOpenSeerExplorer, isOpen, openChatPrompt, openSeerExplorer, closeSeerExplorer, + hideSidebar, toggleSeerExplorer, sessionState, sidebarAppendInitialQuery, + sidebarAutoFocus, sidebarInitialQuery, sidebarKey, sidebarPosition, diff --git a/static/app/views/seerExplorer/useSeerExplorerContext.tsx b/static/app/views/seerExplorer/useSeerExplorerContext.tsx index a9c49a20a292..1f4c8e86e8d0 100644 --- a/static/app/views/seerExplorer/useSeerExplorerContext.tsx +++ b/static/app/views/seerExplorer/useSeerExplorerContext.tsx @@ -6,7 +6,18 @@ import type {SeerExplorerSidebarPosition} from './types'; type SeerExplorerSessionState = 'inactive' | 'thinking' | 'done-thinking'; export type SeerExplorerContextValue = { + /** + * Opens the sidebar without a user action, for pages that show Seer by default. + * Leaves focus on the page, and attributes the open to `referrer`, the route of + * the page that asked. Sidebar mode only. + */ + autoOpenSeerExplorer: (options: {referrer: string}) => void; closeSeerExplorer: () => void; + /** + * Hides the sidebar while its content moves to the popped-out window. Unlike + * `closeSeerExplorer`, it doesn't count as the user closing Seer. + */ + hideSidebar: () => void; isOpen: boolean; /** * Opens Explorer on an "Ask Seer" question from Seer and sends nothing until the user @@ -25,6 +36,8 @@ export type SeerExplorerContextValue = { */ /** Whether `sidebarInitialQuery` goes into the open run. Sidebar mode only. */ sidebarAppendInitialQuery: boolean; + /** Whether the sidebar content focuses its composer when it opens. Sidebar mode only. */ + sidebarAutoFocus: boolean; /** * Ref attached by the sidebar layout to its measuring container, so the * provider can read the available size when persisting the popped-out @@ -43,7 +56,9 @@ export type SeerExplorerContextValue = { }; export const SeerExplorerContext = createContext({ + autoOpenSeerExplorer: () => {}, closeSeerExplorer: () => {}, + hideSidebar: () => {}, isOpen: false, openChatPrompt: () => {}, openSeerExplorer: () => {}, @@ -51,6 +66,7 @@ export const SeerExplorerContext = createContext({ sidebarContainerRef: {current: null}, setSidebarPosition: () => {}, sidebarAppendInitialQuery: false, + sidebarAutoFocus: true, sidebarInitialQuery: undefined, sidebarKey: 0, sidebarPosition: 'auto',