Skip to content

Commit 18455d3

Browse files
fix(chat): only request contextual search when the backend supports it (#1638)
## Problem `chat-module.js` always sent `enableContextualSearch: true` to `POST /api/chat/stream`. `ChatController` returns **400 `contextual_search_unsupported`** when the selected `IChatCompletionService` has `SupportsContextualSearch == false`, which is the case for `LocalChatService` (Ollama / OpenAI-compatible) and `UnavailableChatService`. As a result, **local AI chat was broken in the UI** (the API worked when called with `enableContextualSearch: false`). Found while prototyping Playwright journey tests against the standalone Web AppHost with a fake local model. ## Fix - `AddConfiguredChatServices` registers a lightweight `ChatBackendCapabilities` record alongside whichever backend it selects (Azure → `true`; local / unavailable → `false`). - `_Layout.cshtml` emits `window.CHAT_SUPPORTS_CONTEXTUAL_SEARCH` from that record. - `chat-module.js` sends `enableContextualSearch` only when that value is not `false` (undefined keeps the previous behaviour). The layout deliberately injects the capabilities record rather than `IChatCompletionService`: in Azure mode, resolving the service constructs `AIChatService` → `AISearchService` → embeddings / vector store / `NpgsqlDataSource`, so a misconfiguration there would turn every page render into a 500 instead of only failing chat. ## Tests - `ChatContextualSearchCapabilityTests` (Web): the layout renders the flag from the registered capabilities (true/false), and the default test host (no AI config) renders `false`. Verified these fail without the layout change. - `ServiceCollectionExtensionsTests` (Chat): for every backend-selection scenario, exactly one `ChatBackendCapabilities` is registered and it matches the resolved service's `SupportsContextualSearch`, which guards against drift. `EssentialCSharp.Web.Tests` (193) and `EssentialCSharp.Chat.Tests` (41) pass locally. I have not manually clicked through chat in a browser with this exact build. The earlier prototype showed the UI flow works end to end once the flag is `false`.
1 parent 24bec9d commit 18455d3

6 files changed

Lines changed: 95 additions & 1 deletion

File tree

‎EssentialCSharp.Chat.Shared/Extensions/ServiceCollectionExtensions.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ public static IServiceCollection AddConfiguredChatServices(this IServiceCollecti
107107
services.AddOptions<EmbeddingRetryOptions>()
108108
.Bind(configuration.GetSection(EmbeddingRetryOptions.SectionPath));
109109
services.AddSingleton<IChatCompletionService>(provider => provider.GetRequiredService<AIChatService>());
110+
services.AddSingleton(new ChatBackendCapabilities(SupportsContextualSearch: true));
110111
Console.WriteLine("[AI] Selected backend: Azure/Foundry.");
111112
return services;
112113
}
@@ -118,6 +119,7 @@ public static IServiceCollection AddConfiguredChatServices(this IServiceCollecti
118119
|| (localEndpointUri.Scheme != Uri.UriSchemeHttp && localEndpointUri.Scheme != Uri.UriSchemeHttps))
119120
{
120121
services.AddSingleton<IChatCompletionService, UnavailableChatService>();
122+
services.AddSingleton(new ChatBackendCapabilities(SupportsContextualSearch: false));
121123
Console.Error.WriteLine("[AI] Local backend selected but LocalEndpoint is invalid. Falling back to unavailable backend.");
122124
return services;
123125
}
@@ -135,11 +137,13 @@ public static IServiceCollection AddConfiguredChatServices(this IServiceCollecti
135137
.RemoveAllResilienceHandlers();
136138
#pragma warning restore EXTEXP0001
137139
services.AddSingleton<IChatCompletionService, LocalChatService>();
140+
services.AddSingleton(new ChatBackendCapabilities(SupportsContextualSearch: false));
138141
Console.WriteLine("[AI] Selected backend: Local (Ollama/OpenAI-compatible).");
139142
return services;
140143
}
141144

142145
services.AddSingleton<IChatCompletionService, UnavailableChatService>();
146+
services.AddSingleton(new ChatBackendCapabilities(SupportsContextualSearch: false));
143147
Console.WriteLine("[AI] Selected backend: Unavailable (missing or invalid AI configuration).");
144148
return services;
145149
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
namespace EssentialCSharp.Chat.Common.Services;
2+
3+
/// <summary>
4+
/// Describes what the selected <see cref="IChatCompletionService"/> backend can do, without
5+
/// constructing it. Registered alongside the backend so UI code (for example the shared layout)
6+
/// can read capabilities on every page render without building the backend's dependency graph.
7+
/// </summary>
8+
/// <param name="SupportsContextualSearch">Mirrors <see cref="IChatCompletionService.SupportsContextualSearch"/>.</param>
9+
public sealed record ChatBackendCapabilities(bool SupportsContextualSearch);

‎EssentialCSharp.Chat.Tests/ServiceCollectionExtensionsTests.cs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,34 @@ public async Task AddConfiguredChatServices_SelectsExpectedBackend(string scenar
6060
await Assert.That(descriptor.ImplementationType).IsEqualTo(expectedChatServiceType);
6161
}
6262

63+
[Test]
64+
[Arguments("invalid-azure-falls-back-to-local")]
65+
[Arguments("valid-local")]
66+
[Arguments("connection-string-fallback")]
67+
[Arguments("invalid-local")]
68+
[Arguments("missing-config")]
69+
[Arguments("azure")]
70+
public async Task AddConfiguredChatServices_RegistersCapabilitiesMatchingSelectedBackend(string scenario)
71+
{
72+
Dictionary<string, string?> configValues = scenario == "azure"
73+
? new Dictionary<string, string?>
74+
{
75+
["AIOptions:Endpoint"] = "https://example.openai.azure.com",
76+
["AIOptions:ChatDeploymentName"] = "chat-deployment",
77+
["AIOptions:VectorGenerationDeploymentName"] = "embedding-deployment",
78+
["ConnectionStrings:PostgresVectorStore"] = "Host=localhost;Database=test;Username=test;Password=test;"
79+
}
80+
: CreateBackendSelectionScenario(scenario).ConfigValues;
81+
var services = CreateServices(configValues);
82+
83+
await Assert.That(services.Count(d => d.ServiceType == typeof(ChatBackendCapabilities))).IsEqualTo(1);
84+
85+
using var provider = services.BuildServiceProvider();
86+
var capabilities = provider.GetRequiredService<ChatBackendCapabilities>();
87+
var chatService = provider.GetRequiredService<IChatCompletionService>();
88+
await Assert.That(capabilities.SupportsContextualSearch).IsEqualTo(chatService.SupportsContextualSearch);
89+
}
90+
6391
private static ServiceCollection CreateServices(Dictionary<string, string?> values)
6492
{
6593
var configuration = new ConfigurationBuilder()
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using EssentialCSharp.Chat.Common.Services;
2+
using Microsoft.AspNetCore.Mvc.Testing;
3+
using Microsoft.Extensions.DependencyInjection;
4+
using Microsoft.Extensions.DependencyInjection.Extensions;
5+
6+
namespace EssentialCSharp.Web.Tests;
7+
8+
/// <summary>
9+
/// The chat widget reads <c>window.CHAT_SUPPORTS_CONTEXTUAL_SEARCH</c> to decide whether to request
10+
/// contextual search; the API rejects that request for backends that cannot perform it.
11+
/// </summary>
12+
public class ChatContextualSearchCapabilityTests : IntegrationTestBase
13+
{
14+
[Test]
15+
[Arguments(true)]
16+
[Arguments(false)]
17+
public async Task Layout_RendersChatBackendContextualSearchSupport(bool supportsContextualSearch)
18+
{
19+
await using WebApplicationFactory<Program> factory = Factory.Inner.WithWebHostBuilder(builder =>
20+
builder.ConfigureServices(services =>
21+
{
22+
services.RemoveAll<ChatBackendCapabilities>();
23+
services.AddSingleton(new ChatBackendCapabilities(supportsContextualSearch));
24+
}));
25+
using HttpClient client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
26+
27+
using HttpResponseMessage response = await GetFollowingGetRedirectsAsync(client, "/home");
28+
string body = await response.Content.ReadAsStringAsync();
29+
30+
await Assert.That(response.IsSuccessStatusCode).IsTrue();
31+
await Assert.That(body).Contains(
32+
$"window.CHAT_SUPPORTS_CONTEXTUAL_SEARCH = {(supportsContextualSearch ? "true" : "false")};");
33+
}
34+
35+
[Test]
36+
public async Task Layout_WithDefaultTestBackend_DoesNotRequestContextualSearch()
37+
{
38+
// The test host has no AI configuration, so the Unavailable backend (no contextual search) is selected.
39+
using HttpClient client = CreateClientWithoutAutoRedirect();
40+
41+
using HttpResponseMessage response = await GetFollowingGetRedirectsAsync(client, "/home");
42+
string body = await response.Content.ReadAsStringAsync();
43+
44+
await Assert.That(body).Contains("window.CHAT_SUPPORTS_CONTEXTUAL_SEARCH = false;");
45+
}
46+
}

‎EssentialCSharp.Web/Views/Shared/_Layout.cshtml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@
88
@using EssentialCSharp.Web.Areas.Identity.Data
99
@using Microsoft.Extensions.Configuration
1010
@using Microsoft.Extensions.Options
11+
@using EssentialCSharp.Chat.Common.Services
1112
@inject ISiteMappingService _SiteMappings
1213
@inject SignInManager<EssentialCSharpWebUser> SignInManager
1314
@inject IConfiguration Configuration
1415
@inject IOptions<CaptchaOptions> _CaptchaOptions
1516
@inject IOptions<SiteSettings> SiteSettings
17+
@inject ChatBackendCapabilities _ChatCapabilities
1618
<!DOCTYPE html>
1719
<html lang="en">
1820
<head>
@@ -221,6 +223,7 @@
221223
window.BUILD_LABEL = @Json.Serialize(buildLabel);
222224
window.ENABLE_CHAT_WIDGET = @Json.Serialize(!Context.Request.Path.StartsWithSegments("/Identity"));
223225
window.HCAPTCHA_SITE_KEY = @Json.Serialize(chatCaptchaSiteKey);
226+
window.CHAT_SUPPORTS_CONTEXTUAL_SEARCH = @Json.Serialize(_ChatCapabilities.SupportsContextualSearch);
224227
</script>
225228
<script src="~/dist/assets/site-shell.js" type="module" asp-append-version="true"></script>
226229
</body>

‎EssentialCSharp.Web/wwwroot/js/chat-module.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ function getTraceHeaders() {
2424
return headers;
2525
}
2626

27+
// The server rejects contextual search for backends that do not support it (e.g. local Ollama),
28+
// so only request it when the layout says the selected backend can perform it.
29+
const chatSupportsContextualSearch = window.CHAT_SUPPORTS_CONTEXTUAL_SEARCH !== false;
30+
2731
// hCaptcha integration — invisible widget renders once and is reused across messages.
2832
// When HCAPTCHA_SITE_KEY is null (dev / captcha not configured), all captcha calls are no-ops.
2933
const captchaSiteKey = window.HCAPTCHA_SITE_KEY || null;
@@ -341,7 +345,7 @@ export function useChatWidget() {
341345

342346
const requestBody = {
343347
message: userMessage,
344-
enableContextualSearch: true,
348+
enableContextualSearch: chatSupportsContextualSearch,
345349
previousResponseId: lastResponseId.value,
346350
captchaResponse: captchaResponse
347351
};

0 commit comments

Comments
 (0)