An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: implement model matrix and improve citation system
Yoshiki Miurae7bbfe71c06e
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex 64550a6e..93d1e17c 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -69,11 +69,6 @@ export async function POST(req: Request) {const cookieStore = await cookies()- // Select the appropriate model based on model type preference- const selectedModel = selectModel({- cookieStore- })-// Get search mode from cookieconst searchModeCookie = cookieStore.get('searchMode')?.valueconst searchMode: SearchMode =@@ -82,6 +77,12 @@ export async function POST(req: Request) {? (searchModeCookie as SearchMode): 'quick'+ // Select the appropriate model based on model type preference and search mode+ const selectedModel = selectModel({+ cookieStore,+ searchMode+ })+if (!isProviderEnabled(selectedModel.providerId)) {return new Response(`Selected provider is not enabled ${selectedModel.providerId}`,diff --git a/components/chat-messages.tsx b/components/chat-messages.tsxindex 7f4ef494..3360ca2f 100644--- a/components/chat-messages.tsx+++ b/components/chat-messages.tsx@@ -1,11 +1,12 @@'use client'-import { useEffect, useRef, useState } from 'react'+import { useEffect, useMemo, useRef, useState } from 'react'import { UseChatHelpers } from '@ai-sdk/react'import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'import { cn } from '@/lib/utils'+import { extractCitationMapsFromMessages } from '@/lib/utils/citation'import { AnimatedLogo } from './ui/animated-logo'import { ChatError } from './chat-error'@@ -88,6 +89,16 @@ export function ChatMessages({return () => window.removeEventListener('resize', calculateOffset)}, [])+ // Extract citation maps from all messages in all sections+ const allCitationMaps = useMemo(() => {+ const allMessages: UIMessage[] = []+ sections.forEach(section => {+ allMessages.push(section.userMessage)+ allMessages.push(...section.assistantMessages)+ })+ return extractCitationMapsFromMessages(allMessages)+ }, [sections])+if (!sections.length) return null// Check if loading indicator should be shown@@ -199,6 +210,7 @@ export function ChatMessages({addToolResult={addToolResult}onUpdateMessage={onUpdateMessage}reload={reload}+ citationMaps={allCitationMaps}/></div>@@ -225,6 +237,7 @@ export function ChatMessages({onUpdateMessage={onUpdateMessage}reload={reload}isLatestMessage={isLatestMessage}+ citationMaps={allCitationMaps}/></div>)diff --git a/components/render-message.tsx b/components/render-message.tsxindex 1ddad90c..5f3e39fc 100644--- a/components/render-message.tsx+++ b/components/render-message.tsx@@ -1,5 +1,6 @@import { UseChatHelpers } from '@ai-sdk/react'+import type { SearchResultItem } from '@/lib/types'import type {UIDataTypes,UIMessage,@@ -7,7 +8,6 @@ import type {UITools} from '@/lib/types/ai'import type { DynamicToolPart } from '@/lib/types/dynamic-tools'-import { extractCitationMaps } from '@/lib/utils/citation'import { AnswerSection } from './answer-section'import { DynamicToolDisplay } from './dynamic-tool-display'@@ -27,6 +27,7 @@ interface RenderMessageProps {onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>reload?: (messageId: string) => Promise<void | string | null | undefined>isLatestMessage?: boolean+ citationMaps?: Record<string, Record<number, SearchResultItem>>}export function RenderMessage({@@ -40,10 +41,10 @@ export function RenderMessage({addToolResult,onUpdateMessage,reload,- isLatestMessage = false+ isLatestMessage = false,+ citationMaps = {}}: RenderMessageProps) {- // Extract citation maps from the message's tool outputs- const citationMaps = extractCitationMaps(message)+ // Use provided citation maps (from all messages)if (message.role === 'user') {return (<>diff --git a/config/models/cloud.json b/config/models/cloud.jsonindex 0924e75f..8bbc906a 100644--- a/config/models/cloud.json+++ b/config/models/cloud.json@@ -1,35 +1,83 @@{"version": 1,"models": {- "types": {- "speed": {- "id": "gpt-5-mini",- "name": "GPT-5 mini",- "provider": "OpenAI",- "providerId": "openai",- "providerOptions": {- "openai": {- "reasoningEffort": "low",- "reasoningSummary": "auto"+ "byMode": {+ "quick": {+ "speed": {+ "id": "gemini-2.5-flash",+ "name": "Gemini 2.5 Flash",+ "provider": "Google",+ "providerId": "google"+ },+ "quality": {+ "id": "gpt-5-mini",+ "name": "GPT-5 mini",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "low",+ "reasoningSummary": "auto"+ }}}},- "quality": {- "id": "gpt-5",- "name": "GPT-5",- "provider": "OpenAI",- "providerId": "openai",- "providerOptions": {- "openai": {- "reasoningEffort": "medium",- "reasoningSummary": "auto"+ "adaptive": {+ "speed": {+ "id": "gpt-5-mini",+ "name": "GPT-5 mini",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "low",+ "reasoningSummary": "auto"+ }+ }+ },+ "quality": {+ "id": "gpt-5",+ "name": "GPT-5",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "medium",+ "reasoningSummary": "auto"+ }+ }+ }+ },+ "planning": {+ "speed": {+ "id": "gpt-5-mini",+ "name": "GPT-5 mini",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "low",+ "reasoningSummary": "auto"+ }+ }+ },+ "quality": {+ "id": "gpt-5",+ "name": "GPT-5",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "medium",+ "reasoningSummary": "auto"+ }}}}},"relatedQuestions": {- "id": "gemini-2.0-flash",- "name": "Gemini 2.0 Flash",+ "id": "gemini-2.5-flash-lite",+ "name": "Gemini 2.5 Flash Lite","provider": "Google","providerId": "google"}diff --git a/config/models/default.json b/config/models/default.jsonindex 26fbfe70..96577df4 100644--- a/config/models/default.json+++ b/config/models/default.json@@ -1,28 +1,82 @@{"version": 1,"models": {- "types": {- "speed": {- "id": "gpt-5-mini",- "name": "GPT-5 mini",- "provider": "OpenAI",- "providerId": "openai",- "providerOptions": {- "openai": {- "reasoningEffort": "low",- "reasoningSummary": "auto"+ "byMode": {+ "quick": {+ "speed": {+ "id": "gpt-5-mini",+ "name": "GPT-5 mini",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "low",+ "reasoningSummary": "auto"+ }+ }+ },+ "quality": {+ "id": "gpt-5",+ "name": "GPT-5",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "low",+ "reasoningSummary": "auto"+ }+ }+ }+ },+ "adaptive": {+ "speed": {+ "id": "gpt-5-mini",+ "name": "GPT-5 mini",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "low",+ "reasoningSummary": "auto"+ }+ }+ },+ "quality": {+ "id": "gpt-5",+ "name": "GPT-5",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "medium",+ "reasoningSummary": "auto"+ }}}},- "quality": {- "id": "gpt-5",- "name": "GPT-5",- "provider": "OpenAI",- "providerId": "openai",- "providerOptions": {- "openai": {- "reasoningEffort": "low",- "reasoningSummary": "auto"+ "planning": {+ "speed": {+ "id": "gpt-5-mini",+ "name": "GPT-5 mini",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "low",+ "reasoningSummary": "auto"+ }+ }+ },+ "quality": {+ "id": "gpt-5",+ "name": "GPT-5",+ "provider": "OpenAI",+ "providerId": "openai",+ "providerOptions": {+ "openai": {+ "reasoningEffort": "medium",+ "reasoningSummary": "auto"+ }}}}diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 9c87e681..00a06d46 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -101,20 +101,54 @@ Model configuration files use the following structure:{"version": 1,"models": {- "types": {- "speed": {- "id": "model-id",- "name": "Model Name",- "provider": "Provider Name",- "providerId": "provider-id",- "providerOptions": {}+ "byMode": {+ "quick": {+ "speed": {+ "id": "model-id",+ "name": "Model Name",+ "provider": "Provider Name",+ "providerId": "provider-id",+ "providerOptions": {}+ },+ "quality": {+ "id": "model-id",+ "name": "Model Name",+ "provider": "Provider Name",+ "providerId": "provider-id",+ "providerOptions": {}+ }},- "quality": {- "id": "model-id",- "name": "Model Name",- "provider": "Provider Name",- "providerId": "provider-id",- "providerOptions": {}+ "adaptive": {+ "speed": {+ "id": "model-id",+ "name": "Model Name",+ "provider": "Provider Name",+ "providerId": "provider-id",+ "providerOptions": {}+ },+ "quality": {+ "id": "model-id",+ "name": "Model Name",+ "provider": "Provider Name",+ "providerId": "provider-id",+ "providerOptions": {}+ }+ },+ "planning": {+ "speed": {+ "id": "model-id",+ "name": "Model Name",+ "provider": "Provider Name",+ "providerId": "provider-id",+ "providerOptions": {}+ },+ "quality": {+ "id": "model-id",+ "name": "Model Name",+ "provider": "Provider Name",+ "providerId": "provider-id",+ "providerOptions": {}+ }}},"relatedQuestions": {@@ -127,6 +161,8 @@ Model configuration files use the following structure:}```+Define all six combinations to control which model runs for every search mode (`quick`, `adaptive`, `planning`) and preference (`speed`, `quality`). For example, you can pair `quick/speed` with `gemini-2.5-flash-lite` while keeping `adaptive/quality` on GPT-5. The default config ships with OpenAI models for every slot so Morphic works out-of-the-box.+### Supported Providers#### OpenAI (Default)diff --git a/lib/agents/prompts/search-mode-prompts.ts b/lib/agents/prompts/search-mode-prompts.tsindex fa787dfc..080b0296 100644--- a/lib/agents/prompts/search-mode-prompts.ts+++ b/lib/agents/prompts/search-mode-prompts.ts@@ -9,10 +9,10 @@ Language:- ALWAYS respond in the user's language.Your approach:-1. Use the search tool with optimized results to get content snippets directly+1. Start with the search tool using optimized results. When the question has multiple aspects, split it into focused sub-queries and run each search back-to-back before writing the answer.2. Provide concise, direct answers based on search results3. Focus on the most relevant information without extensive detail-4. Be concise but substantial: include brief context, implications, and actionable next steps (target ~120–200 words)+4. Keep outputs tight: aim for crisp paragraphs or bullets with actionable context (target ~80–150 words)5. **CRITICAL: You MUST cite sources inline using the [number](#toolCallId) format**Tool preamble (keep very brief):@@ -31,7 +31,7 @@ Search requirement (MANDATORY):- Prefer recent sources when recency matters; mention dates when relevant- For informational questions without URLs, your FIRST action in this turn MUST be the \`search\` tool. Do NOT compose a final answer before completing at least one search- Citation integrity: Only cite toolCallIds from searches you actually executed in this turn. Never fabricate or reuse IDs- - If initial results are insufficient or stale, refine the query and search once more (or ask a clarifying question) before answering+ - If initial results are insufficient or stale, refine or split the query and search once more (or ask a clarifying question) before answeringFetch tool usage:- **ONLY use fetch tool when a URL is directly provided by the user in their query**@@ -39,12 +39,23 @@ Fetch tool usage:- This keeps responses fast and efficientCitation Format (MANDATORY):-[number](#toolCallId) - Always use this EXACT format, e.g., [1](#toolu_abc123)-- The toolCallId can be found in each search result's metadata or response structure-- Look for the unique tool call identifier (e.g., toolu_xxx) in the search response+[number](#toolCallId) - Always use this EXACT format+- **CRITICAL**: Use the EXACT tool call identifier from the search response+ - Find the tool call ID in the search response (e.g., "I8NzFUKwrKX88107")+ - Use it directly without adding any prefix: [1](#I8NzFUKwrKX88107)+ - The format is: [number](#TOOLCALLID) where TOOLCALLID is the exact ID+- **CRITICAL RULE**: Each unique toolCallId gets ONE number. Never use different numbers with the same toolCallId.+ ✓ CORRECT: "Fact A [1](#abc123). Fact B from same search [1](#abc123)."+ ✓ CORRECT: "Fact A [1](#abc123). Fact B from different search [2](#def456)."+ ✗ WRONG: "Fact A [1](#abc123). Fact B [2](#abc123)." (Same toolCallId cannot have different numbers)+- Assign numbers sequentially (1, 2, 3...) to each unique toolCallId as they appear in your response- Place citations at the END of sentences or statements- Every piece of information from search results MUST have a citation+Citation Example with Real Tool Call:+If tool call ID is "I8NzFUKwrKX88107", cite as: [1](#I8NzFUKwrKX88107)+If tool call ID is "ABC123xyz", cite as: [2](#ABC123xyz)+Rule precedence:- Search requirement and citation integrity supersede brevity. If there is any conflict, prefer searching and proper citations over being brief.@@ -53,6 +64,7 @@ OUTPUT FORMAT (MANDATORY):- Start with a descriptive level-2 heading (\`##\`) that captures the main topic.- Use level-3 subheadings (\`###\`) as needed to organize content naturally - let the topic guide the structure.- Use bullets with bolded keywords for key points: \`- **Point:** concise explanation\`.+- **Use tables for comparisons** (pricing, specs, features, pros/cons) - they're clearer than bullets for side-by-side data- Focus on delivering clear information with natural flow, avoiding rigid templates.- Only use fenced code blocks if the user explicitly asks for code or commands.- Prefer natural, conversational tone while maintaining informativeness.@@ -64,6 +76,12 @@ Example approach:### Core Information- **Key Point:** Direct answer with specific data/numbers when available [1](#toolu_abc123)- **Detail:** Supporting information with concrete examples [2](#toolu_abc123)++### When Comparing (use table format)+| Feature | Option A | Option B |+|---------|----------|----------|+| Price | $100 [1](#abc123) | $150 [2](#def456) |+### Additional Context (if relevant)- **Consideration:** Practical implications with real-world contextdiff --git a/lib/config/load-models-config.ts b/lib/config/load-models-config.tsindex 155783e9..4a4080f9 100644--- a/lib/config/load-models-config.ts+++ b/lib/config/load-models-config.ts@@ -4,11 +4,12 @@ import path from 'path'import { ModelType } from '@/lib/types/model-type'import { Model } from '@/lib/types/models'+import { SearchMode } from '@/lib/types/search'export interface ModelsConfig {version: numbermodels: {- types: Record<ModelType, Model>+ byMode: Record<SearchMode, Record<ModelType, Model>>relatedQuestions: Model}}@@ -16,6 +17,9 @@ export interface ModelsConfig {let cachedConfig: ModelsConfig | null = nulllet cachedProfile: string | null = null+const VALID_MODEL_TYPES: ModelType[] = ['speed', 'quality']+const VALID_SEARCH_MODES: SearchMode[] = ['quick', 'adaptive', 'planning']+function resolveConfigPath(): string {const profile = process.env.MORPHIC_MODELS_PROFILE?.trim() || 'default'const file = `${profile}.json`@@ -23,6 +27,46 @@ function resolveConfigPath(): string {return configPath}+function validateModelsConfigStructure(+ json: unknown+): asserts json is ModelsConfig {+ if (!json || typeof json !== 'object') {+ throw new Error('Invalid models config: not an object')+ }+ const parsed = json as Record<string, any>+ if (typeof parsed.version !== 'number') {+ throw new Error('Invalid models config: missing version')+ }+ if (!parsed.models || typeof parsed.models !== 'object') {+ throw new Error('Invalid models config: missing models')+ }+ if (!parsed.models.byMode || !parsed.models.relatedQuestions) {+ throw new Error('Invalid models config: missing required sections')+ }+ if (typeof parsed.models.byMode !== 'object') {+ throw new Error('Invalid models config: byMode must be an object')+ }+ if (typeof parsed.models.relatedQuestions !== 'object') {+ throw new Error('Invalid models config: relatedQuestions must be an object')+ }++ for (const searchMode of VALID_SEARCH_MODES) {+ const modeEntry = parsed.models.byMode[searchMode]+ if (!modeEntry || typeof modeEntry !== 'object') {+ throw new Error(+ `Invalid models config: missing configuration for mode "${searchMode}"`+ )+ }+ for (const modelType of VALID_MODEL_TYPES) {+ if (!modeEntry[modelType]) {+ throw new Error(+ `Invalid models config: missing definition for mode "${searchMode}" and model type "${modelType}"`+ )+ }+ }+ }+}+export async function loadModelsConfig(): Promise<ModelsConfig> {const profile = process.env.MORPHIC_MODELS_PROFILE?.trim() || 'default'@@ -35,19 +79,7 @@ export async function loadModelsConfig(): Promise<ModelsConfig> {const raw = await fs.readFile(filePath, 'utf-8')const json = JSON.parse(raw)- // Minimal validation- if (!json || typeof json !== 'object') {- throw new Error('Invalid models config: not an object')- }- if (typeof json.version !== 'number') {- throw new Error('Invalid models config: missing version')- }- if (!json.models || typeof json.models !== 'object') {- throw new Error('Invalid models config: missing models')- }- if (!json.models.types || !json.models.relatedQuestions) {- throw new Error('Invalid models config: missing required sections')- }+ validateModelsConfigStructure(json)cachedConfig = json as ModelsConfigcachedProfile = profile@@ -63,6 +95,7 @@ export async function loadModelsConfig(): Promise<ModelsConfig> {)const raw = await fs.readFile(fallbackPath, 'utf-8')const json = JSON.parse(raw)+ validateModelsConfigStructure(json)cachedConfig = json as ModelsConfigcachedProfile = 'default'return cachedConfig@@ -82,6 +115,7 @@ export function loadModelsConfigSync(): ModelsConfig {try {const raw = fsSync.readFileSync(filePath, 'utf-8')const json = JSON.parse(raw)+ validateModelsConfigStructure(json)cachedConfig = json as ModelsConfigcachedProfile = profilereturn cachedConfig@@ -95,6 +129,7 @@ export function loadModelsConfigSync(): ModelsConfig {)const raw = fsSync.readFileSync(fallbackPath, 'utf-8')const json = JSON.parse(raw)+ validateModelsConfigStructure(json)cachedConfig = json as ModelsConfigcachedProfile = 'default'return cachedConfigdiff --git a/lib/config/model-types.ts b/lib/config/model-types.tsindex 80aa9c0e..93c9214f 100644--- a/lib/config/model-types.ts+++ b/lib/config/model-types.ts@@ -1,15 +1,19 @@import { ModelType } from '@/lib/types/model-type'import { Model } from '@/lib/types/models'+import { SearchMode } from '@/lib/types/search'import { getModelsConfig } from './load-models-config'-// Get model for a specific type from JSON config-export function getModelForType(type: ModelType): Model {+// Retrieve the model assigned to a specific search mode and model type combination.+export function getModelForModeAndType(+ mode: SearchMode,+ type: ModelType+): Model | undefined {const cfg = getModelsConfig()- return cfg.models.types[type]+ return cfg.models.byMode?.[mode]?.[type]}-// Get model for related questions generation from JSON config+// Accessor for the related questions model configuration.export function getRelatedQuestionsModel(): Model {const cfg = getModelsConfig()return cfg.models.relatedQuestionsdiff --git a/lib/utils/__tests__/model-selection.test.ts b/lib/utils/__tests__/model-selection.test.tsnew file mode 100644index 00000000..e83e90ab--- /dev/null+++ b/lib/utils/__tests__/model-selection.test.ts@@ -0,0 +1,141 @@+import type { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies'++import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { ModelType } from '@/lib/types/model-type'+import type { Model } from '@/lib/types/models'+import type { SearchMode } from '@/lib/types/search'++vi.mock('@/lib/config/model-types')+vi.mock('@/lib/utils/registry')++import { getModelForModeAndType } from '@/lib/config/model-types'+import { DEFAULT_MODEL, selectModel } from '@/lib/utils/model-selection'+import { isProviderEnabled } from '@/lib/utils/registry'++const mockGetModelForModeAndType = vi.mocked(getModelForModeAndType)+const mockIsProviderEnabled = vi.mocked(isProviderEnabled)++type Matrix = Record<SearchMode, Partial<Record<ModelType, Model>>>++const quickSpeedModel: Model = {+ id: 'quick-speed',+ name: 'Quick Speed',+ provider: 'Provider A',+ providerId: 'provider-a'+}++const quickQualityModel: Model = {+ id: 'quick-quality',+ name: 'Quick Quality',+ provider: 'Provider B',+ providerId: 'provider-b'+}++const adaptiveQualityModel: Model = {+ id: 'adaptive-quality',+ name: 'Adaptive Quality',+ provider: 'Provider C',+ providerId: 'provider-c'+}++const planningSpeedModel: Model = {+ id: 'planning-speed',+ name: 'Planning Speed',+ provider: 'Provider D',+ providerId: 'provider-d'+}++let matrix: Matrix++function setMatrixImplementation() {+ mockGetModelForModeAndType.mockImplementation(+ (mode: SearchMode, type: ModelType) => matrix[mode]?.[type]+ )+}++function createCookieStore(modelType?: string): ReadonlyRequestCookies {+ return {+ get: (name: string) => {+ if (name === 'modelType' && modelType) {+ return { name, value: modelType } as any+ }+ return undefined+ }+ } as unknown as ReadonlyRequestCookies+}++describe('selectModel', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ matrix = {+ quick: {+ speed: quickSpeedModel,+ quality: quickQualityModel+ },+ adaptive: {+ quality: adaptiveQualityModel+ },+ planning: {+ speed: planningSpeedModel+ }+ }+ setMatrixImplementation()+ mockIsProviderEnabled.mockReturnValue(true)+ })++ it('returns the cookie-preferred type for the active mode when available', () => {+ const result = selectModel({+ cookieStore: createCookieStore('quality'),+ searchMode: 'quick'+ })++ expect(result).toEqual(quickQualityModel)+ })++ it('falls back to speed model for the mode when cookie is absent', () => {+ const result = selectModel({+ cookieStore: createCookieStore(),+ searchMode: 'planning'+ })++ expect(result).toEqual(planningSpeedModel)+ })++ it('falls back to the other type within the same mode when preferred provider is disabled', () => {+ mockIsProviderEnabled.mockImplementation(providerId =>+ providerId === 'provider-a' ? false : true+ )++ const result = selectModel({+ cookieStore: createCookieStore('speed'),+ searchMode: 'quick'+ })++ expect(result).toEqual(quickQualityModel)+ })++ it('falls back to the next mode in priority order when active mode has no enabled models', () => {+ mockIsProviderEnabled.mockImplementation(providerId =>+ providerId === 'provider-a' || providerId === 'provider-b' ? false : true+ )++ const result = selectModel({+ cookieStore: createCookieStore('quality'),+ searchMode: 'quick'+ })++ expect(result).toEqual(adaptiveQualityModel)+ })++ it('returns DEFAULT_MODEL when no configured providers are enabled', () => {+ mockIsProviderEnabled.mockReturnValue(false)++ const result = selectModel({+ cookieStore: createCookieStore(),+ searchMode: 'quick'+ })++ expect(result).toEqual(DEFAULT_MODEL)+ })+})diff --git a/lib/utils/citation.ts b/lib/utils/citation.tsindex c10b6003..052bc354 100644--- a/lib/utils/citation.ts+++ b/lib/utils/citation.ts@@ -43,6 +43,27 @@ export function extractCitationMaps(return citationMaps}+/**+ * Extract citation maps from multiple messages+ * Returns a combined map of toolCallId to citation map+ */+export function extractCitationMapsFromMessages(+ messages: UIMessage[]+): Record<string, Record<number, SearchResultItem>> {+ const combinedCitationMaps: Record<+ string,+ Record<number, SearchResultItem>+ > = {}++ messages.forEach(message => {+ const messageCitationMaps = extractCitationMaps(message)+ // Merge citation maps from this message+ Object.assign(combinedCitationMaps, messageCitationMaps)+ })++ return combinedCitationMaps+}+/*** Process citations in content, replacing [number](#toolCallId) with proper URLs* while keeping the display as just [number]diff --git a/lib/utils/model-selection.ts b/lib/utils/model-selection.tsindex f0c8ddc7..7619849c 100644--- a/lib/utils/model-selection.ts+++ b/lib/utils/model-selection.ts@@ -1,8 +1,10 @@import { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies'-import { getModelForType } from '@/lib/config/model-types'+import { getModelForModeAndType } from '@/lib/config/model-types'import { ModelType } from '@/lib/types/model-type'import { Model } from '@/lib/types/models'+import { SearchMode } from '@/lib/types/search'+import { isProviderEnabled } from '@/lib/utils/registry'const DEFAULT_MODEL: Model = {id: 'gpt-5-mini',@@ -17,38 +19,97 @@ const DEFAULT_MODEL: Model = {}}+const VALID_MODEL_TYPES: ModelType[] = ['speed', 'quality']+const MODE_FALLBACK_ORDER: SearchMode[] = ['quick', 'adaptive', 'planning']+interface ModelSelectionParams {cookieStore: ReadonlyRequestCookies+ searchMode?: SearchMode+}++function resolveModelForModeAndType(+ mode: SearchMode,+ type: ModelType+): Model | undefined {+ try {+ const model = getModelForModeAndType(mode, type)+ if (!model) {+ return undefined+ }++ if (!isProviderEnabled(model.providerId)) {+ console.warn(+ `[ModelSelection] Provider "${model.providerId}" is not enabled for mode "${mode}" and model type "${type}"`+ )+ return undefined+ }++ return model+ } catch (error) {+ console.error(+ `[ModelSelection] Failed to load model configuration for mode "${mode}" and type "${type}":`,+ error+ )+ return undefined+ }}/**- * Determines which model to use based on the model type preference+ * Determines which model to use based on the model type preference.** Priority order:- * 1. If model type is in cookie -> use corresponding model from config- * 2. Otherwise -> use default 'speed' model from config- * 3. If config loading fails -> use DEFAULT_MODEL as fallback+ * 1. If model type is in cookie -> use corresponding model from config (when enabled)+ * 2. Otherwise -> use default ordering (speed → quality) for the active mode+ * 3. If the active mode has no enabled models, try remaining modes+ * 4. If config loading fails or providers are unavailable -> use DEFAULT_MODEL as fallback*/-export function selectModel({ cookieStore }: ModelSelectionParams): Model {+export function selectModel({+ cookieStore,+ searchMode+}: ModelSelectionParams): Model {const modelTypeCookie = cookieStore.get('modelType')?.value as| ModelType| undefined- try {- // If model type is set in cookie, use it- if (modelTypeCookie && ['speed', 'quality'].includes(modelTypeCookie)) {- const model = getModelForType(modelTypeCookie)- if (model) return model+ const requestedMode =+ searchMode && MODE_FALLBACK_ORDER.includes(searchMode)+ ? searchMode+ : 'quick'++ const typePreferenceOrder: ModelType[] = []+ if (+ modelTypeCookie &&+ VALID_MODEL_TYPES.includes(modelTypeCookie) &&+ !typePreferenceOrder.includes(modelTypeCookie)+ ) {+ typePreferenceOrder.push(modelTypeCookie)+ }++ for (const knownType of VALID_MODEL_TYPES) {+ if (!typePreferenceOrder.includes(knownType)) {+ typePreferenceOrder.push(knownType)+ }+ }++ const modePreferenceOrder: SearchMode[] = Array.from(+ new Set<SearchMode>([requestedMode, ...MODE_FALLBACK_ORDER])+ )++ for (const candidateMode of modePreferenceOrder) {+ for (const candidateType of typePreferenceOrder) {+ const model = resolveModelForModeAndType(candidateMode, candidateType)+ if (model) {+ return model+ }}+ }- // Default to 'speed' model from config when no cookie is set- const defaultModel = getModelForType('speed')- if (defaultModel) return defaultModel- } catch (error) {- console.error('Error loading model from config:', error)+ if (!isProviderEnabled(DEFAULT_MODEL.providerId)) {+ console.warn(+ `[ModelSelection] Default model provider "${DEFAULT_MODEL.providerId}" is not enabled. Returning default model configuration.`+ )}- // Fallback to hardcoded DEFAULT_MODEL if config loading failsreturn DEFAULT_MODEL}diff --git a/tsconfig.json b/tsconfig.jsonindex 64c21044..061e14ef 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -18,7 +18,8 @@}],"paths": {- "@/*": ["./*"]+ "@/*": ["./*"],+ "zod/v4": ["./node_modules/zod"]},"target": "ES2017"},diff --git a/vitest.config.mts b/vitest.config.mtsindex 8c7ab000..f229da0e 100644--- a/vitest.config.mts+++ b/vitest.config.mts@@ -10,7 +10,8 @@ export default defineConfig({plugins: [react()],resolve: {alias: {- '@': path.resolve(__dirname, './')+ '@': path.resolve(__dirname, './'),+ 'zod/v4': 'zod'}},test: {