An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Revert "Gate related questions behind related_questions_enabled flag (#906)" (#915)
Yoshiki Miura5d0a7538b854
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex d36d99f2..a52fb041 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -5,7 +5,6 @@ import { loadChat } from '@/lib/actions/chat'import {calculateConversationTurn,deriveQueryShape,- getServerFeatureFlag,trackChatEvent} from '@/lib/analytics'import { getCurrentUserId } from '@/lib/auth/get-current-user'@@ -162,26 +161,6 @@ export async function POST(req: Request) {}}- // Distinct id used for BOTH flag evaluation and analytics attribution, so- // the stamped relatedFlag matches the arm the user was actually bucketed to.- const analyticsDistinctId =- userId ?? (typeof analyticsId === 'string' ? analyticsId : undefined)-- // related_questions_enabled flag. Prefer the client-evaluated value (no- // round-trip); fall back to server evaluation against the same distinct id- // when the client couldn't resolve flags in time (cold-start / auto-submit),- // so first-message sessions aren't misattributed to the on arm. On by default.- const clientRelated = body.relatedEnabled- const relatedEnabled =- typeof clientRelated === 'boolean'- ? clientRelated- : ((analyticsDistinctId- ? await getServerFeatureFlag(- 'related_questions_enabled',- analyticsDistinctId- )- : undefined) ?? true)-const streamStart = performance.now()perfLog(`createChatStreamResponse - Start: model=${selectedModel.providerId}:${selectedModel.id}, searchMode=${searchMode}`@@ -193,8 +172,7 @@ export async function POST(req: Request) {model: selectedModel,abortSignal,searchMode,- chatId,- relatedEnabled+ chatId}): await createChatStreamResponse({message,@@ -205,8 +183,7 @@ export async function POST(req: Request) {messageId,abortSignal,isNewChat,- searchMode,- relatedEnabled+ searchMode})perfTime('createChatStreamResponse resolved', streamStart)@@ -217,7 +194,8 @@ export async function POST(req: Request) {try {// Attribute to the authenticated user id, or the client-provided// PostHog distinct id for guests (so it merges with their client events).- const distinctId = analyticsDistinctId+ const distinctId =+ userId ?? (typeof analyticsId === 'string' ? analyticsId : undefined)if (!distinctId) returnlet conversationTurn = 1 // Default for new chats@@ -254,7 +232,6 @@ export async function POST(req: Request) {userId: userId ?? undefined,providerId: selectedModel.providerId,modelId: selectedModel.id,- relatedFlag: relatedEnabled,queryShape})} catch (error) {diff --git a/components/chat.tsx b/components/chat.tsxindex c23530de..fe5722b2 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -8,11 +8,7 @@ import { DefaultChatTransport } from 'ai'import { toast } from 'sonner'import { summarizeGenui } from '@/lib/analytics/genui-summary'-import {- captureClient,- getDistinctId,- isRelatedQuestionsEnabled-} from '@/lib/analytics/posthog-client'+import { captureClient, getDistinctId } from '@/lib/analytics/posthog-client'import { ChatProvider } from '@/lib/contexts/chat-context'import { generateId } from '@/lib/db/schema'import {@@ -154,17 +150,12 @@ export function Chat({? messages.find(m => m.id === messageId): undefined- // Omit when flags aren't loaded yet so the server resolves the flag- // against the same distinct id (avoids on-arm bias on cold-start sends).- const relatedEnabled = isRelatedQuestionsEnabled()-return {body: {trigger, // Use AI SDK's default trigger value directlychatId: chatId,messageId,analyticsId: getDistinctId(),- ...(relatedEnabled === undefined ? {} : { relatedEnabled }),...(isGuest ? { messages } : {}),message:trigger === 'regenerate-message' &&diff --git a/lib/agents/prompts/search-mode-prompts.ts b/lib/agents/prompts/search-mode-prompts.tsindex fe7d204a..8cbdea86 100644--- a/lib/agents/prompts/search-mode-prompts.ts+++ b/lib/agents/prompts/search-mode-prompts.ts@@ -19,7 +19,7 @@ function getSourceDirectionGuidance(): string {- Fallback: if a domain-restricted search returns too few or no results, run one more search without the restriction before answering.`}-export function getQuickModePrompt(relatedEnabled = true): string {+export function getQuickModePrompt(): string {const hasGeneralProvider = isGeneralSearchProviderAvailable()return `@@ -156,11 +156,11 @@ End with a synthesizing conclusion that ties the main points together into a cle${getImageSpecPrompt()}-${relatedEnabled ? getRelatedQuestionsSpecPrompt() : ''}+${getRelatedQuestionsSpecPrompt()}`}-function getApproachStrategy(relatedEnabled = true): string {+function getApproachStrategy(): string {return `APPROACH STRATEGY:1. **FIRST STEP - Assess query complexity:**- Most queries: Direct search and respond. Do NOT use todoWrite.@@ -206,7 +206,7 @@ Rule precedence:7. Provide comprehensive and detailed responses based on search results, ensuring thorough coverage of the user's question`}-export function getAdaptiveModePrompt(relatedEnabled = true): string {+export function getAdaptiveModePrompt(): string {return `Instructions:@@ -228,7 +228,7 @@ You are a helpful AI assistant with access to real-time web search, content retrLanguage:- ALWAYS respond in the user's language.-${getApproachStrategy(relatedEnabled)}+${getApproachStrategy()}TOOL USAGE GUIDELINES:@@ -332,7 +332,7 @@ Conclude with a brief synthesis that ties together the main insights into a clea${getImageSpecPrompt()}-${relatedEnabled ? getRelatedQuestionsSpecPrompt() : ''}+${getRelatedQuestionsSpecPrompt()}`}diff --git a/lib/agents/researcher.ts b/lib/agents/researcher.tsindex cb9ffb80..4115814e 100644--- a/lib/agents/researcher.ts+++ b/lib/agents/researcher.ts@@ -13,7 +13,7 @@ import { isTracingEnabled } from '../utils/telemetry'import {getAdaptiveModePrompt,- getQuickModePrompt+ QUICK_MODE_PROMPT} from './prompts/search-mode-prompts'// Enhanced wrapper function with better type safety and streaming support@@ -71,14 +71,12 @@ export function createResearcher({model,modelConfig,parentTraceId,- searchMode = 'adaptive',- relatedEnabled = true+ searchMode = 'adaptive'}: {model: stringmodelConfig?: ModelparentTraceId?: stringsearchMode?: SearchMode- relatedEnabled?: boolean}) {try {const currentDate = new Date().toLocaleString()@@ -99,7 +97,7 @@ export function createResearcher({console.log('[Researcher] Quick mode: maxSteps=20, tools=[search, fetch]')- systemPrompt = getQuickModePrompt(relatedEnabled)+ systemPrompt = QUICK_MODE_PROMPTactiveToolsList = ['search', 'fetch']maxSteps = 20searchTool = wrapSearchToolForQuickMode(originalSearchTool)@@ -107,7 +105,7 @@ export function createResearcher({case 'adaptive':default:- systemPrompt = getAdaptiveModePrompt(relatedEnabled)+ systemPrompt = getAdaptiveModePrompt()activeToolsList = ['search', 'fetch', 'todoWrite']console.log(`[Researcher] Adaptive mode: maxSteps=50, tools=[${activeToolsList.join(', ')}]`diff --git a/lib/analytics/dispatch.ts b/lib/analytics/dispatch.tsindex 58acc6ad..e5ff7539 100644--- a/lib/analytics/dispatch.ts+++ b/lib/analytics/dispatch.ts@@ -1,7 +1,6 @@import {captureServerEvent,deletePerson,- getServerFeatureFlag as getServerFeatureFlagProvider,type ServerEvent} from './providers/posthog-server'@@ -9,25 +8,6 @@ export function isAnalyticsEnabled(): boolean {return process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'}-/**- * Evaluate a boolean feature flag for a distinct id. Returns undefined when- * analytics is disabled or evaluation fails, so callers apply their own- * default (never throws).- */-export async function getServerFeatureFlag(- key: string,- distinctId: string-): Promise<boolean | undefined> {- if (!isAnalyticsEnabled()) return undefined-- try {- return await getServerFeatureFlagProvider(key, distinctId)- } catch (error) {- console.error('Failed to evaluate feature flag:', error)- return undefined- }-}-export async function capture(event: ServerEvent): Promise<void> {if (!isAnalyticsEnabled()) returndiff --git a/lib/analytics/index.ts b/lib/analytics/index.tsindex 9a3f68b0..9ed30dc4 100644--- a/lib/analytics/index.ts+++ b/lib/analytics/index.ts@@ -6,7 +6,6 @@* @module analytics*/-export { getServerFeatureFlag } from './dispatch'export { trackAccountDeleted } from './track-account-event'export {type AdaptiveLimitEventData,diff --git a/lib/analytics/posthog-client.ts b/lib/analytics/posthog-client.tsindex 5f31e45f..5c5ebd8d 100644--- a/lib/analytics/posthog-client.ts+++ b/lib/analytics/posthog-client.ts@@ -74,25 +74,6 @@ export function isFeatureEnabled(key: string): boolean {return posthog.isFeatureEnabled?.(key) === true}-/**- * Whether related questions are enabled for the current distinct id.- *- * Returns:- * - `true` — analytics disabled (keep current behavior), or flag resolved on.- * - `false` — flag explicitly resolved to false.- * - `undefined` — flags not loaded yet (cold start / immediate auto-submit).- * Callers should treat this as "unknown" and let the server evaluate against- * the same distinct id, instead of defaulting on and misattributing- * first-message sessions to the on arm of the A/B.- */-export function isRelatedQuestionsEnabled(): boolean | undefined {- if (!clientKey()) return true- initPostHog()- const value = posthog.getFeatureFlag?.('related_questions_enabled')- if (value === undefined) return undefined- return value !== false-}-/** Subscribe to feature-flag loads/changes. Returns an unsubscribe function. */export function subscribeFeatureFlags(callback: () => void): () => void {if (!clientKey()) return () => {}diff --git a/lib/analytics/providers/posthog-server.ts b/lib/analytics/providers/posthog-server.tsindex cad8955d..b32de61e 100644--- a/lib/analytics/providers/posthog-server.ts+++ b/lib/analytics/providers/posthog-server.ts@@ -35,25 +35,6 @@ export async function captureServerEvent({await ph.flush()}-/**- * Evaluate a boolean feature flag server-side for a distinct id.- * Returns undefined when analytics is unconfigured, the flag is unknown, or- * evaluation fails, so callers apply their own default. Does not emit a- * $feature_flag_called event (the flag value is stamped on the chat event).- */-export async function getServerFeatureFlag(- key: string,- distinctId: string-): Promise<boolean | undefined> {- const ph = getClient()- if (!ph) return undefined-- const value = await ph.getFeatureFlag(key, distinctId, {- sendFeatureFlagEvents: false- })- return value === undefined ? undefined : value !== false-}-/*** Delete a person and their events via the management API.* Requires a dedicated personal API key scoped to person:write.diff --git a/lib/analytics/types.ts b/lib/analytics/types.tsindex a2c3a5dc..af64f649 100644--- a/lib/analytics/types.ts+++ b/lib/analytics/types.ts@@ -43,8 +43,6 @@ export interface ChatEventData {providerId: string/** Model identifier used for the chat */modelId: string- /** related_questions_enabled flag value for this request (A/B variant) */- relatedFlag?: boolean/** Derived query shape (omitted for regenerate, where no new query exists) */queryShape?: QueryShape}diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.tsindex 63ff9138..de62cd35 100644--- a/lib/streaming/create-chat-stream-response.ts+++ b/lib/streaming/create-chat-stream-response.ts@@ -48,8 +48,7 @@ export async function createChatStreamResponse(messageId,abortSignal,isNewChat,- searchMode,- relatedEnabled = true+ searchMode} = config// Verify that chatId is provided@@ -130,8 +129,7 @@ export async function createChatStreamResponse(model: context.modelId,modelConfig: model,parentTraceId,- searchMode,- relatedEnabled+ searchMode})// For OpenAI models, strip reasoning parts from UIMessages before conversiondiff --git a/lib/streaming/create-ephemeral-chat-stream-response.ts b/lib/streaming/create-ephemeral-chat-stream-response.tsindex a7249d65..54e4cdec 100644--- a/lib/streaming/create-ephemeral-chat-stream-response.ts+++ b/lib/streaming/create-ephemeral-chat-stream-response.ts@@ -29,7 +29,7 @@ import { BaseStreamConfig } from './types'type EphemeralStreamConfig = Pick<BaseStreamConfig,- 'model' | 'abortSignal' | 'searchMode' | 'relatedEnabled'+ 'model' | 'abortSignal' | 'searchMode'> & {messages: UIMessage[]chatId?: string@@ -38,14 +38,7 @@ type EphemeralStreamConfig = Pick<export async function createEphemeralChatStreamResponse(config: EphemeralStreamConfig): Promise<Response> {- const {- messages,- model,- abortSignal,- searchMode,- chatId,- relatedEnabled = true- } = config+ const { messages, model, abortSignal, searchMode, chatId } = configif (!messages || messages.length === 0) {return new Response('messages are required', {@@ -101,8 +94,7 @@ export async function createEphemeralChatStreamResponse(model: `${model.providerId}:${model.id}`,modelConfig: model,parentTraceId,- searchMode,- relatedEnabled+ searchMode})const modelId = `${model.providerId}:${model.id}`diff --git a/lib/streaming/types.ts b/lib/streaming/types.tsindex fd42acd0..e3361008 100644--- a/lib/streaming/types.ts+++ b/lib/streaming/types.ts@@ -13,5 +13,4 @@ export interface BaseStreamConfig {abortSignal?: AbortSignalisNewChat?: booleansearchMode?: SearchMode- relatedEnabled?: boolean}