5 Commits

21 changed files with 1635 additions and 123 deletions
@@ -1,18 +1,7 @@
using FluentResults;
using MediatR;
using Pgvector;
using Pgvector.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.DTOs.AI;
using Microsoft.Extensions.AI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Resilience;
using Polly;
using Polly.Registry;
using Mapster;
using MapsterMapper;
using NexusReader.Data.Persistence;
namespace NexusReader.Application.Queries.Library;
@@ -21,21 +10,11 @@ public record SearchLibrarySemanticallyQuery(string QueryText, string TenantId,
public class SearchLibrarySemanticallyQueryHandler : IRequestHandler<SearchLibrarySemanticallyQuery, Result<List<SemanticSearchResultDto>>>
{
private readonly IEmbeddingGenerator<string, Embedding<float>> _embeddingGenerator;
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
private readonly ResiliencePipeline _retryPipeline;
private readonly IMapper _mapper;
private readonly IKnowledgeService _knowledgeService;
public SearchLibrarySemanticallyQueryHandler(
IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator,
IDbContextFactory<AppDbContext> dbContextFactory,
ResiliencePipelineProvider<string> pipelineProvider,
IMapper mapper)
public SearchLibrarySemanticallyQueryHandler(IKnowledgeService knowledgeService)
{
_embeddingGenerator = embeddingGenerator;
_dbContextFactory = dbContextFactory;
_retryPipeline = pipelineProvider.GetPipeline("ai-retry");
_mapper = mapper;
_knowledgeService = knowledgeService;
}
public async Task<Result<List<SemanticSearchResultDto>>> Handle(SearchLibrarySemanticallyQuery request, CancellationToken cancellationToken)
@@ -45,19 +24,10 @@ public class SearchLibrarySemanticallyQueryHandler : IRequestHandler<SearchLibra
return Result.Fail("Query text cannot be empty.");
}
// Generate embedding with retry
var embeddingResponse = await _retryPipeline.ExecuteAsync(async ct =>
await _embeddingGenerator.GenerateAsync(new[] { request.QueryText }, cancellationToken: ct), cancellationToken);
var queryVector = new Vector(embeddingResponse.First().Vector.ToArray());
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
var cacheEntries = await dbContext.SemanticKnowledgeCache
.Where(c => c.TenantId == request.TenantId && c.Embedding != null)
.OrderBy(c => c.Embedding!.CosineDistance(queryVector))
.Take(request.Limit)
.ToListAsync(cancellationToken);
var dtos = _mapper.Map<List<SemanticSearchResultDto>>(cacheEntries);
return Result.Ok(dtos);
return await _knowledgeService.SearchLibrarySemanticallyAsync(
request.QueryText,
request.TenantId,
request.Limit,
cancellationToken);
}
}
@@ -55,16 +55,7 @@ public class AppDbContext : IdentityDbContext<NexusUser>
entity.HasKey(e => e.ContentHash);
entity.HasIndex(e => e.ContentHash).IsUnique();
entity.HasIndex(e => e.TenantId);
if (Database.IsNpgsql())
{
// Configure vector column (768 dims) and HNSW index for cosine similarity
entity.Property(e => e.Embedding).HasColumnType("vector(768)");
entity.HasIndex(e => e.Embedding).HasMethod("hnsw").HasOperators("vector_cosine_ops");
}
else
{
entity.Ignore(e => e.Embedding);
}
entity.Ignore(e => e.Embedding);
});
modelBuilder.Entity<KnowledgeUnit>(entity =>
@@ -1,7 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Pgvector.EntityFrameworkCore;
namespace NexusReader.Data.Persistence;
@@ -38,7 +37,7 @@ public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
connectionString = "Host=localhost;Database=nexus_reader;Username=postgres;Password=postgres";
}
optionsBuilder.UseNpgsql(connectionString, x => x.UseVector());
optionsBuilder.UseNpgsql(connectionString);
return new AppDbContext(optionsBuilder.Options);
}
@@ -15,6 +15,7 @@ using Polly.Registry;
using Microsoft.Extensions.Options;
using NexusReader.Infrastructure.Configuration;
using Qdrant.Client;
using Qdrant.Client.Grpc;
using Neo4j.Driver;
namespace NexusReader.Infrastructure.Services;
@@ -285,6 +286,98 @@ public class KnowledgeService : IKnowledgeService
_logger.LogWarning("[KnowledgeService] Skipping invalid link {Source} -> {Target}: one or both units are missing.", linkDto.Source, linkDto.Target);
}
}
// Generate and upsert vectors to Qdrant in batch
var unitsToEmbed = packet.Units
.Where(u => !string.IsNullOrEmpty(u.Content))
.ToList();
if (unitsToEmbed.Any())
{
try
{
var contents = unitsToEmbed.Select(u => u.Content).ToList();
var embeddingResponse = await _retryPipeline.ExecuteAsync(async ct =>
await _embeddingGenerator.GenerateAsync(
contents,
new EmbeddingGenerationOptions { Dimensions = 768 },
cancellationToken: ct), cancellationToken);
var embeddings = embeddingResponse.ToList();
var points = new List<PointStruct>();
for (int i = 0; i < unitsToEmbed.Count; i++)
{
var unitDto = unitsToEmbed[i];
var vector = embeddings[i].Vector.ToArray();
var point = new PointStruct
{
Id = GetDeterministicGuid(unitDto.Id),
Vectors = vector,
Payload =
{
["content"] = unitDto.Content,
["type"] = unitDto.Type ?? string.Empty,
["tenantId"] = tenantId,
["ebookId"] = ebookId?.ToString() ?? string.Empty,
["metadataJson"] = JsonSerializer.Serialize(unitDto.Metadata)
}
};
points.Add(point);
}
if (points.Any())
{
await EnsureCollectionExistsAsync("knowledge_units", cancellationToken);
await _qdrantClient.UpsertAsync("knowledge_units", points, cancellationToken: cancellationToken);
_logger.LogInformation("[KnowledgeService] Successfully upserted {Count} points to Qdrant collection 'knowledge_units'.", points.Count);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "[KnowledgeService] Failed to generate and upsert embeddings for knowledge units to Qdrant.");
}
}
}
private async Task EnsureCollectionExistsAsync(string collectionName, CancellationToken cancellationToken = default)
{
try
{
var exists = await _qdrantClient.CollectionExistsAsync(collectionName, cancellationToken);
if (!exists)
{
_logger.LogInformation("[KnowledgeService] Creating Qdrant collection '{CollectionName}'...", collectionName);
await _qdrantClient.CreateCollectionAsync(
collectionName: collectionName,
vectorsConfig: new VectorParams
{
Size = 768,
Distance = Distance.Cosine
},
cancellationToken: cancellationToken
);
_logger.LogInformation("[KnowledgeService] Qdrant collection '{CollectionName}' created successfully.", collectionName);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "[KnowledgeService] Error ensuring Qdrant collection '{CollectionName}' exists.", collectionName);
}
}
private static Guid GetDeterministicGuid(string input)
{
if (Guid.TryParse(input, out var guid))
{
return guid;
}
using var md5 = System.Security.Cryptography.MD5.Create();
byte[] hash = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(input));
return new Guid(hash);
}
public async Task<Result<GroundednessResult>> VerifyGroundednessAsync(string answer, string context, string tenantId, CancellationToken cancellationToken = default)
@@ -354,6 +447,7 @@ public class KnowledgeService : IKnowledgeService
List<Qdrant.Client.Grpc.ScoredPoint> searchResult;
try
{
await EnsureCollectionExistsAsync("knowledge_units", cancellationToken);
var response = await _qdrantClient.SearchAsync(
collectionName: "knowledge_units",
vector: queryVector,
@@ -417,6 +511,7 @@ public class KnowledgeService : IKnowledgeService
List<Qdrant.Client.Grpc.ScoredPoint> searchResult;
try
{
await EnsureCollectionExistsAsync("knowledge_units", cancellationToken);
var response = await _qdrantClient.SearchAsync(
collectionName: "knowledge_units",
vector: queryVector,
@@ -602,6 +697,7 @@ public class KnowledgeService : IKnowledgeService
List<Qdrant.Client.Grpc.ScoredPoint> searchResult;
try
{
await EnsureCollectionExistsAsync("knowledge_units", cancellationToken);
var response = await _qdrantClient.SearchAsync(
collectionName: "knowledge_units",
vector: queryVector,
@@ -790,6 +886,16 @@ Strict Grounding Rules:
await dbContext.SemanticKnowledgeCache.ExecuteDeleteAsync(cancellationToken);
await dbContext.KnowledgeUnits.ExecuteDeleteAsync(cancellationToken);
await dbContext.KnowledgeUnitLinks.ExecuteDeleteAsync(cancellationToken);
try
{
await _qdrantClient.DeleteCollectionAsync("knowledge_units", cancellationToken: cancellationToken);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "[KnowledgeService] Failed to drop Qdrant collection 'knowledge_units' during cache clear.");
}
return Result.Ok();
}
catch (Exception ex)
+18
View File
@@ -8,4 +8,22 @@ public partial class App : Microsoft.Maui.Controls.Application
MainPage = new MainPage();
}
protected override Window CreateWindow(IActivationState? activationState)
{
var window = base.CreateWindow(activationState);
// Hook into native MAUI lifecycle events to cleanly flush and close Serilog buffers
window.Stopped += (s, e) =>
{
Serilog.Log.CloseAndFlush();
};
window.Destroying += (s, e) =>
{
Serilog.Log.CloseAndFlush();
};
return window;
}
}
@@ -0,0 +1,144 @@
using System.Net.Http.Headers;
using System.Threading;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NexusReader.Application.Abstractions.Services;
namespace NexusReader.Maui.Infrastructure.Identity;
/// <summary>
/// A secure HTTP message delegating handler for MAUI that automatically appends JWT tokens
/// to trusted origin requests and transparently refreshes expired tokens in a thread-safe manner.
/// </summary>
public class MobileAuthenticationHeaderHandler : DelegatingHandler
{
private readonly INativeStorageService _storageService;
private readonly IServiceProvider _serviceProvider;
private const string TokenKey = "nexus_auth_token";
private static readonly SemaphoreSlim _refreshSemaphore = new(1, 1);
public MobileAuthenticationHeaderHandler(INativeStorageService storageService, IServiceProvider serviceProvider)
{
_storageService = storageService;
_serviceProvider = serviceProvider;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var path = request.RequestUri?.AbsolutePath ?? "";
bool isAuthEndpoint = path.Contains("identity/login") ||
path.Contains("identity/register") ||
path.Contains("identity/refresh");
// Resolve configured API host dynamically to avoid hardcoded IP addresses
var config = _serviceProvider.GetRequiredService<IConfiguration>();
var apiBaseUrlString = config["ApiSettings:BaseUrl"];
string? apiHost = null;
if (!string.IsNullOrEmpty(apiBaseUrlString) && Uri.TryCreate(apiBaseUrlString, UriKind.Absolute, out var apiUri))
{
apiHost = apiUri.Host;
}
// In MAUI, since we only call our own local or staging APIs, we trust local IP/localhost/configured API host.
// We ensure we don't accidentally leak tokens to third-party endpoints.
bool isTrustedHost = request.RequestUri != null &&
(request.RequestUri.Host == "localhost" ||
request.RequestUri.Host == "127.0.0.1" ||
(apiHost != null && request.RequestUri.Host == apiHost) ||
request.RequestUri.Host.EndsWith("nexusreader.com")); // Or staging domains
string? originalToken = null;
if (!isAuthEndpoint && isTrustedHost)
{
var tokenResult = await _storageService.GetSecureString(TokenKey);
if (tokenResult.IsSuccess && !string.IsNullOrEmpty(tokenResult.Value))
{
originalToken = tokenResult.Value;
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", originalToken);
}
}
var response = await base.SendAsync(request, cancellationToken);
// Transparent JWT Auto-Refresh on 401 Unauthorized
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized && !isAuthEndpoint)
{
await _refreshSemaphore.WaitAsync(cancellationToken);
try
{
// Re-read token to verify if another concurrent request already refreshed it
var tokenResult = await _storageService.GetSecureString(TokenKey);
var currentToken = tokenResult.IsSuccess ? tokenResult.Value : null;
bool refreshed = false;
if (!string.IsNullOrEmpty(currentToken) && currentToken != originalToken)
{
refreshed = true;
}
else
{
using var scope = _serviceProvider.CreateScope();
var identityService = scope.ServiceProvider.GetRequiredService<IIdentityService>();
var refreshResult = await identityService.RefreshTokenAsync();
if (refreshResult.IsSuccess)
{
var newTokenResult = await _storageService.GetSecureString(TokenKey);
currentToken = newTokenResult.IsSuccess ? newTokenResult.Value : null;
refreshed = !string.IsNullOrEmpty(currentToken);
}
else
{
await identityService.LogoutAsync();
}
}
if (refreshed && !string.IsNullOrEmpty(currentToken))
{
var newRequest = await CloneHttpRequestMessageAsync(request);
newRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", currentToken);
return await base.SendAsync(newRequest, cancellationToken);
}
}
catch (Exception ex)
{
Serilog.Log.Error(ex, "[MobileAuthHandler] Automated token renewal failed");
}
finally
{
_refreshSemaphore.Release();
}
}
return response;
}
private async Task<HttpRequestMessage> CloneHttpRequestMessageAsync(HttpRequestMessage req)
{
var clone = new HttpRequestMessage(req.Method, req.RequestUri)
{
Version = req.Version
};
if (req.Content != null)
{
var ms = new System.IO.MemoryStream();
await req.Content.CopyToAsync(ms);
ms.Position = 0;
clone.Content = new StreamContent(ms);
foreach (var h in req.Content.Headers)
{
clone.Content.Headers.TryAddWithoutValidation(h.Key, h.Value);
}
}
foreach (var h in req.Headers)
{
clone.Headers.TryAddWithoutValidation(h.Key, h.Value);
}
return clone;
}
}
@@ -0,0 +1,53 @@
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
namespace NexusReader.Maui.Infrastructure.Logging;
/// <summary>
/// Lightweight bridge service that intercepts logs, console outputs, and uncaught exceptions
/// from the Blazor WebView/JS side, and routes them directly to Serilog under "BlazorWebView" context.
/// </summary>
public sealed class BlazorLoggingBridge
{
private readonly ILogger _logger;
public BlazorLoggingBridge(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger("BlazorWebView");
}
[JSInvokable("LogJsMessage")]
public void LogJsMessage(string level, string message, string? stackTrace = null)
{
if (string.IsNullOrWhiteSpace(message))
{
return;
}
switch (level.ToLowerInvariant())
{
case "error":
case "exception":
if (!string.IsNullOrWhiteSpace(stackTrace))
{
_logger.LogError("JS Unhandled Exception: {Message}\nStack Trace:\n{StackTrace}", message, stackTrace);
}
else
{
_logger.LogError("JS Error: {Message}", message);
}
break;
case "warning":
case "warn":
_logger.LogWarning("JS Warning: {Message}", message);
break;
case "info":
case "log":
default:
_logger.LogInformation("JS Log: {Message}", message);
break;
}
}
}
@@ -0,0 +1,106 @@
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Display;
namespace NexusReader.Maui.Infrastructure.Logging;
public static class SerilogConfiguration
{
private const string OutputTemplate =
"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [ThreadId: {ThreadId}] [{SourceContext}] {Message:lj}{NewLine}{Exception}";
public static MauiAppBuilder RegisterLogging(this MauiAppBuilder builder)
{
// 1. Ensure logs directory exists in secure sandbox
var logDir = Path.Combine(Microsoft.Maui.Storage.FileSystem.AppDataDirectory, "logs");
if (!Directory.Exists(logDir))
{
Directory.CreateDirectory(logDir);
}
var logPath = Path.Combine(logDir, "log-.txt");
// 2. Inject sandboxed log path dynamically into configuration provider
builder.Configuration["Serilog:WriteTo:0:Args:configure:0:Args:path"] = logPath;
// 3. Configure Serilog Logger Configuration using App Configuration settings
var loggerConfig = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.With(new ThreadIdEnricher());
// 4. Platform-specific and environment-specific sinks
#if ANDROID
// Direct Native Android Logcat Sink (JNI bindings for native diagnostics)
loggerConfig.WriteTo.Sink(
new AndroidLogcatSink(new MessageTemplateTextFormatter(OutputTemplate, null)),
restrictedToMinimumLevel: LogEventLevel.Debug);
#endif
// 5. Initialize the static Serilog Log
Log.Logger = loggerConfig.CreateLogger();
// 6. Connect Serilog to Microsoft.Extensions.Logging
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(dispose: true);
return builder;
}
}
/// <summary>
/// A custom self-contained thread enricher to avoid unnecessary NuGet packages.
/// </summary>
internal sealed class ThreadIdEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("ThreadId", Environment.CurrentManagedThreadId));
}
}
#if ANDROID
/// <summary>
/// A high-performance, direct Android Logcat Sink utilizing native Android APIs.
/// </summary>
internal sealed class AndroidLogcatSink : ILogEventSink
{
private readonly ITextFormatter _formatter;
private const string Tag = "NexusReader";
public AndroidLogcatSink(ITextFormatter formatter)
{
_formatter = formatter ?? throw new ArgumentNullException(nameof(formatter));
}
public void Emit(LogEvent logEvent)
{
using var writer = new StringWriter();
_formatter.Format(logEvent, writer);
var message = writer.ToString().Trim();
switch (logEvent.Level)
{
case LogEventLevel.Verbose:
Android.Util.Log.Verbose(Tag, message);
break;
case LogEventLevel.Debug:
Android.Util.Log.Debug(Tag, message);
break;
case LogEventLevel.Information:
Android.Util.Log.Info(Tag, message);
break;
case LogEventLevel.Warning:
Android.Util.Log.Warn(Tag, message);
break;
case LogEventLevel.Error:
Android.Util.Log.Error(Tag, message);
break;
case LogEventLevel.Fatal:
Android.Util.Log.Wtf(Tag, message);
break;
}
}
}
#endif
+21
View File
@@ -1,5 +1,8 @@
@using Microsoft.AspNetCore.Components.Routing
@using NexusReader.UI.Shared
@using NexusReader.Maui.Infrastructure.Logging
@inject IJSRuntime JSRuntime
@inject BlazorLoggingBridge LoggingBridge
<Router AppAssembly="@typeof(NexusReader.UI.Shared._Imports).Assembly">
<Found Context="routeData">
@@ -16,3 +19,21 @@
</LayoutView>
</NotFound>
</Router>
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
try
{
var dotNetRef = DotNetObjectReference.Create(LoggingBridge);
await JSRuntime.InvokeVoidAsync("NexusLogging.initializeBridge", dotNetRef);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[SerilogBridge] Failed to initialize Blazor/JS Bridge: {ex}");
}
}
}
}
+29 -4
View File
@@ -1,9 +1,13 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Infrastructure.Mobile.Services;
using NexusReader.UI.Shared.Services;
using NexusReader.Application;
using MediatR;
using NexusReader.Maui.Infrastructure.Logging;
using NexusReader.Maui.Infrastructure.Identity;
namespace NexusReader.Maui;
@@ -14,16 +18,30 @@ public static class MauiProgram
try
{
var builder = MauiApp.CreateBuilder();
// Load embedded appsettings.json configuration
var assembly = typeof(App).Assembly;
using (var stream = assembly.GetManifestResourceStream("NexusReader.Maui.appsettings.json"))
{
if (stream != null)
{
((IConfigurationBuilder)builder.Configuration).AddJsonStream(stream);
}
}
builder
.UseMauiApp<App>();
.UseMauiApp<App>()
.RegisterLogging();
builder.Services.AddMauiBlazorWebView();
#if DEBUG
builder.Services.AddBlazorWebViewDeveloperTools();
builder.Logging.AddDebug();
#endif
// Interception bridge for JS/Blazor WebView logs
builder.Services.AddSingleton<BlazorLoggingBridge>();
// Minimal Infrastructure
builder.Services.AddSingleton<IPlatformService, MauiPlatformService>();
builder.Services.AddSingleton<INativeStorageService, MauiStorageService>();
@@ -34,8 +52,15 @@ public static class MauiProgram
sp.GetRequiredService<NexusAuthenticationStateProvider>());
builder.Services.AddAuthorizationCore();
// Basic Network
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("http://10.0.2.2:5000") });
// Basic Network with Secure Token Handler
builder.Services.AddTransient<MobileAuthenticationHeaderHandler>();
builder.Services.AddHttpClient("NexusAPI", client =>
{
var apiBaseUrl = builder.Configuration["ApiSettings:BaseUrl"] ?? "http://localhost:5000";
client.BaseAddress = new Uri(apiBaseUrl);
}).AddHttpMessageHandler<MobileAuthenticationHeaderHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("NexusAPI"));
// UI State
builder.Services.AddScoped<IThemeService, ThemeService>();
@@ -27,6 +27,14 @@
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="10.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebView.Maui" Version="10.0.20" />
<PackageReference Include="Microsoft.Maui.Essentials" Version="10.0.20" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.Async" Version="2.1.0" />
<PackageReference Include="Serilog.Sinks.Debug" Version="3.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.0" />
</ItemGroup>
<ItemGroup>
@@ -34,4 +42,8 @@
<ProjectReference Include="..\NexusReader.Infrastructure.Mobile\NexusReader.Infrastructure.Mobile.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appsettings.json" />
</ItemGroup>
</Project>
+48
View File
@@ -0,0 +1,48 @@
{
"ApiSettings": {
"BaseUrl": "https://localhost:5000"
},
"Serilog": {
"Using": [
"Serilog.Sinks.File",
"Serilog.Sinks.Debug",
"Serilog.Sinks.Async"
],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "File",
"Args": {
"path": "LOG_PATH_PLACEHOLDER",
"rollingInterval": "Day",
"retainedFileCountLimit": 7,
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [ThreadId: {ThreadId}] [{SourceContext}] {Message:lj}{NewLine}{Exception}",
"shared": true
}
}
]
}
},
{
"Name": "Debug",
"Args": {
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [ThreadId: {ThreadId}] [{SourceContext}] {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [
"FromLogContext"
]
}
}
+46
View File
@@ -26,7 +26,53 @@
<script src="_framework/blazor.webview.js" autostart="false"></script>
<script src="_content/NexusReader.UI.Shared/js/d3.v7.min.js"></script>
<script>
window.NexusLogging = {
initializeBridge: function (dotNetHelper) {
const originalLog = console.log;
const originalWarn = console.warn;
const originalError = console.error;
console.log = function (...args) {
originalLog.apply(console, args);
try {
dotNetHelper.invokeMethodAsync('LogJsMessage', 'info', args.map(x => typeof x === 'object' ? JSON.stringify(x) : String(x)).join(' '));
} catch (e) {}
};
console.warn = function (...args) {
originalWarn.apply(console, args);
try {
dotNetHelper.invokeMethodAsync('LogJsMessage', 'warn', args.map(x => typeof x === 'object' ? JSON.stringify(x) : String(x)).join(' '));
} catch (e) {}
};
console.error = function (...args) {
originalError.apply(console, args);
try {
dotNetHelper.invokeMethodAsync('LogJsMessage', 'error', args.map(x => typeof x === 'object' ? JSON.stringify(x) : String(x)).join(' '));
} catch (e) {}
};
window.onerror = function (message, source, lineno, colno, error) {
const stack = error ? error.stack : '';
try {
dotNetHelper.invokeMethodAsync('LogJsMessage', 'error', `${message} at ${source}:${lineno}:${colno}`, stack);
} catch (e) {}
return false;
};
window.addEventListener('unhandledrejection', function (event) {
const reason = event.reason;
const message = reason instanceof Error ? reason.message : String(reason);
const stack = reason instanceof Error ? reason.stack : '';
try {
dotNetHelper.invokeMethodAsync('LogJsMessage', 'error', `Unhandled Promise Rejection: ${message}`, stack);
} catch (e) {}
});
}
};
</script>
</body>
</html>
@@ -1,39 +1,334 @@
@namespace NexusReader.UI.Shared.Components.Atoms
@using System.Text.RegularExpressions
@using NexusReader.Application.DTOs.AI
@inject IKnowledgeService KnowledgeService
@inject IReaderNavigationService NavService
@inject IReaderInteractionService InteractionService
@inject NavigationManager NavManager
@inject AuthenticationStateProvider AuthStateProvider
@inject ILogger<NexusSearchBox> Logger
@implements IDisposable
<div class="nexus-search-container @(IsActive ? "active" : "")">
<div class="nexus-search-container @(IsFocused ? "focused" : "") @(HasResults ? "has-results" : "")" @onfocusin="HandleFocusIn" @onfocusout="HandleFocusOut">
<div class="search-wrapper">
<i class="nexus-icon @IconClass"></i>
<input type="text"
@bind="SearchValue"
@bind:event="oninput"
@onkeypress="HandleKeyPress"
placeholder="@Placeholder"
<div class="search-icon-container">
@if (_isLoading)
{
<div class="neon-spinner"></div>
}
else
{
<i class="nexus-icon bi bi-search"></i>
}
</div>
<input type="text"
value="@SearchValue"
@oninput="HandleInput"
@onkeydown="HandleKeyDown"
placeholder="@Placeholder"
class="nexus-search-input" />
<div class="ai-status-indicator" title="Aktywny silnik AI biblioteki">
<span class="ai-pulse-dot"></span>
</div>
@if (!string.IsNullOrEmpty(SearchValue))
{
<button class="clear-btn" @onclick="ClearSearch">×</button>
<button type="button" class="clear-btn" @onclick="ClearSearch" aria-label="Wyczyść wyszukiwanie">×</button>
}
</div>
@if (_isDropdownOpen && (!string.IsNullOrEmpty(SearchValue) || _isLoading || _results.Any() || _searchError != null))
{
<div class="search-dropdown glass-panel">
@if (_isLoading)
{
<div class="dropdown-state-container">
<div class="neon-spinner-large"></div>
<span class="state-text">Analizowanie biblioteki semantycznej...</span>
</div>
}
else if (_searchError != null)
{
<div class="dropdown-state-container error">
<i class="bi bi-exclamation-triangle-fill error-icon"></i>
<span class="state-text">@_searchError</span>
</div>
}
else if (_results.Any())
{
<div class="dropdown-results-list">
@foreach (var result in _results)
{
<div class="result-card" @onclick="() => HandleResultClick(result)">
<div class="result-header">
<span class="relevance-badge">@(Math.Round(result.RelevanceScore * 100))% Trafności</span>
@if (!string.IsNullOrEmpty(result.SourceBookTitle))
{
<span class="source-title" title="@result.SourceBookTitle">w <strong>@result.SourceBookTitle</strong></span>
}
</div>
<div class="result-snippet">
@((MarkupString)HighlightQueryWords(result.Snippet, SearchValue))
</div>
</div>
}
</div>
}
else if (!string.IsNullOrEmpty(SearchValue))
{
<div class="dropdown-state-container empty">
<i class="bi bi-search empty-icon"></i>
<span class="state-text">Brak wyników dla zapytania.</span>
</div>
}
</div>
}
</div>
@code {
[Parameter] public string Placeholder { get; set; } = "Search your library...";
[Parameter] public string IconClass { get; set; } = "bi bi-search";
[Parameter] public string Placeholder { get; set; } = "Zapytaj swoją bibliotekę AI...";
[Parameter] public EventCallback<string> OnSearch { get; set; }
private string SearchValue { get; set; } = string.Empty;
private bool IsActive => !string.IsNullOrEmpty(SearchValue);
[Parameter] public int Limit { get; set; } = 5;
private async Task HandleKeyPress(KeyboardEventArgs e)
private string SearchValue { get; set; } = string.Empty;
private bool IsFocused { get; set; }
private bool HasResults => _results.Any() && _isDropdownOpen;
private List<SemanticSearchResultDto> _results = new();
private bool _isLoading;
private string? _searchError;
private bool _isDropdownOpen;
private CancellationTokenSource? _searchCts;
private async Task HandleInput(ChangeEventArgs e)
{
if (e.Key == "Enter")
SearchValue = e.Value?.ToString() ?? string.Empty;
_searchError = null;
if (string.IsNullOrWhiteSpace(SearchValue))
{
await OnSearch.InvokeAsync(SearchValue);
_results.Clear();
_isDropdownOpen = false;
return;
}
_isDropdownOpen = true;
// Cancel previous search in-flight
_searchCts?.Cancel();
_searchCts?.Dispose();
_searchCts = new CancellationTokenSource();
var token = _searchCts.Token;
try
{
// Debounce for 300ms
await Task.Delay(300, token);
await PerformSearchAsync(token);
}
catch (TaskCanceledException)
{
// Typing continued, search cancelled
}
}
private async Task PerformSearchAsync(CancellationToken token)
{
_isLoading = true;
_searchError = null;
await InvokeAsync(StateHasChanged);
try
{
var authState = await AuthStateProvider.GetAuthenticationStateAsync();
var tenantId = authState.User.FindFirst("TenantId")?.Value ?? "global";
var result = await KnowledgeService.SearchLibrarySemanticallyAsync(SearchValue, tenantId, Limit, token);
if (token.IsCancellationRequested) return;
if (result.IsSuccess)
{
_results = result.Value ?? new List<SemanticSearchResultDto>();
_searchError = null;
}
else
{
_results.Clear();
_searchError = result.Errors.FirstOrDefault()?.Message ?? "Nie udało się wykonać wyszukiwania.";
Logger.LogWarning("Semantic search returned errors: {Errors}", string.Join(", ", result.Errors.Select(e => e.Message)));
}
}
catch (Exception ex)
{
if (!token.IsCancellationRequested)
{
_results.Clear();
_searchError = "Wystąpił nieoczekiwany błąd podczas wyszukiwania.";
Logger.LogError(ex, "Unexpected error during semantic search for query: {Query}", SearchValue);
}
}
finally
{
if (!token.IsCancellationRequested)
{
_isLoading = false;
await InvokeAsync(StateHasChanged);
}
}
}
private async Task HandleResultClick(SemanticSearchResultDto result)
{
_isDropdownOpen = false;
// 1. Resolve Ebook ID
Guid? ebookId = null;
if (result.Metadata != null)
{
foreach (var key in new[] { "ebookId", "ebook_id", "EbookId", "Ebook_Id" })
{
if (result.Metadata.TryGetValue(key, out var val) && val != null)
{
if (Guid.TryParse(val.ToString(), out var g))
{
ebookId = g;
break;
}
}
}
}
if (ebookId == null || ebookId == Guid.Empty)
{
ebookId = NavService.CurrentEbookId;
}
if (ebookId == null || ebookId == Guid.Empty)
{
Logger.LogWarning("Could not resolve ebook ID from search result metadata.");
return;
}
// 2. Resolve Chapter Index
int chapterIndex = 0;
if (result.Metadata != null)
{
foreach (var key in new[] { "chapterIndex", "chapter_index", "ChapterIndex", "chapter" })
{
if (result.Metadata.TryGetValue(key, out var val) && val != null)
{
if (int.TryParse(val.ToString(), out var parsedInt))
{
chapterIndex = parsedInt;
break;
}
}
}
}
// 3. Resolve Block ID
string? blockId = null;
if (result.Metadata != null)
{
foreach (var key in new[] { "blockId", "block_id", "BlockId", "nodeId", "node_id", "NodeId", "id" })
{
if (result.Metadata.TryGetValue(key, out var val) && val != null)
{
blockId = val.ToString();
break;
}
}
}
if (string.IsNullOrEmpty(blockId))
{
blockId = result.ContentHash;
}
// 4. Set pending scroll and navigate
NavService.PendingScrollBlockId = blockId;
if (NavService.CurrentEbookId == ebookId.Value && NavService.CurrentChapterIndex == chapterIndex)
{
// Same chapter - scroll and highlight immediately
if (!string.IsNullOrEmpty(blockId))
{
await InteractionService.RequestScrollToBlock(blockId);
await InteractionService.RequestHighlightBlock(blockId);
}
}
else
{
// Different chapter or book - perform routing
NavService.SetBook(ebookId.Value, chapterIndex);
NavManager.NavigateTo($"/reader/{ebookId.Value}?chapter={chapterIndex}");
}
// Invoke the optional callback for parent components
await OnSearch.InvokeAsync(SearchValue);
}
private void HandleKeyDown(KeyboardEventArgs e)
{
if (e.Key == "Escape")
{
_isDropdownOpen = false;
}
}
private void HandleFocusIn()
{
IsFocused = true;
_isDropdownOpen = true;
}
private async Task HandleFocusOut()
{
IsFocused = false;
// Delay slightly to allow click handlers on result cards to execute
await Task.Delay(200);
_isDropdownOpen = false;
StateHasChanged();
}
private void ClearSearch()
{
SearchValue = string.Empty;
_results.Clear();
_searchError = null;
_isDropdownOpen = false;
}
private string HighlightQueryWords(string text, string query)
{
if (string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(query))
return text;
var words = query.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Where(w => w.Length > 2)
.Select(Regex.Escape);
if (!words.Any())
return text;
var pattern = "(" + string.Join("|", words) + ")";
try
{
return Regex.Replace(text, pattern, "<mark class=\"search-highlight\">$1</mark>", RegexOptions.IgnoreCase);
}
catch
{
return text;
}
}
public void Dispose()
{
_searchCts?.Cancel();
_searchCts?.Dispose();
}
}
@@ -1,57 +1,309 @@
.nexus-search-container {
position: relative;
width: 100%;
max-width: 500px;
margin: 1rem auto;
transition: all 0.3s ease;
max-width: 600px;
margin: 1.5rem auto;
font-family: var(--nexus-font-sans), 'Inter', sans-serif;
z-index: 1000;
}
.search-wrapper {
position: relative;
display: flex;
align-items: center;
background: var(--nexus-card, #141414);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 0.5rem 1rem;
transition: border-color 0.3s ease, box-shadow 0.3s ease;
background: rgba(255, 255, 255, 0.03);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 14px;
padding: 0.65rem 1.1rem;
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
.nexus-search-container.active .search-wrapper,
.search-wrapper:focus-within {
border-color: var(--nexus-neon, #00ff99);
box-shadow: 0 0 15px rgba(0, 255, 153, 0.2);
/* Focused state: glowing neon border matching other dashboard components */
.nexus-search-container.focused .search-wrapper {
background: rgba(255, 255, 255, 0.05);
border-color: var(--nexus-neon);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5), 0 0 15px rgba(0, 255, 153, 0.25);
}
.search-icon-container {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
margin-right: 0.85rem;
}
.nexus-icon {
color: rgba(255, 255, 255, 0.5);
margin-right: 0.75rem;
font-size: 1.1rem;
color: rgba(255, 255, 255, 0.45);
font-size: 1.25rem;
transition: color 0.3s ease;
}
.nexus-search-container.focused .nexus-icon {
color: var(--nexus-neon);
}
.nexus-search-input {
flex: 1;
background: transparent;
border: none;
color: white;
font-family: 'Inter', sans-serif;
font-size: 0.95rem;
color: #ffffff;
font-size: 1rem;
font-weight: 400;
outline: none;
padding: 0;
width: 100%;
}
.nexus-search-input::placeholder {
color: rgba(255, 255, 255, 0.3);
color: rgba(255, 255, 255, 0.35);
font-style: italic;
transition: color 0.3s ease;
}
.nexus-search-container.focused .nexus-search-input::placeholder {
color: rgba(255, 255, 255, 0.5);
}
/* Pulsing neon-green AI status indicator */
.ai-status-indicator {
display: flex;
align-items: center;
margin: 0 0.75rem;
}
.ai-pulse-dot {
width: 8px;
height: 8px;
background-color: var(--nexus-neon);
border-radius: 50%;
display: inline-block;
position: relative;
box-shadow: 0 0 8px var(--nexus-neon);
}
.ai-pulse-dot::after {
content: '';
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: var(--nexus-neon);
border-radius: 50%;
z-index: -1;
animation: pulse 2s infinite ease-in-out;
}
.clear-btn {
background: transparent;
border: none;
color: rgba(255, 255, 255, 0.4);
font-size: 1.2rem;
font-size: 1.5rem;
line-height: 1;
cursor: pointer;
padding: 0 0.5rem;
transition: color 0.2s ease;
padding: 0 0.25rem;
margin-left: 0.5rem;
transition: color 0.2s ease, transform 0.2s ease;
}
.clear-btn:hover {
color: var(--nexus-neon, #00ff99);
color: #ff3b30;
transform: scale(1.1);
}
/* Frosted glass results container */
.search-dropdown {
position: absolute;
top: calc(100% + 8px);
left: 0;
right: 0;
background: rgba(18, 18, 18, 0.9);
backdrop-filter: blur(20px) saturate(160%);
-webkit-backdrop-filter: blur(20px) saturate(160%);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 14px;
box-shadow: 0 12px 36px rgba(0, 0, 0, 0.6), 0 0 20px rgba(0, 255, 153, 0.05);
max-height: 420px;
overflow-y: auto;
overflow-x: hidden;
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.15) transparent;
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
animation: slideDown 0.25s cubic-bezier(0.16, 1, 0.3, 1);
}
.search-dropdown::-webkit-scrollbar {
width: 6px;
}
.search-dropdown::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
}
.search-dropdown::-webkit-scrollbar-thumb:hover {
background: var(--nexus-neon);
}
/* In-flight spinners */
.neon-spinner {
width: 16px;
height: 16px;
border: 2px solid rgba(0, 255, 153, 0.15);
border-top: 2px solid var(--nexus-neon);
border-radius: 50%;
animation: spin 0.75s linear infinite;
}
.neon-spinner-large {
width: 32px;
height: 32px;
border: 3px solid rgba(255, 255, 255, 0.05);
border-top: 3px solid var(--nexus-neon);
border-radius: 50%;
animation: spin 0.8s cubic-bezier(0.5, 0.1, 0.5, 0.9) infinite;
margin-bottom: 1rem;
}
.dropdown-state-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2.5rem 1.5rem;
text-align: center;
}
.state-text {
font-size: 0.95rem;
color: rgba(255, 255, 255, 0.65);
font-weight: 300;
}
.error-icon, .empty-icon {
font-size: 2rem;
margin-bottom: 0.75rem;
}
.error-icon {
color: #ff3b30;
text-shadow: 0 0 10px rgba(255, 59, 48, 0.4);
}
.empty-icon {
color: rgba(255, 255, 255, 0.2);
}
/* Results Cards list */
.dropdown-results-list {
padding: 0.5rem;
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.result-card {
padding: 0.95rem 1.1rem;
background: rgba(255, 255, 255, 0.02);
border: 1px solid rgba(255, 255, 255, 0.04);
border-radius: 10px;
cursor: pointer;
transition: all 0.2s ease;
}
.result-card:hover {
background: rgba(0, 255, 153, 0.05);
border-color: rgba(0, 255, 153, 0.2);
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
.result-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 0.5rem;
font-size: 0.8rem;
}
.relevance-badge {
background: rgba(0, 255, 153, 0.1);
color: var(--nexus-neon);
border: 1px solid rgba(0, 255, 153, 0.25);
border-radius: 6px;
padding: 0.15rem 0.45rem;
font-weight: 600;
letter-spacing: 0.02em;
text-shadow: 0 0 4px rgba(0, 255, 153, 0.25);
}
.source-title {
color: rgba(255, 255, 255, 0.5);
max-width: 60%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.source-title strong {
color: rgba(255, 255, 255, 0.85);
}
.result-snippet {
font-size: 0.88rem;
line-height: 1.45;
color: rgba(255, 255, 255, 0.78);
font-weight: 300;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
/* Markup highlights */
::deep mark.search-highlight {
background: rgba(0, 255, 153, 0.2);
color: var(--nexus-neon);
border-bottom: 1px solid var(--nexus-neon);
padding: 0.05rem 0.15rem;
border-radius: 3px;
font-weight: 500;
}
/* Animations */
@keyframes pulse {
0% {
transform: scale(1);
box-shadow: 0 0 0 0 rgba(0, 255, 153, 0.7);
}
70% {
transform: scale(1.6);
box-shadow: 0 0 0 6px rgba(0, 255, 153, 0);
}
100% {
transform: scale(1);
box-shadow: 0 0 0 0 rgba(0, 255, 153, 0);
}
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@@ -247,6 +247,17 @@
_isLoadingChapter = false;
StateHasChanged();
if (result.IsSuccess && !string.IsNullOrEmpty(NavigationService.PendingScrollBlockId))
{
var targetBlockId = NavigationService.PendingScrollBlockId;
NavigationService.PendingScrollBlockId = null; // Clear it to prevent multiple scrolls
// Give the browser slightly more than one frame to render the loaded blocks
await Task.Delay(150);
await ScrollToNodeAsync(targetBlockId);
await InteractionService.RequestHighlightBlock(targetBlockId);
}
}
public async Task ScrollToNodeAsync(string id)
@@ -0,0 +1,370 @@
@page "/serilog-demo"
@inject ILogger<SerilogDemo> Logger
@inject IJSRuntime JSRuntime
<div class="serilog-demo-container">
<div class="header-card">
<div class="header-content">
<NexusIcon Name="cpu" Size="36" Class="header-icon" />
<div class="header-text">
<h1>Serilog Logging Infrastructure</h1>
<p class="subtitle">Production-grade diagnostic pipeline for unified native & web logs</p>
</div>
</div>
<div class="status-badge">
<span class="status-dot green"></span>
<span class="status-text">Pipeline Active</span>
</div>
</div>
<div class="demo-grid">
<!-- Native .NET Logging Panel -->
<div class="control-card">
<div class="card-header">
<NexusIcon Name="terminal" Size="20" Class="card-icon" />
<h2>Native .NET Logs (C#)</h2>
</div>
<p class="card-desc">Trigger structured C# logs using Dependency Injected ILogger.</p>
<div class="btn-group">
<button class="btn btn-info" @onclick="LogInfo">
<NexusIcon Name="info" Size="16" />
Log Info
</button>
<button class="btn btn-warning" @onclick="LogWarning">
<NexusIcon Name="alert-triangle" Size="16" />
Log Warning
</button>
<button class="btn btn-error" @onclick="LogError">
<NexusIcon Name="x-circle" Size="16" />
Log Error Exception
</button>
</div>
</div>
<!-- Blazor / JS Interop Bridge Panel -->
<div class="control-card">
<div class="card-header">
<NexusIcon Name="globe" Size="20" Class="card-icon js-icon" />
<h2>Blazor / JS WebView Logs</h2>
</div>
<p class="card-desc">Trigger logs from JavaScript to verify the interop error capture bridge.</p>
<div class="btn-group">
<button class="btn btn-js-info" @onclick="TriggerJsLog">
<NexusIcon Name="message-square" Size="16" />
Trigger console.log()
</button>
<button class="btn btn-js-error" @onclick="TriggerJsException">
<NexusIcon Name="zap" Size="16" />
Trigger JS Exception
</button>
</div>
</div>
</div>
<!-- Active Log Config Panel -->
<div class="config-card">
<div class="card-header">
<NexusIcon Name="settings" Size="20" Class="card-icon" />
<h2>Pipeline Diagnostics</h2>
</div>
<div class="config-grid">
<div class="config-item">
<span class="label">Rolling Daily File Sandbox Path</span>
<span class="value code-value">AppDataDirectory/logs/log-*.txt</span>
</div>
<div class="config-item">
<span class="label">Active Configuration Provider</span>
<span class="value">Serilog.Settings.Configuration (appsettings.json)</span>
</div>
<div class="config-item">
<span class="label">Native Apple Console Sink</span>
<span class="value">Serilog.Sinks.Debug (conditional compilation)</span>
</div>
<div class="config-item">
<span class="label">Native Android Logcat Sink</span>
<span class="value">AndroidLogcatSink (direct JNI bindings)</span>
</div>
</div>
</div>
</div>
<style>
.serilog-demo-container {
padding: 2rem;
max-width: 1200px;
margin: 0 auto;
color: #e2e8f0;
font-family: 'Inter', system-ui, -apple-system, sans-serif;
}
.header-card {
display: flex;
justify-content: space-between;
align-items: center;
background: linear-gradient(135deg, rgba(30, 41, 59, 0.7) 0%, rgba(15, 23, 42, 0.8) 100%);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 16px;
padding: 2rem;
margin-bottom: 2rem;
backdrop-filter: blur(12px);
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
}
.header-content {
display: flex;
align-items: center;
gap: 1.5rem;
}
.header-icon {
color: #6366f1;
filter: drop-shadow(0 0 8px rgba(99, 102, 241, 0.5));
}
.header-text h1 {
font-size: 1.8rem;
font-weight: 700;
margin: 0;
background: linear-gradient(to right, #ffffff, #94a3b8);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.subtitle {
margin: 0.25rem 0 0 0;
color: #94a3b8;
font-size: 0.95rem;
}
.status-badge {
display: flex;
align-items: center;
gap: 0.5rem;
background: rgba(16, 185, 129, 0.1);
border: 1px solid rgba(16, 185, 129, 0.2);
padding: 0.5rem 1rem;
border-radius: 9999px;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.status-dot.green {
background-color: #10b981;
box-shadow: 0 0 8px #10b981;
}
.status-text {
font-size: 0.85rem;
font-weight: 600;
color: #10b981;
}
.demo-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
margin-bottom: 2rem;
}
@@media (max-width: 768px) {
.demo-grid {
grid-template-columns: 1fr;
}
}
.control-card {
background: rgba(30, 41, 59, 0.45);
border: 1px solid rgba(255, 255, 255, 0.05);
border-radius: 16px;
padding: 2rem;
backdrop-filter: blur(8px);
}
.card-header {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1rem;
}
.card-icon {
color: #6366f1;
}
.js-icon {
color: #eab308;
}
.card-header h2 {
font-size: 1.25rem;
font-weight: 600;
margin: 0;
}
.card-desc {
color: #94a3b8;
font-size: 0.9rem;
margin-bottom: 1.5rem;
line-height: 1.5;
}
.btn-group {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.btn {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1.25rem;
border-radius: 8px;
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
border: none;
}
.btn-info {
background-color: rgba(99, 102, 241, 0.1);
color: #818cf8;
border: 1px solid rgba(99, 102, 241, 0.2);
}
.btn-info:hover {
background-color: #6366f1;
color: white;
}
.btn-warning {
background-color: rgba(245, 158, 11, 0.1);
color: #fbbf24;
border: 1px solid rgba(245, 158, 11, 0.2);
}
.btn-warning:hover {
background-color: #f59e0b;
color: white;
}
.btn-error {
background-color: rgba(239, 68, 68, 0.1);
color: #f87171;
border: 1px solid rgba(239, 68, 68, 0.2);
}
.btn-error:hover {
background-color: #ef4444;
color: white;
}
.btn-js-info {
background-color: rgba(234, 179, 8, 0.1);
color: #fef08a;
border: 1px solid rgba(234, 179, 8, 0.2);
}
.btn-js-info:hover {
background-color: #eab308;
color: #0f172a;
}
.btn-js-error {
background-color: rgba(236, 72, 153, 0.1);
color: #fbcfe8;
border: 1px solid rgba(236, 72, 153, 0.2);
}
.btn-js-error:hover {
background-color: #ec4899;
color: white;
}
.config-card {
background: rgba(15, 23, 42, 0.5);
border: 1px solid rgba(255, 255, 255, 0.05);
border-radius: 16px;
padding: 2rem;
}
.config-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.5rem;
margin-top: 1.5rem;
}
@@media (max-width: 768px) {
.config-grid {
grid-template-columns: 1fr;
}
}
.config-item {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.config-item .label {
font-size: 0.8rem;
color: #64748b;
text-transform: uppercase;
letter-spacing: 0.05em;
font-weight: 600;
}
.config-item .value {
font-size: 0.95rem;
color: #cbd5e1;
}
.code-value {
font-family: 'Fira Code', 'Courier New', Courier, monospace;
background: rgba(0, 0, 0, 0.2);
padding: 0.25rem 0.5rem;
border-radius: 4px;
border: 1px solid rgba(255, 255, 255, 0.05);
word-break: break-all;
}
</style>
@code {
private void LogInfo()
{
Logger.LogInformation("Structured native log triggered by user from SerilogDemo. Button: LogInfo");
}
private void LogWarning()
{
Logger.LogWarning("Potential warning log triggered from Blazor razor component at {Time}", DateTime.UtcNow);
}
private void LogError()
{
try
{
throw new InvalidOperationException("Simulated native C# operation exception triggered in Diagnostic dashboard.");
}
catch (Exception ex)
{
Logger.LogError(ex, "Captured exception successfully in native Serilog pipeline!");
}
}
private async Task TriggerJsLog()
{
await JSRuntime.InvokeVoidAsync("console.log", "Intercepted JS console statement from Blazor WebView interop trigger!");
}
private async Task TriggerJsException()
{
await JSRuntime.InvokeVoidAsync("eval", "throw new Error('Simulated runtime JS Exception triggered from Blazor UI button click!');");
}
}
+50 -3
View File
@@ -2,16 +2,63 @@
@attribute [Authorize]
<div class="settings-page">
<h1>Ustawienia</h1>
<p>Konfiguracja Twojego konta i preferencji czytania.</p>
<h1>Settings</h1>
<p>Configure your account and application preferences.</p>
<div class="settings-section">
<h2>Diagnostics & System Logs</h2>
<p>Inspect native logging infrastructure, trigger custom logs, and trace WebView errors.</p>
<a class="diag-btn" href="/serilog-demo">
<NexusIcon Name="cpu" Size="16" />
Open Serilog Diagnostics Dashboard
</a>
</div>
</div>
<style>
.settings-page {
padding: 2rem;
color: #e2e8f0;
font-family: 'Inter', sans-serif;
}
h1 {
margin-bottom: 1rem;
margin-bottom: 0.5rem;
color: #fff;
}
h2 {
margin-top: 2rem;
font-size: 1.2rem;
color: #fff;
margin-bottom: 0.5rem;
}
.settings-section {
background: rgba(30, 41, 59, 0.45);
border: 1px solid rgba(255, 255, 255, 0.05);
padding: 1.5rem;
border-radius: 12px;
margin-top: 1.5rem;
}
.settings-section p {
color: #94a3b8;
font-size: 0.9rem;
margin-bottom: 1.25rem;
}
.diag-btn {
display: inline-flex;
align-items: center;
gap: 0.5rem;
background: rgba(99, 102, 241, 0.1);
color: #818cf8;
border: 1px solid rgba(99, 102, 241, 0.2);
padding: 0.75rem 1.25rem;
border-radius: 8px;
text-decoration: none;
font-size: 0.85rem;
font-weight: 600;
transition: all 0.2s ease;
}
.diag-btn:hover {
background: #6366f1;
color: white;
}
</style>
@@ -6,6 +6,7 @@ public interface IReaderNavigationService
int CurrentChapterIndex { get; }
int TotalChapters { get; }
string ChapterTitle { get; }
string? PendingScrollBlockId { get; set; }
event Func<Task>? OnNavigationChanged;
@@ -15,6 +15,7 @@ public class ReaderNavigationService : IReaderNavigationService
public int CurrentChapterIndex { get; private set; } = 0;
public int TotalChapters { get; private set; } = 1;
public string ChapterTitle { get; private set; } = "Loading...";
public string? PendingScrollBlockId { get; set; }
public event Func<Task>? OnNavigationChanged;
@@ -116,11 +116,8 @@ public class QueryTests : IDisposable
public async Task SearchLibrarySemanticallyQuery_WithEmptyQueryText_ReturnsFailure()
{
// Arrange
var handler = new SearchLibrarySemanticallyQueryHandler(
_embeddingGeneratorMock.Object,
_dbContextFactoryMock.Object,
_pipelineProviderMock.Object,
_mapperMock.Object);
var knowledgeServiceMock = new Mock<IKnowledgeService>();
var handler = new SearchLibrarySemanticallyQueryHandler(knowledgeServiceMock.Object);
var query = new SearchLibrarySemanticallyQuery("", "tenant-123");
// Act
@@ -132,39 +129,38 @@ public class QueryTests : IDisposable
}
[Fact]
public async Task SearchLibrarySemanticallyQuery_WithValidQuery_GeneratesEmbeddingAndQueriesDatabase()
public async Task SearchLibrarySemanticallyQuery_WithValidQuery_CallsKnowledgeService()
{
// Arrange
var queryText = "test query";
var tenantId = "tenant-123";
var expectedResponse = new List<SemanticSearchResultDto>
{
new SemanticSearchResultDto
{
Snippet = "Matched content",
RelevanceScore = 0.95f,
SourceBookTitle = "Test Book"
}
};
var mockEmbedding = new Embedding<float>(new float[768]);
var mockResponse = new GeneratedEmbeddings<Embedding<float>>(new[] { mockEmbedding });
_embeddingGeneratorMock.Setup(g => g.GenerateAsync(
It.Is<IEnumerable<string>>(s => s.Contains(queryText)),
It.IsAny<EmbeddingGenerationOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(mockResponse);
var handler = new SearchLibrarySemanticallyQueryHandler(
_embeddingGeneratorMock.Object,
_dbContextFactoryMock.Object,
_pipelineProviderMock.Object,
_mapperMock.Object);
var knowledgeServiceMock = new Mock<IKnowledgeService>();
knowledgeServiceMock.Setup(s => s.SearchLibrarySemanticallyAsync(queryText, tenantId, 5, It.IsAny<CancellationToken>()))
.ReturnsAsync(Result.Ok(expectedResponse));
var handler = new SearchLibrarySemanticallyQueryHandler(knowledgeServiceMock.Object);
var query = new SearchLibrarySemanticallyQuery(queryText, tenantId);
// Act
Func<Task> act = async () => await handler.Handle(query, CancellationToken.None);
var result = await handler.Handle(query, CancellationToken.None);
// Assert (SQLite provider will throw an execution/translation exception since CosineDistance is not supported,
// which confirms that the query built successfully and attempted execution!)
await act.Should().ThrowAsync<Exception>();
// Assert
result.IsSuccess.Should().BeTrue();
result.Value.Should().HaveCount(1);
result.Value.First().Snippet.Should().Be("Matched content");
result.Value.First().SourceBookTitle.Should().Be("Test Book");
_embeddingGeneratorMock.Verify(g => g.GenerateAsync(
It.Is<IEnumerable<string>>(s => s.Contains(queryText)),
It.IsAny<EmbeddingGenerationOptions>(),
It.IsAny<CancellationToken>()), Times.Once);
knowledgeServiceMock.Verify(s => s.SearchLibrarySemanticallyAsync(queryText, tenantId, 5, It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]