Skip to content

An AI-powered search engine with a generative UI

Show auth modal for adaptive guest access

Yoshiki Miurae35f60481685
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index cd0689ba..a9245bc0 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -7,6 +7,10 @@ import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { checkAndEnforceAdaptiveLimit } from '@/lib/rate-limit/adaptive-limit'
import { checkAndEnforceOverallChatLimit } from '@/lib/rate-limit/chat-limits'
import { checkAndEnforceGuestLimit } from '@/lib/rate-limit/guest-limit'
+import {
+ ADAPTIVE_MODE_AUTH_REQUIRED_MESSAGE,
+ isAdaptiveModeAuthBlocked
+} from '@/lib/search-mode-availability'
import { createChatStreamResponse } from '@/lib/streaming/create-chat-stream-response'
import { createEphemeralChatStreamResponse } from '@/lib/streaming/create-ephemeral-chat-stream-response'
import { SearchMode } from '@/lib/types/search'
@@ -93,6 +97,29 @@ export async function POST(req: Request) {
? (searchModeCookie as SearchMode)
: 'quick'
+ // Adaptive mode is gated to authenticated users on cloud deployments.
+ // Check before model/provider selection so guests always get the
+ // intentional auth payload instead of lower-level configuration errors.
+ if (
+ isAdaptiveModeAuthBlocked({
+ mode: searchMode,
+ isGuest,
+ isCloudDeployment: process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
+ })
+ ) {
+ return new Response(
+ JSON.stringify({
+ error: ADAPTIVE_MODE_AUTH_REQUIRED_MESSAGE,
+ mode: 'adaptive',
+ authRequired: true
+ }),
+ {
+ status: 401,
+ headers: { 'Content-Type': 'application/json' }
+ }
+ )
+ }
+
const selectedModel = await selectModel({ searchMode, cookieStore })
if (!selectedModel) {
@@ -112,27 +139,6 @@ export async function POST(req: Request) {
)
}
- // Adaptive mode is gated to authenticated users on cloud deployments.
- // Guests are nudged to sign in instead of being downgraded silently.
- if (
- isGuest &&
- searchMode === 'adaptive' &&
- process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
- ) {
- return new Response(
- JSON.stringify({
- error:
- 'Sign in to use Adaptive mode. Quick mode remains available without an account.',
- mode: 'adaptive',
- authRequired: true
- }),
- {
- status: 401,
- headers: { 'Content-Type': 'application/json' }
- }
- )
- }
-
if (!isGuest) {
const overallLimitResponse = await checkAndEnforceOverallChatLimit(userId)
if (overallLimitResponse) return overallLimitResponse
diff --git a/components/__tests__/chat-panel.test.tsx b/components/__tests__/chat-panel.test.tsx
new file mode 100644
index 00000000..cfd3c239
--- /dev/null
+++ b/components/__tests__/chat-panel.test.tsx
@@ -0,0 +1,89 @@
+import React from 'react'
+
+import { render, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, test, vi } from 'vitest'
+
+import { deleteCookie, getCookie, setCookie } from '@/lib/utils/cookies'
+
+import { ChatPanel } from '../chat-panel'
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: vi.fn() })
+}))
+
+vi.mock('../artifact/artifact-context', () => ({
+ useArtifact: () => ({ close: vi.fn() })
+}))
+
+vi.mock('../action-buttons', () => ({
+ ActionButtons: () => null
+}))
+
+vi.mock('../file-upload-button', () => ({
+ FileUploadButton: () => null
+}))
+
+vi.mock('../message-navigation-dots', () => ({
+ MessageNavigationDots: () => null
+}))
+
+vi.mock('../model-selector-client', () => ({
+ ModelSelectorClient: () => null
+}))
+
+vi.mock('../uploaded-file-list', () => ({
+ UploadedFileList: () => null
+}))
+
+vi.mock('../ui/icons', () => ({
+ IconBlinkingLogo: () => <div data-testid="logo" />,
+ IconLogoOutline: ({ className }: { className?: string }) => (
+ <span className={className} data-testid="adaptive-icon" />
+ )
+}))
+
+describe('ChatPanel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ deleteCookie('searchMode')
+ })
+
+ test('preserves and submits the initial query after resetting a stale adaptive cookie', async () => {
+ const append = vi.fn()
+ const onAdaptiveModeAuthRequired = vi.fn()
+ setCookie('searchMode', 'adaptive')
+
+ render(
+ <ChatPanel
+ chatId="chat-1"
+ input=""
+ handleInputChange={vi.fn()}
+ handleSubmit={vi.fn()}
+ status="ready"
+ messages={[]}
+ setMessages={vi.fn()}
+ query="latest news"
+ stop={vi.fn()}
+ append={append}
+ showScrollToBottomButton={false}
+ scrollContainerRef={React.createRef<HTMLDivElement>()}
+ uploadedFiles={[]}
+ setUploadedFiles={vi.fn()}
+ isGuest
+ isCloudDeployment
+ onAdaptiveModeAuthRequired={onAdaptiveModeAuthRequired}
+ />
+ )
+
+ await waitFor(() => {
+ expect(getCookie('searchMode')).toBe('quick')
+ })
+ await waitFor(() => {
+ expect(append).toHaveBeenCalledWith({
+ role: 'user',
+ content: 'latest news'
+ })
+ })
+ expect(onAdaptiveModeAuthRequired).not.toHaveBeenCalled()
+ })
+})
diff --git a/components/__tests__/search-mode-selector.test.tsx b/components/__tests__/search-mode-selector.test.tsx
new file mode 100644
index 00000000..704a3420
--- /dev/null
+++ b/components/__tests__/search-mode-selector.test.tsx
@@ -0,0 +1,55 @@
+import React from 'react'
+
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, test, vi } from 'vitest'
+
+import { deleteCookie, getCookie, setCookie } from '@/lib/utils/cookies'
+
+import { SearchModeSelector } from '../search-mode-selector'
+
+describe('SearchModeSelector', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ deleteCookie('searchMode')
+ })
+
+ test('blocks adaptive selection when auth is required', () => {
+ const onAdaptiveAuthRequired = vi.fn()
+ setCookie('searchMode', 'quick')
+
+ render(
+ <SearchModeSelector
+ isAdaptiveAuthRequired
+ onAdaptiveAuthRequired={onAdaptiveAuthRequired}
+ />
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: /adaptive mode/i }))
+
+ expect(onAdaptiveAuthRequired).toHaveBeenCalledTimes(1)
+ expect(getCookie('searchMode')).toBe('quick')
+ })
+
+ test('allows adaptive selection when auth is not required', () => {
+ const onAdaptiveAuthRequired = vi.fn()
+
+ render(
+ <SearchModeSelector onAdaptiveAuthRequired={onAdaptiveAuthRequired} />
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: /adaptive mode/i }))
+
+ expect(onAdaptiveAuthRequired).not.toHaveBeenCalled()
+ expect(getCookie('searchMode')).toBe('adaptive')
+ })
+
+ test('resets a stale adaptive cookie when auth is required', async () => {
+ setCookie('searchMode', 'adaptive')
+
+ render(<SearchModeSelector isAdaptiveAuthRequired />)
+
+ await waitFor(() => {
+ expect(getCookie('searchMode')).toBe('quick')
+ })
+ })
+})
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index ca0b789b..739f578f 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -1,6 +1,12 @@
'use client'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ useSyncExternalStore
+} from 'react'
import Textarea from 'react-textarea-autosize'
import { useRouter } from 'next/navigation'
@@ -9,10 +15,20 @@ import { ArrowUp, ChevronDown, MessageCirclePlus, Square } from 'lucide-react'
import { toast } from 'sonner'
import { SHORTCUT_EVENTS } from '@/lib/keyboard-shortcuts'
+import {
+ isAdaptiveModeAuthBlocked,
+ requiresAdaptiveModeAuth
+} from '@/lib/search-mode-availability'
import { UploadedFile } from '@/lib/types'
import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'
import type { ModelSelectorData } from '@/lib/types/model-selector'
+import type { SearchMode } from '@/lib/types/search'
import { cn } from '@/lib/utils'
+import {
+ getCookie,
+ setCookie,
+ subscribeToCookieChange
+} from '@/lib/utils/cookies'
import { useArtifact } from './artifact/artifact-context'
import { Button } from './ui/button'
@@ -27,6 +43,10 @@ import { UploadedFileList } from './uploaded-file-list'
// Constants for timing delays
const INPUT_UPDATE_DELAY_MS = 10 // Delay to ensure input value is updated before form submission
+function getSearchModeSnapshot(): SearchMode {
+ return getCookie('searchMode') === 'adaptive' ? 'adaptive' : 'quick'
+}
+
interface ChatPanelProps {
chatId: string
input: string
@@ -50,6 +70,7 @@ interface ChatPanelProps {
isGuest?: boolean
/** Whether the deployment is cloud mode */
isCloudDeployment?: boolean
+ onAdaptiveModeAuthRequired?: () => void
modelSelectorData?: ModelSelectorData
/** Chat sections for message navigation dots */
sections?: { id: string; userMessage: UIMessage }[]
@@ -73,6 +94,7 @@ export function ChatPanel({
onNewChat,
isGuest = false,
isCloudDeployment = false,
+ onAdaptiveModeAuthRequired,
modelSelectorData,
sections = []
}: ChatPanelProps) {
@@ -86,6 +108,20 @@ export function ChatPanel({
const isLoading = status === 'submitted' || status === 'streaming'
const hasAvailableModels =
isCloudDeployment || modelSelectorData?.hasAvailableModels !== false
+ const searchMode = useSyncExternalStore(
+ subscribeToCookieChange,
+ getSearchModeSnapshot,
+ () => 'quick' as SearchMode
+ )
+ const isAdaptiveAuthRequired = requiresAdaptiveModeAuth({
+ isGuest,
+ isCloudDeployment
+ })
+ const adaptiveModeSubmitBlocked = isAdaptiveModeAuthBlocked({
+ mode: searchMode,
+ isGuest,
+ isCloudDeployment
+ })
const handleCompositionStart = () => setIsComposing(true)
@@ -154,14 +190,18 @@ export function ChatPanel({
// if query is not empty, submit the query
useEffect(() => {
if (isFirstRender.current && query && query.trim().length > 0) {
+ if (adaptiveModeSubmitBlocked) {
+ setCookie('searchMode', 'quick')
+ return
+ }
+
append({
role: 'user',
content: query
})
isFirstRender.current = false
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [query])
+ }, [adaptiveModeSubmitBlocked, append, query])
const handleFileRemove = useCallback(
(index: number) => {
@@ -202,6 +242,12 @@ export function ChatPanel({
)}
<form
onSubmit={e => {
+ if (adaptiveModeSubmitBlocked) {
+ e.preventDefault()
+ onAdaptiveModeAuthRequired?.()
+ return
+ }
+
if (!hasAvailableModels) {
e.preventDefault()
toast.error('No enabled model is available')
@@ -372,7 +418,10 @@ export function ChatPanel({
}}
/>
)}
- <SearchModeSelector />
+ <SearchModeSelector
+ isAdaptiveAuthRequired={isAdaptiveAuthRequired}
+ onAdaptiveAuthRequired={onAdaptiveModeAuthRequired}
+ />
</div>
<div className="flex items-center gap-2">
{!isCloudDeployment && modelSelectorData && (
diff --git a/components/chat.tsx b/components/chat.tsx
index afdabf6e..498ccbd7 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -15,6 +15,10 @@ import {
} from '@/lib/errors/public-error'
import { SHORTCUT_EVENTS } from '@/lib/keyboard-shortcuts'
import { stripSpecBlocks } from '@/lib/render/strip-spec-blocks'
+import {
+ ADAPTIVE_MODE_AUTH_REQUIRED_MESSAGE,
+ isAdaptiveModeAuthBlocked
+} from '@/lib/search-mode-availability'
import { UploadedFile } from '@/lib/types'
import type { UIMessage } from '@/lib/types/ai'
import {
@@ -24,6 +28,7 @@ import {
} from '@/lib/types/dynamic-tools'
import type { ModelSelectorData } from '@/lib/types/model-selector'
import { cn } from '@/lib/utils'
+import { getCookie } from '@/lib/utils/cookies'
import { useFileDropzone } from '@/hooks/use-file-dropzone'
@@ -97,6 +102,23 @@ export function Chat({
// its `handlers` prop via useState(initialHandlers)) can still see
// the freshest value through `.current`. See lib/contexts/chat-context.tsx.
const isStreamingRef = useRef(false)
+ const showAdaptiveModeAuthModal = useCallback(() => {
+ setErrorModal({
+ open: true,
+ type: 'auth',
+ message: ADAPTIVE_MODE_AUTH_REQUIRED_MESSAGE
+ })
+ }, [setErrorModal])
+
+ const isCurrentAdaptiveModeAuthBlocked = useCallback(
+ () =>
+ isAdaptiveModeAuthBlocked({
+ mode: getCookie('searchMode') === 'adaptive' ? 'adaptive' : 'quick',
+ isGuest,
+ isCloudDeployment
+ }),
+ [isGuest, isCloudDeployment]
+ )
const {
messages,
@@ -180,6 +202,11 @@ export function Chat({
// action handlers can reliably reject overlapping sends.
const safeSendMessage = useCallback<typeof sendMessage>(
(...args) => {
+ if (isCurrentAdaptiveModeAuthBlocked()) {
+ showAdaptiveModeAuthModal()
+ return Promise.resolve()
+ }
+
isStreamingRef.current = true
try {
return sendMessage(...args)
@@ -188,11 +215,16 @@ export function Chat({
throw error
}
},
- [sendMessage]
+ [sendMessage, isCurrentAdaptiveModeAuthBlocked, showAdaptiveModeAuthModal]
)
const safeRegenerate = useCallback(
async (...args: Parameters<typeof regenerate>) => {
+ if (isCurrentAdaptiveModeAuthBlocked()) {
+ showAdaptiveModeAuthModal()
+ return
+ }
+
isStreamingRef.current = true
try {
return await regenerate(...args)
@@ -201,7 +233,7 @@ export function Chat({
throw error
}
},
- [regenerate]
+ [regenerate, isCurrentAdaptiveModeAuthBlocked, showAdaptiveModeAuthModal]
)
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
@@ -541,6 +573,7 @@ export function Chat({
onNewChat={handleNewChat}
isGuest={isGuest}
isCloudDeployment={isCloudDeployment}
+ onAdaptiveModeAuthRequired={showAdaptiveModeAuthModal}
modelSelectorData={modelSelectorData}
sections={sections}
/>
diff --git a/components/search-mode-selector.tsx b/components/search-mode-selector.tsx
index 6d85e48e..24b8996e 100644
--- a/components/search-mode-selector.tsx
+++ b/components/search-mode-selector.tsx
@@ -22,13 +22,25 @@ import {
} from './ui/dropdown-menu'
import { HoverCard, HoverCardContent, HoverCardTrigger } from './ui/hover-card'
-export function SearchModeSelector() {
+const VALID_SEARCH_MODES = new Set(['quick', 'adaptive'])
+
+function getSearchModeSnapshot(): SearchMode {
+ const savedMode = getCookie('searchMode')
+ return savedMode === 'adaptive' ? 'adaptive' : 'quick'
+}
+
+interface SearchModeSelectorProps {
+ isAdaptiveAuthRequired?: boolean
+ onAdaptiveAuthRequired?: () => void
+}
+
+export function SearchModeSelector({
+ isAdaptiveAuthRequired = false,
+ onAdaptiveAuthRequired
+}: SearchModeSelectorProps) {
const value = useSyncExternalStore(
subscribeToCookieChange,
- () => {
- const savedMode = getCookie('searchMode')
- return savedMode === 'adaptive' ? 'adaptive' : 'quick'
- },
+ getSearchModeSnapshot,
() => 'quick'
)
const [openHoverCard, setOpenHoverCard] = useState<string | null>(null)
@@ -37,14 +49,18 @@ export function SearchModeSelector() {
useEffect(() => {
const savedMode = getCookie('searchMode')
- if (savedMode && !['quick', 'adaptive'].includes(savedMode)) {
+ if (savedMode && !VALID_SEARCH_MODES.has(savedMode)) {
// Clean up invalid cookie value (e.g., old 'planning' mode)
setCookie('searchMode', 'quick')
+ return
}
- }, [])
- const handleModeSelect = (mode: SearchMode) => {
- setCookie('searchMode', mode)
+ if (isAdaptiveAuthRequired && savedMode === 'adaptive') {
+ setCookie('searchMode', 'quick')
+ }
+ }, [isAdaptiveAuthRequired])
+
+ const closeModeSelectControls = () => {
setOpenHoverCard(null) // Close hover card on selection
setDropdownOpen(false) // Close dropdown on selection
setJustSelected(true)
@@ -55,6 +71,18 @@ export function SearchModeSelector() {
}, 500)
}
+ const handleModeSelect = (mode: SearchMode) => {
+ if (mode === 'adaptive' && isAdaptiveAuthRequired) {
+ setCookie('searchMode', 'quick')
+ closeModeSelectControls()
+ onAdaptiveAuthRequired?.()
+ return
+ }
+
+ setCookie('searchMode', mode)
+ closeModeSelectControls()
+ }
+
const selectedMode = SEARCH_MODE_CONFIGS.find(
config => config.value === value
)
diff --git a/lib/__tests__/search-mode-availability.test.ts b/lib/__tests__/search-mode-availability.test.ts
new file mode 100644
index 00000000..84d0d8a7
--- /dev/null
+++ b/lib/__tests__/search-mode-availability.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ ADAPTIVE_MODE_AUTH_REQUIRED_MESSAGE,
+ isAdaptiveModeAuthBlocked,
+ requiresAdaptiveModeAuth
+} from '@/lib/search-mode-availability'
+
+describe('search mode availability', () => {
+ it('requires auth for adaptive mode only for cloud guests', () => {
+ expect(
+ requiresAdaptiveModeAuth({
+ isGuest: true,
+ isCloudDeployment: true
+ })
+ ).toBe(true)
+ expect(
+ requiresAdaptiveModeAuth({
+ isGuest: false,
+ isCloudDeployment: true
+ })
+ ).toBe(false)
+ expect(
+ requiresAdaptiveModeAuth({
+ isGuest: true,
+ isCloudDeployment: false
+ })
+ ).toBe(false)
+ })
+
+ it('blocks adaptive mode sends for cloud guests', () => {
+ expect(
+ isAdaptiveModeAuthBlocked({
+ mode: 'adaptive',
+ isGuest: true,
+ isCloudDeployment: true
+ })
+ ).toBe(true)
+ expect(
+ isAdaptiveModeAuthBlocked({
+ mode: 'quick',
+ isGuest: true,
+ isCloudDeployment: true
+ })
+ ).toBe(false)
+ })
+
+ it('uses the intentional auth message', () => {
+ expect(ADAPTIVE_MODE_AUTH_REQUIRED_MESSAGE).toContain(
+ 'Sign in to use Adaptive mode'
+ )
+ })
+})
diff --git a/lib/errors/__tests__/public-error.test.ts b/lib/errors/__tests__/public-error.test.ts
index b86d3269..f5c3a39c 100644
--- a/lib/errors/__tests__/public-error.test.ts
+++ b/lib/errors/__tests__/public-error.test.ts
@@ -87,6 +87,25 @@ describe('public error mapping', () => {
)
})
+ it('maps guest limit payloads to the auth modal path', () => {
+ const payload = toPublicErrorPayload(
+ JSON.stringify({
+ error: 'Please sign in to continue.',
+ authRequired: true,
+ remaining: 0,
+ resetAt: 1767139200000,
+ limit: 10
+ })
+ )
+
+ expect(payload.type).toBe('auth')
+ expect(payload.code).toBe('auth_required')
+ expect(payload.authRequired).toBe(true)
+ expect(payload.error).toBe('Please sign in to continue.')
+ expect(payload.remaining).toBe(0)
+ expect(payload.limit).toBe(10)
+ })
+
it('does not preserve raw text just because a parsed payload has a known code', () => {
const payload = toPublicErrorPayload(
JSON.stringify({
diff --git a/lib/rate-limit/__tests__/guest-limit.test.ts b/lib/rate-limit/__tests__/guest-limit.test.ts
index a1616d94..980031de 100644
--- a/lib/rate-limit/__tests__/guest-limit.test.ts
+++ b/lib/rate-limit/__tests__/guest-limit.test.ts
@@ -36,6 +36,7 @@ describe('checkAndEnforceGuestLimit', () => {
expect(response?.status).toBe(401)
const body = await response!.json()
expect(body.error).toBe('Please sign in to continue.')
+ expect(body.authRequired).toBe(true)
expect(body.limit).toBe(10)
})
diff --git a/lib/rate-limit/guest-limit.ts b/lib/rate-limit/guest-limit.ts
index 3024a308..dbfb7212 100644
--- a/lib/rate-limit/guest-limit.ts
+++ b/lib/rate-limit/guest-limit.ts
@@ -88,6 +88,7 @@ export async function checkAndEnforceGuestLimit(
return new Response(
JSON.stringify({
error: 'Please sign in to continue.',
+ authRequired: true,
remaining: 0,
resetAt: result.resetAt,
limit: result.limit
diff --git a/lib/search-mode-availability.ts b/lib/search-mode-availability.ts
new file mode 100644
index 00000000..c798f631
--- /dev/null
+++ b/lib/search-mode-availability.ts
@@ -0,0 +1,29 @@
+import type { SearchMode } from '@/lib/types/search'
+
+export const ADAPTIVE_MODE_AUTH_REQUIRED_MESSAGE =
+ 'Sign in to use Adaptive mode. Quick mode remains available without an account.'
+
+export function requiresAdaptiveModeAuth({
+ isGuest,
+ isCloudDeployment
+}: {
+ isGuest?: boolean
+ isCloudDeployment?: boolean
+}) {
+ return Boolean(isGuest && isCloudDeployment)
+}
+
+export function isAdaptiveModeAuthBlocked({
+ mode,
+ isGuest,
+ isCloudDeployment
+}: {
+ mode: SearchMode
+ isGuest?: boolean
+ isCloudDeployment?: boolean
+}) {
+ return (
+ mode === 'adaptive' &&
+ requiresAdaptiveModeAuth({ isGuest, isCloudDeployment })
+ )
+}