4 Commits

Author SHA1 Message Date
mjasin 94f6fe366d feat(recommendations): refactor handler to use clean IVectorSearchStore abstraction and fix unit tests 2026-06-06 11:28:14 +02:00
mjasin e9bb51af77 feat(ui): implement client-side [PAYWALL_TRIGGER] token parser, styling and tests 2026-06-06 11:07:21 +02:00
mjasin 93133a49b6 feat(intelligence): implement global hybrid search engine and monetization logic
- Created IUserLibraryStore and IVectorSearchStore abstractions to decouple relational DB and Qdrant gRPC logic from Application Layer
- Implemented MediatR GetGlobalIntelligenceQuery with value-first teaser RAG monetization logic
- Registered new request and response DTOs in AppJsonContext for Native AOT source-generated serialization
- Bound RagMonetizationOptions via IOptions pattern in appsettings.json configuration
- Added POST /api/intelligence endpoint on server and implemented GetGlobalIntelligenceAsync in WASM client service
- Refactored Intelligence.razor to consume the backend-driven global hybrid search Q&A engine
2026-06-06 10:55:58 +02:00
mjasin faf6ec826e feat(intelligence): implement Global AI Q&A screen and paywall blocker
- Implemented standard empty and active chat conversation states for the `/intelligence` page
- Created interactive `AiResponseRenderer` with AOT-compliant sentence splitting and payment gateway simulation
- Added scoped `LibraryStateService` to synchronize book ownership and updates across the application
- Obfuscated paywalled content in DOM to prevent inspection bypass
- Fixed local port connection mismatch by updating API configurations to use port 5104
2026-06-06 10:41:48 +02:00
33 changed files with 2200 additions and 328 deletions
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace NexusReader.Application.Abstractions.Persistence;
/// <summary>
/// Provides access to user library ownership details, decoupling the relational database
/// structures from vector search and intelligence query operations.
/// </summary>
public interface IUserLibraryStore
{
/// <summary>
/// Retrieves a list of book IDs that are owned by or uploaded for the specified user.
/// </summary>
Task<List<Guid>> GetOwnedBookIdsAsync(string userId, CancellationToken cancellationToken = default);
/// <summary>
/// Retrieves a dictionary mapping book IDs to their titles.
/// </summary>
Task<Dictionary<Guid, string>> GetBookTitlesAsync(List<Guid> bookIds, CancellationToken cancellationToken = default);
}
@@ -0,0 +1,21 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NexusReader.Application.Abstractions.Persistence;
/// <summary>
/// Decoupled database store to retrieve active user reading states and chapter content.
/// </summary>
public interface IUserReadingStateStore
{
/// <summary>
/// Retrieves the user's active reading state: last read ebook ID, last opened chapter/page ID, and tenant ID.
/// </summary>
Task<(Guid? EbookId, string? ChapterId, string? TenantId)> GetActiveReadingStateAsync(string userId, CancellationToken cancellationToken = default);
/// <summary>
/// Retrieves the text content of a specific chapter/page by its ID.
/// </summary>
Task<string?> GetChapterContentAsync(string chapterId, CancellationToken cancellationToken = default);
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace NexusReader.Application.Abstractions.Persistence;
/// <summary>
/// Represents a chunk of text retrieved from the semantic vector database.
/// </summary>
public record VectorChunk(string Content, string EbookId, double Score, string MetadataJson = "", string BookTitle = "", string ChapterTitle = "");
/// <summary>
/// Abstraction for performing semantic vector searches, isolating Qdrant gRPC dependencies from the Application layer.
/// </summary>
public interface IVectorSearchStore
{
/// <summary>
/// Searches the entire global catalog (filtered by tenant) for the best semantic matches.
/// </summary>
Task<List<VectorChunk>> SearchGlobalAsync(string queryText, string tenantId, int limit, CancellationToken cancellationToken = default);
/// <summary>
/// Searches within a whitelist of owned book IDs for the best semantic matches.
/// </summary>
Task<List<VectorChunk>> SearchLocalAsync(string queryText, string tenantId, List<Guid> whitelistedBookIds, int limit, CancellationToken cancellationToken = default);
/// <summary>
/// Searches the entire global catalog (filtered by tenant) for the best semantic matches, excluding a specific book ID.
/// </summary>
Task<List<VectorChunk>> SearchGlobalExcludeAsync(string queryText, string tenantId, Guid excludeBookId, int limit, CancellationToken cancellationToken = default);
}
@@ -1,5 +1,6 @@
using FluentResults;
using NexusReader.Application.DTOs.AI;
using NexusReader.Application.Queries.Intelligence;
namespace NexusReader.Application.Abstractions.Services;
@@ -13,6 +14,7 @@ public interface IKnowledgeService
Task<Result<GroundednessResult>> VerifyGroundednessAsync(string answer, string context, string tenantId, CancellationToken cancellationToken = default);
Task<Result<List<SemanticSearchResultDto>>> SearchLibrarySemanticallyAsync(string queryText, string tenantId, int limit, CancellationToken cancellationToken = default);
Task<Result<GroundedResponseDto>> AskQuestionAsync(string question, string tenantId, Guid? ebookId = null, int limit = 5, CancellationToken cancellationToken = default);
Task<Result<IntelligenceResponse>> GetGlobalIntelligenceAsync(string queryText, string userId, string tenantId, CancellationToken cancellationToken = default);
Task<Result> ClearCacheAsync(CancellationToken cancellationToken = default);
}
@@ -1,5 +1,7 @@
using System.Text.Json.Serialization;
using System.Collections.Generic;
using NexusReader.Application.Queries.Graph;
using NexusReader.Application.Queries.Intelligence;
namespace NexusReader.Application.Common;
@@ -9,6 +11,11 @@ namespace NexusReader.Application.Common;
[JsonSerializable(typeof(GraphDataDto))]
[JsonSerializable(typeof(List<GraphNodeDto>))]
[JsonSerializable(typeof(List<GraphLinkDto>))]
[JsonSerializable(typeof(GetGlobalIntelligenceRequest))]
[JsonSerializable(typeof(IntelligenceResponse))]
[JsonSerializable(typeof(NexusReader.Application.Queries.Recommendations.ContextualRecommendationResponse))]
[JsonSerializable(typeof(NexusReader.Application.Queries.Recommendations.RecommendationDto))]
[JsonSerializable(typeof(List<NexusReader.Application.Queries.Recommendations.RecommendationDto>))]
public partial class AppJsonContext : JsonSerializerContext
{
}
@@ -0,0 +1,28 @@
namespace NexusReader.Application.Common;
/// <summary>
/// Configurations for the monetization engine, controlling the thresholds at which
/// search queries trigger paywalls.
/// </summary>
public class RagMonetizationOptions
{
public const string SectionName = "RagMonetization";
/// <summary>
/// The baseline score threshold above which global content might trigger a paywall if there is no local content.
/// Default: 0.45.
/// </summary>
public double BaselineThreshold { get; set; } = 0.45;
/// <summary>
/// The similarity gap (Delta) required between global and local content to trigger an upgrade paywall.
/// Default: 0.15.
/// </summary>
public double DeltaThreshold { get; set; } = 0.15;
/// <summary>
/// The absolute score required from global content to trigger an upgrade paywall.
/// Default: 0.70.
/// </summary>
public double UpgradeThreshold { get; set; } = 0.70;
}
@@ -0,0 +1,222 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentResults;
using MediatR;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Options;
using NexusReader.Application.Abstractions.Persistence;
using NexusReader.Application.Common;
using NexusReader.Application.DTOs.AI;
namespace NexusReader.Application.Queries.Intelligence;
/// <summary>
/// MediatR query to request global intelligence hybrid Q&A context.
/// </summary>
public record GetGlobalIntelligenceQuery(string QueryText, string UserId, string TenantId = "global")
: IRequest<Result<IntelligenceResponse>>;
/// <summary>
/// Request schema for global hybrid search queries.
/// </summary>
public record GetGlobalIntelligenceRequest(string QueryText);
/// <summary>
/// Response schema returning generated AI text, paywall status, and locked publishing details.
/// </summary>
public record IntelligenceResponse(
string ResponseText,
bool HasPaywall,
Guid? LockedBookId,
string? LockedBookTitle,
List<CitationDto>? Citations = null);
/// <summary>
/// Handles <see cref="GetGlobalIntelligenceQuery"/> by performing local/global dual searches,
/// executing monetization rules, and invoking Chat AI with appropriate gating logic.
/// </summary>
public class GetGlobalIntelligenceQueryHandler : IRequestHandler<GetGlobalIntelligenceQuery, Result<IntelligenceResponse>>
{
private readonly IUserLibraryStore _userLibraryStore;
private readonly IVectorSearchStore _vectorSearchStore;
private readonly IChatClient _chatClient;
private readonly RagMonetizationOptions _options;
public GetGlobalIntelligenceQueryHandler(
IUserLibraryStore userLibraryStore,
IVectorSearchStore vectorSearchStore,
IChatClient chatClient,
IOptions<RagMonetizationOptions> options)
{
_userLibraryStore = userLibraryStore;
_vectorSearchStore = vectorSearchStore;
_chatClient = chatClient;
_options = options.Value;
}
public async Task<Result<IntelligenceResponse>> Handle(GetGlobalIntelligenceQuery request, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(request.QueryText))
{
return Result.Fail("Question cannot be empty.");
}
try
{
// Step A: Fetch whitelisted BookIds
var whitelistedBookIds = await _userLibraryStore.GetOwnedBookIdsAsync(request.UserId, cancellationToken);
// Step B & C: Vector Dual-Search with Resilient Trapping
List<VectorChunk> globalChunks = new();
List<VectorChunk> localChunks = new();
double globalScore = 0.0;
double localScore = 0.0;
try
{
// Execute searches
globalChunks = await _vectorSearchStore.SearchGlobalAsync(request.QueryText, request.TenantId, limit: 3, cancellationToken);
globalScore = globalChunks.Any() ? Math.Max(0.0, globalChunks.Max(c => c.Score)) : 0.0;
if (whitelistedBookIds.Any())
{
localChunks = await _vectorSearchStore.SearchLocalAsync(request.QueryText, request.TenantId, whitelistedBookIds, limit: 3, cancellationToken);
localScore = localChunks.Any() ? Math.Max(0.0, localChunks.Max(c => c.Score)) : 0.0;
}
}
catch (Exception ex)
{
// Resilient Error Trapping: transform connectivity anomalies into domain-friendly errors
return Result.Fail(new Error("Serwer wyszukiwania semantycznego jest tymczasowo niedostępny. Spróbuj ponownie później.").CausedBy(ex));
}
// Step D: Evaluate Monetization Thresholds
bool triggerPaywall = false;
if (localScore == 0.0 && globalScore > _options.BaselineThreshold)
{
triggerPaywall = true;
}
else if ((globalScore - localScore) > _options.DeltaThreshold && globalScore > _options.UpgradeThreshold)
{
triggerPaywall = true;
}
var chosenChunks = triggerPaywall ? globalChunks : localChunks;
// Fetch book titles for citations/paywall metadata
var chunkEbookIds = chosenChunks
.Where(c => Guid.TryParse(c.EbookId, out _))
.Select(c => Guid.Parse(c.EbookId))
.Distinct()
.ToList();
var bookTitles = await _userLibraryStore.GetBookTitlesAsync(chunkEbookIds, cancellationToken);
// Step E: Identify locked book if paywall triggered
Guid? lockedBookId = null;
string? lockedBookTitle = null;
if (triggerPaywall && globalChunks.Any())
{
var topGlobalChunk = globalChunks.OrderByDescending(c => c.Score).First();
if (Guid.TryParse(topGlobalChunk.EbookId, out var parsedLockedId))
{
lockedBookId = parsedLockedId;
bookTitles.TryGetValue(parsedLockedId, out lockedBookTitle);
if (string.IsNullOrEmpty(lockedBookTitle))
{
lockedBookTitle = "Nieznana książka";
}
}
}
// Format context blocks for LLM
var relatedContexts = new List<string>();
foreach (var chunk in chosenChunks)
{
var sourceId = chunk.EbookId;
relatedContexts.Add($"[Source ID: {sourceId}] {chunk.Content}");
}
var contextBlocksText = string.Join("\n\n", relatedContexts);
// Build LLM prompts
var systemPrompt = "You are an advanced, extremely precise Fact-Checking AI assistant. Your task is to answer the user's question using ONLY the provided context blocks.\n" +
"Rely EXCLUSIVELY on the provided context. Do NOT use any pre-existing external knowledge, facts, or assumptions.\n" +
"If the context does not contain the answer, say: 'I cannot answer this based on the provided book context.'";
if (triggerPaywall)
{
var localScorePercent = (int)Math.Round(localScore * 100);
var globalScorePercent = (int)Math.Round(globalScore * 100);
var resolvedTitle = lockedBookTitle ?? "Nieznana książka";
systemPrompt += $"\n\nCRITICAL: You are operating in TEASER mode. The user does not own the source document named '{resolvedTitle}'. You are strictly allowed to provide only a 1-sentence foundational definition or answer based on the context to prove the system knows the solution. DO NOT output code blocks, implementation details, or bullet points. You must immediately terminate your response with this exact token format: [PAYWALL_TRIGGER:{lockedBookId}:{resolvedTitle}:{localScorePercent}:{globalScorePercent}].";
}
var messages = new List<Microsoft.Extensions.AI.ChatMessage>
{
new(Microsoft.Extensions.AI.ChatRole.System, systemPrompt),
new(Microsoft.Extensions.AI.ChatRole.User, $"Context:\n{contextBlocksText}\n\nQuestion: {request.QueryText}")
};
var chatOptions = new ChatOptions
{
Temperature = 0.0f,
MaxOutputTokens = 1000
};
var chatResponse = await _chatClient.GetResponseAsync(messages, chatOptions, cancellationToken);
var responseText = chatResponse.Text?.Trim() ?? string.Empty;
// Ensure the paywall token is appended if LLM misses it in teaser mode
if (triggerPaywall)
{
var localScorePercent = (int)Math.Round(localScore * 100);
var globalScorePercent = (int)Math.Round(globalScore * 100);
var resolvedTitle = lockedBookTitle ?? "Nieznana książka";
var paywallToken = $"[PAYWALL_TRIGGER:{lockedBookId}:{resolvedTitle}:{localScorePercent}:{globalScorePercent}]";
if (!responseText.Contains("[PAYWALL_TRIGGER:"))
{
responseText = responseText.Trim() + " " + paywallToken;
}
}
// Build citations list
var citations = new List<CitationDto>();
foreach (var chunk in chosenChunks)
{
var sourceBookName = "Unknown";
if (Guid.TryParse(chunk.EbookId, out var parsedId) && bookTitles.TryGetValue(parsedId, out var title))
{
sourceBookName = title;
}
citations.Add(new CitationDto
{
CitationId = chunk.EbookId,
Snippet = chunk.Content,
SourceBook = sourceBookName,
Author = null,
PageNumber = null
});
}
return Result.Ok(new IntelligenceResponse(
ResponseText: responseText,
HasPaywall: triggerPaywall,
LockedBookId: lockedBookId,
LockedBookTitle: lockedBookTitle,
Citations: citations
));
}
catch (Exception ex)
{
return Result.Fail(new Error("Nieoczekiwany błąd serwera podczas przetwarzania zapytania.").CausedBy(ex));
}
}
}
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using FluentResults;
using MediatR;
namespace NexusReader.Application.Queries.Recommendations;
/// <summary>
/// MediatR query to fetch contextual recommendations based on the user's active reading state.
/// </summary>
public record GetContextualRecommendationsQuery(string UserId)
: IRequest<Result<ContextualRecommendationResponse>>;
/// <summary>
/// Response DTO containing contextual recommendations.
/// </summary>
public record ContextualRecommendationResponse(List<RecommendationDto> Recommendations);
/// <summary>
/// Individual contextual recommendation details.
/// </summary>
public record RecommendationDto(
string BookTitle,
string ChapterTitle,
int MatchPercentage,
bool IsPremiumUpsell,
Guid TargetBookId
);
@@ -2,6 +2,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.AI;
using NexusReader.Application.Common;
using GeminiDotnet;
using GeminiDotnet.Extensions.AI;
using NexusReader.Data.Persistence;
@@ -76,6 +77,7 @@ public static class DependencyInjection
services.Configure<AiSettings>(configuration.GetSection(AiSettings.SectionName));
services.Configure<StripeSettings>(configuration.GetSection(StripeSettings.SectionName));
services.Configure<RagMonetizationOptions>(configuration.GetSection(RagMonetizationOptions.SectionName));
var aiSettings = configuration.GetSection(AiSettings.SectionName).Get<AiSettings>() ?? new AiSettings();
if (string.IsNullOrWhiteSpace(aiSettings.ApiKey) || aiSettings.ApiKey == "PLACEHOLDER")
@@ -127,6 +129,9 @@ public static class DependencyInjection
services.AddScoped<IEbookRepository, EbookRepository>();
services.AddScoped<IQuizResultRepository, QuizResultRepository>();
services.AddScoped<IConceptsMapReadRepository, ConceptsMapReadRepository>();
services.AddScoped<IUserLibraryStore, UserLibraryStore>();
services.AddScoped<IUserReadingStateStore, UserReadingStateStore>();
services.AddScoped<IVectorSearchStore, VectorSearchStore>();
// Fix #2: SignalR broadcaster (scoped, wraps IHubContext which is itself a singleton wrapper)
services.AddScoped<ISyncBroadcaster, SignalRSyncBroadcaster>();
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Persistence;
using NexusReader.Data.Persistence;
namespace NexusReader.Infrastructure.Persistence;
/// <summary>
/// EF Core implementation of <see cref="IUserLibraryStore"/> using <see cref="AppDbContext"/>.
/// </summary>
internal sealed class UserLibraryStore : IUserLibraryStore
{
private readonly AppDbContext _context;
public UserLibraryStore(AppDbContext context)
{
_context = context;
}
/// <inheritdoc />
public async Task<List<Guid>> GetOwnedBookIdsAsync(string userId, CancellationToken cancellationToken = default)
{
return await _context.Ebooks
.Where(e => e.UserId == userId)
.Select(e => e.Id)
.ToListAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<Dictionary<Guid, string>> GetBookTitlesAsync(List<Guid> bookIds, CancellationToken cancellationToken = default)
{
if (bookIds == null || !bookIds.Any())
{
return new Dictionary<Guid, string>();
}
return await _context.Ebooks
.Where(e => bookIds.Contains(e.Id))
.ToDictionaryAsync(e => e.Id, e => e.Title, cancellationToken);
}
}
@@ -0,0 +1,56 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Persistence;
using NexusReader.Data.Persistence;
namespace NexusReader.Infrastructure.Persistence;
/// <summary>
/// EF Core implementation of <see cref="IUserReadingStateStore"/>.
/// </summary>
internal sealed class UserReadingStateStore : IUserReadingStateStore
{
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
public UserReadingStateStore(IDbContextFactory<AppDbContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
/// <inheritdoc />
public async Task<(Guid? EbookId, string? ChapterId, string? TenantId)> GetActiveReadingStateAsync(string userId, CancellationToken cancellationToken = default)
{
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
var userState = await dbContext.Users
.Where(u => u.Id == userId)
.Select(u => new
{
u.TenantId,
u.LastReadPageId,
LastReadBookId = u.Ebooks.OrderByDescending(e => e.LastReadDate).Select(e => (Guid?)e.Id).FirstOrDefault()
})
.FirstOrDefaultAsync(cancellationToken);
if (userState == null)
{
return (null, null, null);
}
return (userState.LastReadBookId, userState.LastReadPageId, userState.TenantId);
}
/// <inheritdoc />
public async Task<string?> GetChapterContentAsync(string chapterId, CancellationToken cancellationToken = default)
{
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
return await dbContext.KnowledgeUnits
.Where(ku => ku.Id == chapterId)
.Select(ku => ku.Content)
.FirstOrDefaultAsync(cancellationToken);
}
}
@@ -0,0 +1,188 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Qdrant.Client;
using Qdrant.Client.Grpc;
using Polly;
using Polly.Registry;
using NexusReader.Application.Abstractions.Persistence;
namespace NexusReader.Infrastructure.Persistence;
/// <summary>
/// Infrastructure implementation of <see cref="IVectorSearchStore"/> utilizing <see cref="QdrantClient"/>
/// and <see cref="IEmbeddingGenerator{TInput, TEmbedding}"/> to execute semantic vector queries.
/// </summary>
internal sealed class VectorSearchStore : IVectorSearchStore
{
private readonly QdrantClient _qdrantClient;
private readonly IEmbeddingGenerator<string, Embedding<float>> _embeddingGenerator;
private readonly ResiliencePipeline _retryPipeline;
private readonly ILogger<VectorSearchStore> _logger;
public VectorSearchStore(
QdrantClient qdrantClient,
IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator,
ResiliencePipelineProvider<string> pipelineProvider,
ILogger<VectorSearchStore> logger)
{
_qdrantClient = qdrantClient;
_embeddingGenerator = embeddingGenerator;
_retryPipeline = pipelineProvider.GetPipeline("ai-retry");
_logger = logger;
}
/// <inheritdoc />
public async Task<List<VectorChunk>> SearchGlobalAsync(string queryText, string tenantId, int limit, CancellationToken cancellationToken = default)
{
var queryVector = await GenerateEmbeddingAsync(queryText, cancellationToken);
var filter = BuildTenantFilter(tenantId);
return await ExecuteSearchAsync(queryVector, filter, limit, cancellationToken);
}
/// <inheritdoc />
public async Task<List<VectorChunk>> SearchLocalAsync(string queryText, string tenantId, List<Guid> whitelistedBookIds, int limit, CancellationToken cancellationToken = default)
{
if (whitelistedBookIds == null || !whitelistedBookIds.Any())
{
return new List<VectorChunk>();
}
var queryVector = await GenerateEmbeddingAsync(queryText, cancellationToken);
var filter = BuildTenantFilter(tenantId);
var whitelistFilter = new Qdrant.Client.Grpc.Filter();
foreach (var bookId in whitelistedBookIds)
{
whitelistFilter.Should.Add(new Qdrant.Client.Grpc.Condition
{
Field = new Qdrant.Client.Grpc.FieldCondition
{
Key = "ebookId",
Match = new Qdrant.Client.Grpc.Match { Text = bookId.ToString() }
}
});
}
filter.Must.Add(new Qdrant.Client.Grpc.Condition { Filter = whitelistFilter });
return await ExecuteSearchAsync(queryVector, filter, limit, cancellationToken);
}
/// <inheritdoc />
public async Task<List<VectorChunk>> SearchGlobalExcludeAsync(string queryText, string tenantId, Guid excludeBookId, int limit, CancellationToken cancellationToken = default)
{
var queryVector = await GenerateEmbeddingAsync(queryText, cancellationToken);
var filter = BuildTenantFilter(tenantId);
// Exclude current book
filter.MustNot.Add(new Qdrant.Client.Grpc.Condition
{
Field = new Qdrant.Client.Grpc.FieldCondition
{
Key = "ebookId",
Match = new Qdrant.Client.Grpc.Match { Text = excludeBookId.ToString() }
}
});
return await ExecuteSearchAsync(queryVector, filter, limit, cancellationToken);
}
private async Task<float[]> GenerateEmbeddingAsync(string text, CancellationToken cancellationToken)
{
var response = await _retryPipeline.ExecuteAsync(async ct =>
await _embeddingGenerator.GenerateAsync(
new[] { text },
new EmbeddingGenerationOptions { Dimensions = 768 },
cancellationToken: ct), cancellationToken);
return response.First().Vector.ToArray();
}
private Qdrant.Client.Grpc.Filter BuildTenantFilter(string tenantId)
{
var filter = new Qdrant.Client.Grpc.Filter();
var tenantFilter = new Qdrant.Client.Grpc.Filter();
tenantFilter.Should.Add(new Qdrant.Client.Grpc.Condition
{
Field = new Qdrant.Client.Grpc.FieldCondition
{
Key = "tenantId",
Match = new Qdrant.Client.Grpc.Match { Text = tenantId }
}
});
tenantFilter.Should.Add(new Qdrant.Client.Grpc.Condition
{
Field = new Qdrant.Client.Grpc.FieldCondition
{
Key = "tenantId",
Match = new Qdrant.Client.Grpc.Match { Text = "global" }
}
});
filter.Must.Add(new Qdrant.Client.Grpc.Condition { Filter = tenantFilter });
return filter;
}
private async Task<List<VectorChunk>> ExecuteSearchAsync(float[] queryVector, Qdrant.Client.Grpc.Filter filter, int limit, CancellationToken cancellationToken)
{
try
{
await EnsureCollectionExistsAsync("knowledge_units", cancellationToken);
var response = await _qdrantClient.SearchAsync(
collectionName: "knowledge_units",
vector: queryVector,
filter: filter,
limit: (ulong)limit,
cancellationToken: cancellationToken
);
return response.Select(point =>
{
var content = point.Payload.TryGetValue("content", out var cv) ? cv.StringValue : string.Empty;
var ebookId = point.Payload.TryGetValue("ebookId", out var ev) ? ev.StringValue : string.Empty;
var metadataJson = point.Payload.TryGetValue("metadataJson", out var mv) ? mv.StringValue : string.Empty;
var bookTitle = point.Payload.TryGetValue("bookTitle", out var btv) ? btv.StringValue : string.Empty;
var chapterTitle = point.Payload.TryGetValue("chapterTitle", out var ctv) ? ctv.StringValue : string.Empty;
return new VectorChunk(content, ebookId, point.Score, metadataJson, bookTitle, chapterTitle);
}).ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "[VectorSearchStore] Qdrant search execution failed.");
throw;
}
}
private async Task EnsureCollectionExistsAsync(string collectionName, CancellationToken cancellationToken)
{
try
{
var exists = await _qdrantClient.CollectionExistsAsync(collectionName, cancellationToken);
if (!exists)
{
await _qdrantClient.CreateCollectionAsync(
collectionName: collectionName,
vectorsConfig: new Qdrant.Client.Grpc.VectorParams
{
Size = 768,
Distance = Distance.Cosine
},
cancellationToken: cancellationToken
);
}
}
catch (Exception)
{
// Ignore concurrent creation conflicts in multi-threaded/concurrent flows
}
}
}
@@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using FluentResults;
using MediatR;
using NexusReader.Application.Abstractions.Persistence;
using NexusReader.Application.Queries.Recommendations;
namespace NexusReader.Infrastructure.Queries;
/// <summary>
/// Handles <see cref="GetContextualRecommendationsQuery"/> by discovering the active reading state,
/// performing semantic search using IVectorSearchStore with book exclusion, and mapping upsells.
/// </summary>
public class GetContextualRecommendationsQueryHandler : IRequestHandler<GetContextualRecommendationsQuery, Result<ContextualRecommendationResponse>>
{
private readonly IUserReadingStateStore _readingStateStore;
private readonly IUserLibraryStore _libraryStore;
private readonly IVectorSearchStore _vectorSearchStore;
public GetContextualRecommendationsQueryHandler(
IUserReadingStateStore readingStateStore,
IUserLibraryStore libraryStore,
IVectorSearchStore vectorSearchStore)
{
_readingStateStore = readingStateStore;
_libraryStore = libraryStore;
_vectorSearchStore = vectorSearchStore;
}
public async Task<Result<ContextualRecommendationResponse>> Handle(GetContextualRecommendationsQuery request, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(request.UserId))
{
return Result.Fail("UserId cannot be empty.");
}
try
{
// Step 1: Discover active reading state
var (ebookId, chapterId, tenantId) = await _readingStateStore.GetActiveReadingStateAsync(request.UserId, cancellationToken);
if (ebookId == null)
{
// Fallback: brand-new user with no reading history, return empty recommendations list safely
return Result.Ok(new ContextualRecommendationResponse(new List<RecommendationDto>()));
}
// Step 2: Fetch specific content associated with active ChapterId
string? chapterContent = null;
if (!string.IsNullOrEmpty(chapterId))
{
chapterContent = await _readingStateStore.GetChapterContentAsync(chapterId, cancellationToken);
}
// Fallback: if no active chapter or content, try retrieving any chapter content from this book
if (string.IsNullOrEmpty(chapterContent))
{
return Result.Ok(new ContextualRecommendationResponse(new List<RecommendationDto>()));
}
// Step 3: Perform similarity search using IVectorSearchStore
var resolvedTenantId = tenantId ?? "global";
var searchResults = await _vectorSearchStore.SearchGlobalExcludeAsync(
chapterContent,
resolvedTenantId,
ebookId.Value,
limit: 2,
cancellationToken: cancellationToken
);
// Step 4: Process recommendations and cross-reference owned books
var ownedBookIds = await _libraryStore.GetOwnedBookIdsAsync(request.UserId, cancellationToken);
var recommendations = new List<RecommendationDto>();
foreach (var point in searchResults)
{
var targetEbookIdStr = point.EbookId;
if (!Guid.TryParse(targetEbookIdStr, out var targetEbookId))
continue;
// Load bookTitle from point
var bookTitle = point.BookTitle;
if (string.IsNullOrEmpty(bookTitle))
{
bookTitle = "Nieznana książka";
}
// Load chapterTitle from point or metadataJson
var chapterTitle = point.ChapterTitle;
if (string.IsNullOrEmpty(chapterTitle))
{
chapterTitle = "Wiedza z rozdziału";
if (!string.IsNullOrEmpty(point.MetadataJson))
{
try
{
using var doc = JsonDocument.Parse(point.MetadataJson);
if (doc.RootElement.TryGetProperty("label", out var labelProp))
{
chapterTitle = labelProp.GetString() ?? chapterTitle;
}
}
catch { }
}
}
var isPremiumUpsell = !ownedBookIds.Contains(targetEbookId);
var matchPercentage = (int)Math.Round(point.Score * 100);
recommendations.Add(new RecommendationDto(
BookTitle: bookTitle,
ChapterTitle: chapterTitle,
MatchPercentage: matchPercentage,
IsPremiumUpsell: isPremiumUpsell,
TargetBookId: targetEbookId
));
}
return Result.Ok(new ContextualRecommendationResponse(recommendations));
}
catch (Exception ex)
{
return Result.Fail(new Error("Downstream vector database or state query failed.").CausedBy(ex));
}
}
}
@@ -4,6 +4,8 @@ using FluentResults;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using MediatR;
using NexusReader.Application.Queries.Intelligence;
using Microsoft.ML.Tokenizers;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.DTOs.AI;
@@ -33,6 +35,7 @@ public class KnowledgeService : IKnowledgeService
private readonly ILogger<KnowledgeService> _logger;
private readonly QdrantClient _qdrantClient;
private readonly IDriver _neo4jDriver;
private readonly IMediator _mediator;
private const string PromptVersion = "1.7";
private static readonly ConcurrentDictionary<string, Lazy<Task<Result<KnowledgePacket>>>> _activeRequests = new();
private static readonly SemaphoreSlim _collectionSemaphore = new(1, 1);
@@ -45,7 +48,8 @@ public class KnowledgeService : IKnowledgeService
IOptions<AiSettings> settings,
ILogger<KnowledgeService> logger,
QdrantClient qdrantClient,
IDriver neo4jDriver)
IDriver neo4jDriver,
IMediator mediator)
{
_chatClient = chatClient;
_embeddingGenerator = embeddingGenerator;
@@ -55,6 +59,7 @@ public class KnowledgeService : IKnowledgeService
_logger = logger;
_qdrantClient = qdrantClient;
_neo4jDriver = neo4jDriver;
_mediator = mediator;
// Use Tiktoken (cl100k_base) which is a standard for modern LLMs and provides
// a very reliable estimation for token usage in Gemini-based workloads.
_tokenizer = TiktokenTokenizer.CreateForModel("gpt-4");
@@ -334,6 +339,17 @@ public class KnowledgeService : IKnowledgeService
{
try
{
// Retrieve the book's title from the database using EF Core
string bookTitle = "Nieznana książka";
if (ebookId.HasValue)
{
var ebook = await dbContext.Ebooks.FindAsync(new object[] { ebookId.Value }, cancellationToken);
if (ebook != null)
{
bookTitle = ebook.Title;
}
}
var contents = unitsToEmbed.Select(u => u.Content).ToList();
var embeddingResponse = await _retryPipeline.ExecuteAsync(async ct =>
@@ -350,6 +366,12 @@ public class KnowledgeService : IKnowledgeService
var unitDto = unitsToEmbed[i];
var vector = embeddings[i].Vector.ToArray();
string chapterTitle = "Wiedza z rozdziału";
if (unitDto.Metadata != null && unitDto.Metadata.TryGetValue("label", out var labelVal) && labelVal is string labelStr)
{
chapterTitle = labelStr;
}
var point = new PointStruct
{
Id = GetDeterministicGuid(unitDto.Id),
@@ -360,6 +382,8 @@ public class KnowledgeService : IKnowledgeService
["type"] = unitDto.Type ?? string.Empty,
["tenantId"] = tenantId,
["ebookId"] = ebookId?.ToString() ?? string.Empty,
["bookTitle"] = bookTitle,
["chapterTitle"] = chapterTitle,
["metadataJson"] = JsonSerializer.Serialize(unitDto.Metadata)
}
};
@@ -1187,6 +1211,12 @@ public class KnowledgeService : IKnowledgeService
}
}
/// <inheritdoc />
public async Task<Result<IntelligenceResponse>> GetGlobalIntelligenceAsync(string queryText, string userId, string tenantId, CancellationToken cancellationToken = default)
{
return await _mediator.Send(new GetGlobalIntelligenceQuery(queryText, userId, tenantId), cancellationToken);
}
private int EstimateTokenCount(string text)
{
if (string.IsNullOrEmpty(text)) return 0;
+2 -1
View File
@@ -56,7 +56,7 @@ public static class MauiProgram
builder.Services.AddTransient<MobileAuthenticationHeaderHandler>();
builder.Services.AddHttpClient("NexusAPI", client =>
{
var apiBaseUrl = builder.Configuration["ApiSettings:BaseUrl"] ?? "http://localhost:5000";
var apiBaseUrl = builder.Configuration["ApiSettings:BaseUrl"] ?? "http://localhost:5104";
client.BaseAddress = new Uri(apiBaseUrl);
}).AddHttpMessageHandler<MobileAuthenticationHeaderHandler>();
@@ -74,6 +74,7 @@ public static class MauiProgram
builder.Services.AddScoped<IKnowledgeGraphService, KnowledgeGraphService>();
builder.Services.AddScoped<IReaderInteractionService, ReaderInteractionService>();
builder.Services.AddScoped<IReaderStateService, ReaderStateService>();
builder.Services.AddScoped<ILibraryStateService, LibraryStateService>();
builder.Services.AddScoped<KnowledgeCoordinator>();
builder.Services.AddScoped<ISyncService, SyncService>();
builder.Services.AddScoped<IIdentityService, IdentityService>();
+1 -1
View File
@@ -1,6 +1,6 @@
{
"ApiSettings": {
"BaseUrl": "https://localhost:5000"
"BaseUrl": "http://localhost:5104"
},
"Serilog": {
"Using": [
@@ -0,0 +1,277 @@
@using NexusReader.UI.Shared.Models
@using NexusReader.UI.Shared.Services
@using NexusReader.Application.DTOs.AI
@using NexusReader.Application.DTOs.User
@using System.Net.Http.Json
@inject HttpClient Http
@inject ILibraryStateService LibraryStateService
@inject NavigationManager NavigationManager
<div class="message-row @(Message.Sender == "User" ? "user-row" : "ai-row")">
<div class="message-avatar" aria-hidden="true">
@if (Message.Sender == "User")
{
<i class="bi bi-person-fill"></i>
}
else
{
<i class="bi bi-robot"></i>
}
</div>
<div class="message-bubble @GetBubbleClass()">
<div class="message-header">
<span class="sender-name">@Message.Sender</span>
<span class="message-time">@Message.Timestamp.ToString("HH:mm")</span>
</div>
<div class="message-content">
@if (Message.Sender == "User")
{
<p>@Message.Text</p>
}
else
{
@if (_hasPaywall)
{
<div class="paywall-teaser" aria-hidden="true">
@foreach (var segment in ParseSegments(_displayTeaserText))
{
@if (segment.IsCitation)
{
<NexusCitationMarker SourceId="@segment.CitationId" Citations="@Message.Citations" />
}
else
{
@RenderMarkdown(segment.Text)
}
}
</div>
<div class="upsell-card" role="alert" aria-live="polite">
<div class="upsell-header">
<span class="upsell-icon" aria-hidden="true">🔒</span>
<h4>Dostęp Premium Zablokowany</h4>
</div>
<p class="upsell-text">
Twoje zasoby odpowiadają na to pytanie w <strong>@_localScore%</strong>. W materiale <strong>'@_lockedBookTitle'</strong> znaleźliśmy odpowiedź dopasowaną w <strong>@_globalScore%</strong>.
</p>
<div class="upsell-actions">
@if (_isSimulatingPayment)
{
<button class="btn-upsell btn-primary loading" disabled aria-busy="true">
<div class="payment-spinner" aria-hidden="true"></div>
PRZETWARZANIE PŁATNOŚCI...
</button>
}
else
{
<button class="btn-upsell btn-primary" @onclick="HandlePurchase">
ODBLOKUJ PEŁNĄ TREŚĆ (29 PLN)
</button>
}
<a href="/catalog?bookId=@_lockedBookId" class="btn-upsell btn-secondary">
Zobacz szczegóły w Katalogu
</a>
</div>
</div>
}
else
{
<div class="full-response">
@foreach (var segment in ParseSegments(GetCleanText()))
{
@if (segment.IsCitation)
{
<NexusCitationMarker SourceId="@segment.CitationId" Citations="@Message.Citations" />
}
else
{
@RenderMarkdown(segment.Text)
}
}
</div>
@if (_showSuccessBanner)
{
<div class="success-unlock-banner" role="status">
<span class="success-icon" aria-hidden="true">✓</span>
<span>Odblokowano pełną odpowiedź! Książka została dodana do Twojej biblioteki.</span>
</div>
}
}
}
</div>
</div>
</div>
@code {
[Parameter] public ChatMessage Message { get; set; } = default!;
[Parameter] public List<LastReadBookDto>? OwnedBooks { get; set; }
[Parameter] public EventCallback<Guid> OnUnlockRequested { get; set; }
private bool _hasPaywall;
private string _displayTeaserText = string.Empty;
private Guid _lockedBookId;
private string _lockedBookTitle = string.Empty;
private int _localScore;
private int _globalScore;
private bool _isUnlocked = false;
private bool _isSimulatingPayment = false;
private bool _showSuccessBanner = false;
protected override void OnParametersSet()
{
base.OnParametersSet();
if (Message != null && Message.Sender != "User" && !_isUnlocked)
{
_hasPaywall = PaywallParser.TryParsePaywallTrigger(Message.Text, out _displayTeaserText, out _lockedBookId, out _lockedBookTitle, out _localScore, out _globalScore);
// Additional check: if user already owns the book, don't show the paywall
if (_hasPaywall && OwnedBooks != null)
{
var isOwned = OwnedBooks.Any(b =>
b.Id == _lockedBookId ||
(!string.IsNullOrEmpty(b.Title) && b.Title.Equals(_lockedBookTitle, StringComparison.OrdinalIgnoreCase)));
if (isOwned)
{
_hasPaywall = false;
}
}
}
else
{
_hasPaywall = false;
}
}
private string GetCleanText()
{
if (Message == null) return string.Empty;
if (PaywallParser.TryParsePaywallTrigger(Message.Text, out var cleanText, out _, out _, out _, out _))
{
return cleanText;
}
return Message.Text;
}
private string GetBubbleClass()
{
if (Message.Sender == "User") return "user-bubble";
return _hasPaywall ? "ai-bubble paywalled-bubble" : "ai-bubble";
}
private async Task HandlePurchase()
{
if (_isSimulatingPayment) return;
_isSimulatingPayment = true;
StateHasChanged();
// Simulate payment gateway delay (1.5 seconds)
await Task.Delay(1500);
try
{
var bookTitle = string.IsNullOrEmpty(_lockedBookTitle)
? "Architektura .NET 10 i Ekosystem Blazor"
: _lockedBookTitle;
// Call POST endpoint to persist the purchase
var response = await Http.PostAsJsonAsync("api/library/purchase", new { Title = bookTitle });
if (response.IsSuccessStatusCode)
{
_isUnlocked = true;
_hasPaywall = false;
_showSuccessBanner = true;
// Fetch updated library list and update state manager
var updatedBooks = await Http.GetFromJsonAsync<List<LastReadBookDto>>("api/library/books");
LibraryStateService.OwnedBooks = updatedBooks;
if (OnUnlockRequested.HasDelegate)
{
await OnUnlockRequested.InvokeAsync(_lockedBookId);
}
}
else
{
Console.WriteLine("[AiResponseRenderer] Purchase failed on server.");
}
}
catch (Exception ex)
{
Console.WriteLine($"[AiResponseRenderer] Error processing purchase: {ex.Message}");
}
finally
{
_isSimulatingPayment = false;
StateHasChanged();
}
}
private List<ResponseSegment> ParseSegments(string text)
{
var segments = new List<ResponseSegment>();
if (string.IsNullOrEmpty(text)) return segments;
var regex = new System.Text.RegularExpressions.Regex(
@"\[Source ID:\s*([^\]]+)\]|\[([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\]",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var matches = regex.Matches(text);
int lastIndex = 0;
foreach (System.Text.RegularExpressions.Match match in matches)
{
if (match.Index > lastIndex)
{
segments.Add(new ResponseSegment
{
Text = text.Substring(lastIndex, match.Index - lastIndex),
IsCitation = false
});
}
var citationId = match.Groups[1].Success
? match.Groups[1].Value.Trim()
: match.Groups[2].Value.Trim();
segments.Add(new ResponseSegment
{
IsCitation = true,
CitationId = citationId
});
lastIndex = match.Index + match.Length;
}
if (lastIndex < text.Length)
{
segments.Add(new ResponseSegment
{
Text = text.Substring(lastIndex),
IsCitation = false
});
}
return segments;
}
private MarkupString RenderMarkdown(string text)
{
if (string.IsNullOrEmpty(text)) return new MarkupString(string.Empty);
var html = System.Net.WebUtility.HtmlEncode(text);
html = System.Text.RegularExpressions.Regex.Replace(html, @"\*\*(.*?)\*\*", "<strong>$1</strong>");
html = System.Text.RegularExpressions.Regex.Replace(html, @"\*(.*?)\*", "<em>$1</em>");
html = System.Text.RegularExpressions.Regex.Replace(html, @"```(?:[a-zA-Z0-9+#]+)?\s*([\s\S]*?)\s*```", "<pre class=\"nexus-code-block\"><code>$1</code></pre>");
html = System.Text.RegularExpressions.Regex.Replace(html, @"`(.*?)`", "<code class=\"nexus-inline-code\">$1</code>");
html = html.Replace("\n", "<br />");
return new MarkupString(html);
}
}
@@ -0,0 +1,267 @@
.message-row {
display: flex;
gap: 1rem;
width: 100%;
max-width: 90%;
margin-bottom: 1.5rem;
animation: bubble-fade-in 0.35s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.user-row {
align-self: flex-end;
margin-left: auto;
flex-direction: row-reverse;
}
.ai-row {
align-self: flex-start;
margin-right: auto;
}
.message-avatar {
width: 38px;
height: 38px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.1rem;
flex-shrink: 0;
}
.user-row .message-avatar {
background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%);
color: #ffffff;
border: 1px solid rgba(255, 255, 255, 0.2);
box-shadow: 0 0 10px rgba(255, 255, 255, 0.1);
}
.ai-row .message-avatar {
background: linear-gradient(135deg, #005f38 0%, #004024 100%);
color: #e6fffa;
border: 1px solid rgba(0, 255, 153, 0.4);
box-shadow: 0 0 10px rgba(0, 255, 153, 0.25);
}
.message-bubble {
padding: 1.25rem 1.5rem;
border-radius: 16px;
position: relative;
line-height: 1.6;
font-size: 0.975rem;
display: flex;
flex-direction: column;
width: 100%;
}
.user-bubble {
background: #1a1a1e;
border: 1px solid rgba(255, 255, 255, 0.05);
color: #e4e4e7;
border-top-right-radius: 4px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}
.ai-bubble {
background: rgba(26, 26, 30, 0.6);
border: 1px solid rgba(255, 255, 255, 0.05);
color: #e2e8f0;
border-top-left-radius: 4px;
box-shadow: 0 4px 25px rgba(0, 0, 0, 0.2);
}
.paywalled-bubble {
border-color: rgba(16, 185, 129, 0.15);
}
.message-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.75rem;
font-size: 0.75rem;
opacity: 0.6;
}
.sender-name {
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.message-time {
font-family: monospace;
}
.message-content {
word-break: break-word;
}
/* Paragraph spacing */
.message-content p {
margin: 0 0 1rem 0;
}
.message-content p:last-child {
margin-bottom: 0;
}
/* Paywall Blur Styles */
.paywall-teaser {
position: relative;
margin-bottom: 1.5rem;
-webkit-mask-image: linear-gradient(to bottom, black 30%, transparent 100%);
mask-image: linear-gradient(to bottom, black 30%, transparent 100%);
filter: blur(2px);
pointer-events: none;
-webkit-user-select: none;
user-select: none;
}
/* Upsell Card */
.upsell-card {
background: #1a1a1e;
border-radius: 12px;
border: 1px solid rgba(16, 185, 129, 0.25);
padding: 1.5rem;
margin-top: 1rem;
box-shadow: 0 8px 32px rgba(16, 185, 129, 0.08), 0 4px 12px rgba(0, 0, 0, 0.4);
animation: card-slide-in 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.upsell-header {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 0.75rem;
}
.upsell-icon {
font-size: 1.25rem;
}
.upsell-header h4 {
margin: 0;
color: #10b981;
font-size: 1.1rem;
font-weight: 700;
letter-spacing: 0.5px;
}
.upsell-text {
color: rgba(255, 255, 255, 0.75);
font-size: 0.9rem;
line-height: 1.55;
margin: 0 0 1.25rem 0;
}
.upsell-actions {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.btn-upsell {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.75rem 1.5rem;
font-size: 0.85rem;
font-weight: 700;
text-transform: uppercase;
border-radius: 8px;
cursor: pointer;
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
text-decoration: none;
letter-spacing: 0.5px;
min-height: 44px;
}
.btn-primary {
background: #10b981;
border: none;
color: #121214;
}
.btn-primary:hover:not(:disabled) {
background: #0d9668;
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
}
.btn-primary:active:not(:disabled) {
transform: translateY(0);
}
.btn-primary:disabled {
background: rgba(16, 185, 129, 0.5);
color: rgba(18, 18, 20, 0.6);
cursor: not-allowed;
}
.btn-secondary {
background: transparent;
border: 1px solid #10b981;
color: #10b981;
}
.btn-secondary:hover {
background: rgba(16, 185, 129, 0.05);
transform: translateY(-2px);
}
.btn-secondary:active {
transform: translateY(0);
}
/* Success Banner */
.success-unlock-banner {
display: flex;
align-items: center;
gap: 0.75rem;
background: rgba(16, 185, 129, 0.1);
border: 1px solid rgba(16, 185, 129, 0.3);
color: #10b981;
padding: 1rem;
border-radius: 8px;
margin-top: 1.25rem;
font-size: 0.9rem;
font-weight: 600;
animation: fade-in 0.5s ease-out;
}
.success-icon {
font-weight: bold;
font-size: 1.1rem;
}
/* Payment Spinner */
.payment-spinner {
width: 16px;
height: 16px;
border: 2px solid rgba(18, 18, 20, 0.2);
border-top-color: #121214;
border-radius: 50%;
margin-right: 0.75rem;
animation: spin 0.8s linear infinite;
}
/* Keyframes */
@keyframes bubble-fade-in {
0% { opacity: 0; transform: translateY(12px) scale(0.98); }
100% { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes card-slide-in {
0% { opacity: 0; transform: translateY(10px); }
100% { opacity: 1; transform: translateY(0); }
}
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@@ -28,6 +28,12 @@ public class ChatMessage
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
public List<ResponseSegment> Segments { get; set; } = new();
public List<CitationDto> Citations { get; set; } = new();
public string ClearText { get; set; } = string.Empty;
public string BlurredTeaserText { get; set; } = string.Empty;
public bool IsPaywalled { get; set; }
public string SourceBookTitle { get; set; } = string.Empty;
public string DocumentId { get; set; } = string.Empty;
}
/// <summary>
@@ -1,5 +1,6 @@
@page "/catalog"
@attribute [Authorize]
@implements IDisposable
@using NexusReader.UI.Shared.Components.Organisms
@using NexusReader.Application.DTOs.User
@using NexusReader.UI.Shared.Services
@@ -7,6 +8,7 @@
@inject HttpClient Http
@inject IReaderNavigationService ReaderNavigation
@inject NavigationManager NavigationManager
@inject ILibraryStateService LibraryStateService
<div class="catalog-page">
<header class="catalog-header">
@@ -189,6 +191,11 @@
private bool _isLoading = true;
private List<LastReadBookDto>? _books;
protected override void OnInitialized()
{
LibraryStateService.OnBooksChanged += HandleBooksChanged;
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
@@ -197,6 +204,11 @@
}
}
private void HandleBooksChanged()
{
_ = InvokeAsync(LoadBooksAsync);
}
private async Task LoadBooksAsync()
{
_isLoading = true;
@@ -231,4 +243,9 @@
// Showcase callback
NavigationManager.NavigateTo("/profile");
}
public void Dispose()
{
LibraryStateService.OnBooksChanged -= HandleBooksChanged;
}
}
@@ -1,35 +1,34 @@
@page "/intelligence"
@attribute [Authorize]
@implements IDisposable
@using NexusReader.Application.DTOs.AI
@using NexusReader.Application.Abstractions.Services
@using NexusReader.Application.DTOs.User
@using NexusReader.UI.Shared.Components.Molecules
@using NexusReader.UI.Shared.Components.Atoms
@using NexusReader.UI.Shared.Models
@using System.Net.Http.Json
@inject HttpClient Http
@inject IKnowledgeService KnowledgeService
@inject AuthenticationStateProvider AuthStateProvider
@inject ILibraryStateService LibraryStateService
<div class="intelligence-page">
<header class="intelligence-header">
<div class="header-title-section">
<h1 class="neon-glow-text">Global Intelligence</h1>
<p class="subtitle">Interrogate, explore, and synthesize grounded knowledge from your library using Polyglot KM-RAG</p>
</div>
</header>
<div class="intelligence-layout glass-panel">
<div class="intelligence-layout">
<div class="chat-thread-container">
@if (_chatMessages.Count == 0)
{
<div class="welcome-state">
<div class="welcome-icon">
<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
<svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="#8b8273" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z" stroke-dasharray="2 2" stroke="rgba(139, 130, 115, 0.3)" />
<path d="M12 6v12M8 8h8M6 12h12M8 16h8" stroke="rgba(139, 130, 115, 0.4)" />
<path d="M9.5 4.5c-1.5 0-3 1.5-3 3.5s1.5 3 3 3h5c1.5 0 3-1 3-3s-1.5-3.5-3-3.5" />
<path d="M9.5 19.5c-1.5 0-3-1.5-3-3.5s1.5-3 3-3h5c1.5 0 3 1 3 3s-1.5 3.5-3 3.5" />
<circle cx="12" cy="12" r="2" fill="#8b8273" />
</svg>
</div>
<h3>Start Interrogating Your Library</h3>
<p>Ask complex questions across your entire ebook collection. The KM-RAG engine dynamically builds semantic maps, resolves dependencies, and formulates high-fidelity, grounded answers with interactive popover citations.</p>
<div class="welcome-prompt">Zadaj pytanie globalne do całej biblioteki...</div>
</div>
}
else
@@ -37,37 +36,7 @@
<div class="chat-bubbles-scroll">
@foreach (var message in _chatMessages)
{
<div class="message-row @(message.Sender == "User" ? "user-row" : "ai-row")" key="@message.Id">
<div class="message-avatar">
@if (message.Sender == "User")
{
<i class="bi bi-person-fill"></i>
}
else
{
<i class="bi bi-robot"></i>
}
</div>
<div class="message-bubble @(message.Sender == "User" ? "user-bubble" : "ai-bubble")">
<div class="message-header">
<span class="sender-name">@message.Sender</span>
<span class="message-time">@message.Timestamp.ToString("HH:mm")</span>
</div>
<div class="message-content">
@foreach (var segment in message.Segments)
{
@if (segment.IsCitation)
{
<NexusCitationMarker SourceId="@segment.CitationId" Citations="@message.Citations" />
}
else
{
@RenderMarkdown(segment.Text)
}
}
</div>
</div>
</div>
<AiResponseRenderer @key="message.Id" Message="@message" OwnedBooks="@_books" />
}
@if (_isLoading)
@@ -100,9 +69,9 @@
<div class="input-panel-wrapper">
<div class="scope-bar">
<div class="scope-selector">
<label for="book-select"><i class="bi bi-compass"></i> Scope:</label>
<label for="book-select">Scope:</label>
<select id="book-select" class="nexus-select" @bind="_selectedBookId">
<option value="">All Books (Global Search)</option>
<option value="">[ All Resources (Including Global Catalog) ]</option>
@if (_books != null)
{
@foreach (var book in _books)
@@ -121,7 +90,7 @@
@bind:event="oninput"
@onkeyup="HandleKeyUp"
disabled="@_isLoading" />
<button class="btn-nexus btn-nexus-primary search-btn"
<button class="search-btn"
disabled="@(string.IsNullOrWhiteSpace(_question) || _isLoading)"
@onclick="AskQuestionAsync">
@if (_isLoading)
@@ -146,20 +115,52 @@
private List<LastReadBookDto>? _books;
private List<ChatMessage> _chatMessages = new();
protected override async Task OnInitializedAsync()
{
LibraryStateService.OnBooksChanged += HandleBooksChanged;
await LoadBooksAsync();
}
private async Task LoadBooksAsync()
{
try
{
_books = await Http.GetFromJsonAsync<List<LastReadBookDto>>("api/library/books");
LibraryStateService.OwnedBooks = _books;
}
catch (Exception ex)
{
Console.WriteLine($"[Intelligence] Failed to load books for scope selector: {ex.Message}");
Console.WriteLine($"[Intelligence] Failed to load books: {ex.Message}");
}
}
private void HandleBooksChanged()
{
_ = InvokeAsync(async () =>
{
_books = LibraryStateService.OwnedBooks;
// Check if any existing message in the chat thread was paywalled,
// and update its owned state dynamically.
if (_books != null)
{
foreach (var message in _chatMessages)
{
if (message.IsPaywalled && !string.IsNullOrEmpty(message.SourceBookTitle))
{
var isNowOwned = _books.Any(b => b.Title.Equals(message.SourceBookTitle, StringComparison.OrdinalIgnoreCase));
if (isNowOwned)
{
message.IsPaywalled = false;
}
}
}
}
StateHasChanged();
});
}
private async Task HandleKeyUp(KeyboardEventArgs e)
{
if (e.Key == "Enter" && !string.IsNullOrWhiteSpace(_question) && !_isLoading)
@@ -176,7 +177,7 @@
_question = string.Empty; // Clear input field immediately
_isLoading = true;
// Add user query message
// Add user query message with custom background in renderer
_chatMessages.Add(new ChatMessage
{
Sender = "User",
@@ -196,18 +197,16 @@
var authState = await AuthStateProvider.GetAuthenticationStateAsync();
var tenantId = authState.User.FindFirst("TenantId")?.Value ?? "global";
var userId = authState.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
var result = await KnowledgeService.AskQuestionAsync(userQuestion, tenantId, ebookId);
if (ebookId == null)
{
var result = await KnowledgeService.GetGlobalIntelligenceAsync(userQuestion, userId, tenantId);
if (result.IsSuccess)
{
var response = result.Value;
_chatMessages.Add(new ChatMessage
{
Sender = "AI",
Text = response.Answer,
Segments = ParseSegments(response.Answer),
Citations = response.Citations
});
var chatMsg = CreateGlobalAiChatMessage(response, _books);
_chatMessages.Add(chatMsg);
}
else
{
@@ -220,6 +219,60 @@
});
}
}
else
{
var result = await KnowledgeService.AskQuestionAsync(userQuestion, tenantId, ebookId);
if (result.IsSuccess)
{
var response = result.Value;
// --- Paywall Simulation Logic ---
// If the user does not own "Architektura .NET 10 i Ekosystem Blazor"
// and the question refers to Blazor/architecture/C#/etc,
// we simulate that the RAG search pulled a citation from that unowned book.
var hasBlazorBook = _books != null && _books.Any(b => b.Title.Contains("Architektura .NET 10", StringComparison.OrdinalIgnoreCase));
var isSimulatingPaywall = !hasBlazorBook &&
(userQuestion.Contains("blazor", StringComparison.OrdinalIgnoreCase) ||
userQuestion.Contains("net", StringComparison.OrdinalIgnoreCase) ||
userQuestion.Contains("architektura", StringComparison.OrdinalIgnoreCase) ||
userQuestion.Contains("c#", StringComparison.OrdinalIgnoreCase));
if (isSimulatingPaywall)
{
var mockCitationId = Guid.NewGuid().ToString();
var mockCitation = new CitationDto
{
CitationId = mockCitationId,
SourceBook = "Architektura .NET 10 i Ekosystem Blazor",
Author = "Nexus Architect",
Snippet = "Konfiguracja kontenera dependency injection w standardzie .NET 10 Blazor przy użyciu Native AOT wymaga wyeliminowania dynamicznej refleksji.",
PageNumber = 42
};
if (response.Citations == null)
{
response.Citations = new List<CitationDto>();
}
response.Citations.Add(mockCitation);
response.Answer = "Aby poprawnie skonfigurować architekturę .NET 10 Blazor pod Native AOT, należy unikać dynamicznego ładowania typów. Konieczne jest używanie generatorów kodu źródłowego (Source Generators) do rejestracji zależności w kontenerze DI. W ten sposób kompilator AOT może przeanalizować graf zależności podczas kompilacji. [Source ID: " + mockCitationId + "]\n\nPełny przykładowy kod konfiguracji Program.cs wygląda następująco:\n```csharp\nvar builder = WebApplication.CreateBuilder(args);\nbuilder.Services.AddSingleton<IService, AotService>();\n```";
}
var chatMsg = CreateAiChatMessage(response, _books);
_chatMessages.Add(chatMsg);
}
else
{
var errMsg = $"Error: {result.Errors.FirstOrDefault()?.Message ?? "An error occurred."}";
_chatMessages.Add(new ChatMessage
{
Sender = "AI",
Text = errMsg,
Segments = new List<ResponseSegment> { new ResponseSegment { Text = errMsg, IsCitation = false } }
});
}
}
}
catch (Exception ex)
{
var errMsg = $"Network/API Error: {ex.Message}";
@@ -237,12 +290,115 @@
}
}
private ChatMessage CreateAiChatMessage(GroundedResponseDto response, List<LastReadBookDto>? ownedBooks)
{
var msg = new ChatMessage
{
Sender = "AI",
Text = response.Answer,
Segments = ParseSegments(response.Answer),
Citations = response.Citations
};
// Check if paywalled: citations contain a book not in ownedBooks
var unownedCitation = response.Citations.FirstOrDefault(c =>
!string.IsNullOrEmpty(c.SourceBook) &&
(ownedBooks == null || !ownedBooks.Any(ob => ob.Title.Equals(c.SourceBook, StringComparison.OrdinalIgnoreCase))));
if (unownedCitation != null)
{
msg.IsPaywalled = true;
msg.SourceBookTitle = unownedCitation.SourceBook;
// Split sentences *once* during creation for Native AOT rendering performance
var (clear, _) = SplitSentences(response.Answer);
msg.ClearText = clear;
msg.BlurredTeaserText = "\n\n// [Blokada Paywall] Pełna treść oraz kody źródłowe C# zostały zablokowane.\npublic class ArchitekturaProcessor {\n public async Task ProcessAsync() {\n // Zaimplementuj wzorzec CQRS...\n throw new PaywallException(\"Kup publikację w katalogu\");\n }\n}";
}
else
{
msg.IsPaywalled = false;
msg.ClearText = response.Answer;
msg.BlurredTeaserText = string.Empty;
}
return msg;
}
private ChatMessage CreateGlobalAiChatMessage(NexusReader.Application.Queries.Intelligence.IntelligenceResponse response, List<LastReadBookDto>? ownedBooks)
{
var msg = new ChatMessage
{
Sender = "AI",
Text = response.ResponseText,
Segments = ParseSegments(response.ResponseText),
Citations = response.Citations ?? new List<CitationDto>()
};
if (response.HasPaywall)
{
msg.IsPaywalled = true;
msg.SourceBookTitle = response.LockedBookTitle ?? string.Empty;
// Split sentences *once* during creation for Native AOT rendering performance
var (clear, _) = SplitSentences(response.ResponseText);
msg.ClearText = clear;
msg.BlurredTeaserText = "\n\n// [Blokada Paywall] Pełna treść oraz kody źródłowe C# zostały zablokowane.\npublic class ArchitekturaProcessor {\n public async Task ProcessAsync() {\n // Zaimplementuj wzorzec CQRS...\n throw new PaywallException(\"Kup publikację w katalogu\");\n }\n}";
}
else
{
msg.IsPaywalled = false;
msg.ClearText = response.ResponseText;
msg.BlurredTeaserText = string.Empty;
}
return msg;
}
private (string ClearText, string BlurredText) SplitSentences(string text)
{
if (string.IsNullOrEmpty(text)) return (string.Empty, string.Empty);
int sentenceCount = 0;
int firstSplit = -1;
int secondSplit = -1;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == '.' || c == '?' || c == '!')
{
if (i + 1 == text.Length || char.IsWhiteSpace(text[i + 1]))
{
sentenceCount++;
if (sentenceCount == 1)
{
firstSplit = i + 1;
}
else if (sentenceCount == 2)
{
secondSplit = i + 1;
break;
}
}
}
}
int splitIndex = secondSplit != -1 ? secondSplit : firstSplit;
if (splitIndex != -1 && splitIndex < text.Length)
{
return (text.Substring(0, splitIndex), text.Substring(splitIndex));
}
return (text, string.Empty);
}
private List<ResponseSegment> ParseSegments(string text)
{
var segments = new List<ResponseSegment>();
if (string.IsNullOrEmpty(text)) return segments;
// Matches [Source ID: some-id] OR raw GUIDs in brackets [e225e58f-7539-cd51-e0ab-82741ec7e65c]
var regex = new System.Text.RegularExpressions.Regex(
@"\[Source ID:\s*([^\]]+)\]|\[([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\]",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
@@ -285,28 +441,8 @@
return segments;
}
private MarkupString RenderMarkdown(string text)
public void Dispose()
{
if (string.IsNullOrEmpty(text)) return new MarkupString(string.Empty);
// 1. HTML Encode to prevent XSS
var html = System.Net.WebUtility.HtmlEncode(text);
// 2. Bold: **text** -> <strong>text</strong>
html = System.Text.RegularExpressions.Regex.Replace(html, @"\*\*(.*?)\*\*", "<strong>$1</strong>");
// 3. Italic: *text* -> <em>text</em>
html = System.Text.RegularExpressions.Regex.Replace(html, @"\*(.*?)\*", "<em>$1</em>");
// 4. Code blocks: ```language ... ``` -> <pre class="nexus-code-block"><code>...</code></pre>
html = System.Text.RegularExpressions.Regex.Replace(html, @"```(?:[a-zA-Z0-9+#]+)?\s*([\s\S]*?)\s*```", "<pre class=\"nexus-code-block\"><code>$1</code></pre>");
// 5. Inline Code: `code` -> <code class="nexus-inline-code">code</code>
html = System.Text.RegularExpressions.Regex.Replace(html, @"`(.*?)`", "<code class=\"nexus-inline-code\">$1</code>");
// 6. Newlines: \n -> <br />
html = html.Replace("\n", "<br />");
return new MarkupString(html);
LibraryStateService.OnBooksChanged -= HandleBooksChanged;
}
}
@@ -1,33 +1,18 @@
.intelligence-page {
padding: 2rem;
max-width: 1100px;
margin: 0 auto;
height: calc(100vh - 100px);
margin: -2.5rem;
height: 100vh;
background: #121214;
display: flex;
flex-direction: column;
animation: fadeIn 0.5s ease-out;
overflow: hidden;
animation: fadeIn 0.4s ease-out;
}
.intelligence-header {
margin-bottom: 1.5rem;
flex-shrink: 0;
}
.neon-glow-text {
font-family: var(--nexus-font-sans);
font-size: 2.5rem;
font-weight: 800;
margin: 0 0 0.25rem 0;
background: linear-gradient(135deg, var(--nexus-neon) 0%, rgba(0, 255, 153, 0.7) 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
filter: drop-shadow(0 0 8px rgba(0, 255, 153, 0.2));
}
.subtitle {
font-size: 0.95rem;
color: rgba(255, 255, 255, 0.6);
margin: 0;
@media (max-width: 768px) {
.intelligence-page {
margin: -1.25rem;
height: calc(100vh - 60px);
}
}
.intelligence-layout {
@@ -35,202 +20,90 @@
display: flex;
flex-direction: column;
overflow: hidden;
padding: 0;
height: 100%;
}
.chat-thread-container {
flex-grow: 1;
overflow-y: auto;
padding: 2rem;
padding: 3rem 4rem 2rem 4rem;
display: flex;
flex-direction: column;
}
@media (max-width: 768px) {
.chat-thread-container {
padding: 1.5rem 1rem;
}
}
/* Custom Scrollbars */
.chat-thread-container::-webkit-scrollbar {
width: 6px;
}
.chat-thread-container::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.01);
background: transparent;
}
.chat-thread-container::-webkit-scrollbar-thumb {
background: rgba(0, 255, 153, 0.2);
background: rgba(16, 185, 129, 0.2);
border-radius: 4px;
}
.chat-thread-container::-webkit-scrollbar-thumb:hover {
background: rgba(0, 255, 153, 0.4);
background: rgba(16, 185, 129, 0.4);
}
.chat-bubbles-scroll {
display: flex;
flex-direction: column;
gap: 1.5rem;
width: 100%;
}
.message-row {
display: flex;
gap: 1rem;
width: 100%;
max-width: 85%;
animation: bubble-fade-in 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.user-row {
align-self: flex-end;
flex-direction: row-reverse;
}
.ai-row {
align-self: flex-start;
}
.message-avatar {
width: 38px;
height: 38px;
border-radius: 50%;
/* State 1: Initial Empty Screen */
.welcome-state {
text-align: center;
padding: 4rem 2rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: 1.1rem;
flex-shrink: 0;
margin-top: auto;
margin-bottom: auto;
animation: fade-in-up 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.user-row .message-avatar {
background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%);
color: #ffffff;
border: 1px solid rgba(255, 255, 255, 0.2);
box-shadow: 0 0 10px rgba(255, 255, 255, 0.1);
.welcome-icon {
margin-bottom: 2rem;
filter: drop-shadow(0 0 15px rgba(139, 130, 115, 0.15));
}
.ai-row .message-avatar {
background: linear-gradient(135deg, #005f38 0%, #004024 100%);
color: #e6fffa;
border: 1px solid rgba(0, 255, 153, 0.4);
box-shadow: 0 0 10px rgba(0, 255, 153, 0.25);
}
.message-bubble {
padding: 1.25rem 1.5rem;
border-radius: var(--radius-lg);
position: relative;
line-height: 1.6;
font-size: 0.975rem;
}
.user-bubble {
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
color: #ffffff;
border-top-right-radius: 4px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}
.ai-bubble {
background: rgba(10, 20, 30, 0.55);
border: 1px solid rgba(0, 255, 153, 0.2);
color: #e2e8f0;
border-top-left-radius: 4px;
box-shadow: 0 4px 15px rgba(0, 255, 153, 0.05);
flex-grow: 1;
}
.message-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
font-size: 0.75rem;
opacity: 0.6;
}
.sender-name {
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.message-time {
font-family: monospace;
}
.message-content {
word-break: break-word;
}
/* Paragraph Spacing & Markdown */
.message-content p {
margin: 0 0 1rem 0;
}
.message-content p:last-child {
margin-bottom: 0;
}
.nexus-code-block {
background: rgba(0, 0, 0, 0.4) !important;
border: 1px solid rgba(255, 255, 255, 0.08) !important;
border-radius: var(--radius-sm);
padding: 1rem;
margin: 1rem 0;
overflow-x: auto;
font-family: 'Fira Code', monospace;
font-size: 0.85rem;
color: #a7f3d0;
}
.nexus-inline-code {
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 4px;
padding: 0.15rem 0.35rem;
font-family: monospace;
font-size: 0.9em;
color: #f472b6; /* Light pink for inline code */
}
/* Pending State Bubble */
.pending-bubble {
border-color: rgba(0, 255, 153, 0.4);
box-shadow: 0 0 15px rgba(0, 255, 153, 0.1);
}
.typing-indicator {
display: flex;
gap: 4px;
align-items: center;
margin-bottom: 0.5rem;
}
.typing-indicator span {
width: 8px;
height: 8px;
background: var(--nexus-neon);
border-radius: 50%;
display: inline-block;
animation: typing-bounce 1.4s infinite ease-in-out both;
}
.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }
.loading-label {
font-size: 0.85rem;
color: rgba(255, 255, 255, 0.5);
font-style: italic;
.welcome-prompt {
font-family: var(--nexus-font-sans, inherit);
color: #e4e4e7;
font-size: 1.35rem;
font-weight: 500;
letter-spacing: -0.2px;
}
/* Input Controls */
.chat-input-controls {
padding: 1.5rem 2rem 2rem 2rem;
background: rgba(0, 0, 0, 0.2);
border-top: 1px solid rgba(255, 255, 255, 0.05);
padding: 1.5rem 4rem 3rem 4rem;
background: linear-gradient(to top, #121214 70%, rgba(18, 18, 20, 0));
flex-shrink: 0;
}
@media (max-width: 768px) {
.chat-input-controls {
padding: 1rem 1rem 1.5rem 1rem;
}
}
.input-panel-wrapper {
display: flex;
flex-direction: column;
gap: 0.75rem;
max-width: 900px;
margin: 0 auto;
width: 100%;
}
.scope-bar {
@@ -241,46 +114,48 @@
.scope-selector {
display: flex;
align-items: center;
gap: 0.5rem;
gap: 0.6rem;
font-size: 0.85rem;
color: rgba(255, 255, 255, 0.5);
font-weight: 500;
color: #8b8273;
}
.nexus-select {
background: rgba(255, 255, 255, 0.02);
border: 1px solid rgba(255, 255, 255, 0.08);
color: #ffffff;
padding: 0.35rem 2rem 0.35rem 0.75rem;
border-radius: var(--radius-sm);
background: #1a1a1e;
border: 1px solid rgba(255, 255, 255, 0.06);
color: #e4e4e7;
padding: 0.4rem 2rem 0.4rem 0.75rem;
border-radius: 8px;
outline: none;
cursor: pointer;
font-size: 0.85rem;
transition: all 0.3s ease;
font-size: 0.825rem;
transition: all 0.25s ease;
appearance: none;
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238b8273' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
background-repeat: no-repeat;
background-position: right 0.75rem center;
background-size: 0.85em;
}
.nexus-select:focus {
border-color: var(--nexus-neon);
box-shadow: 0 0 8px rgba(0, 255, 153, 0.2);
border-color: #10b981;
box-shadow: 0 0 8px rgba(16, 185, 129, 0.15);
}
.input-field-group {
display: flex;
background: rgba(255, 255, 255, 0.02);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: var(--radius-md);
padding: 0.35rem;
background: #1a1a1e;
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 12px;
padding: 0.4rem;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}
.input-field-group:focus-within {
border-color: var(--nexus-neon);
background: rgba(0, 255, 153, 0.01);
box-shadow: 0 0 15px rgba(0, 255, 153, 0.15);
border-color: rgba(16, 185, 129, 0.5);
background: #1a1a1e;
box-shadow: 0 10px 35px rgba(16, 185, 129, 0.1);
}
.nexus-input {
@@ -288,68 +163,92 @@
background: transparent;
border: none;
color: #ffffff;
font-size: 1rem;
font-size: 0.975rem;
outline: none;
padding: 0.5rem 1rem;
}
.nexus-input::placeholder {
color: rgba(255, 255, 255, 0.35);
color: #8b8273;
}
.search-btn {
width: 46px;
height: 46px;
padding: 0 !important;
width: 44px;
height: 44px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
border-radius: 8px;
background: #10b981;
border: none;
color: #121214;
cursor: pointer;
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}
.welcome-state {
text-align: center;
color: rgba(255, 255, 255, 0.5);
padding: 4rem 2rem;
.search-btn:hover:not(:disabled) {
background: #0d9668;
transform: scale(1.02);
}
.search-btn:disabled {
background: rgba(26, 26, 30, 0.8);
color: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.02);
cursor: not-allowed;
}
/* Typing / Loading Indicators */
.message-bubble.pending-bubble {
border-color: rgba(16, 185, 129, 0.25);
background: rgba(16, 185, 129, 0.03);
max-width: 450px;
}
.typing-indicator {
display: flex;
flex-direction: column;
gap: 4px;
align-items: center;
justify-content: center;
height: 100%;
margin-bottom: 0.6rem;
}
.welcome-icon {
color: rgba(0, 255, 153, 0.4);
margin-bottom: 1.5rem;
filter: drop-shadow(0 0 10px rgba(0, 255, 153, 0.2));
animation: pulse 2.5s infinite alternate;
.typing-indicator span {
width: 7px;
height: 7px;
background: #10b981;
border-radius: 50%;
display: inline-block;
animation: typing-bounce 1.4s infinite ease-in-out both;
}
.welcome-state h3 {
color: #ffffff;
font-size: 1.5rem;
margin: 0 0 0.75rem 0;
}
.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }
.welcome-state p {
max-width: 550px;
margin: 0;
font-size: 0.95rem;
line-height: 1.6;
.loading-label {
font-size: 0.825rem;
color: rgba(255, 255, 255, 0.45);
font-style: italic;
}
.btn-spinner {
width: 20px;
height: 20px;
border: 2px solid rgba(0, 0, 0, 0.1);
width: 18px;
height: 18px;
border: 2px solid rgba(18, 18, 20, 0.1);
border-radius: 50%;
border-top-color: #000000;
border-top-color: #121214;
animation: spin 0.8s linear infinite;
}
/* Keyframe Animations */
@keyframes bubble-fade-in {
0% { opacity: 0; transform: translateY(10px) scale(0.98); }
100% { opacity: 1; transform: translateY(0) scale(1); }
/* Animations */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fade-in-up {
0% { opacity: 0; transform: translateY(15px); }
100% { opacity: 1; transform: translateY(0); }
}
@keyframes typing-bounce {
@@ -357,11 +256,6 @@
50% { transform: translateY(-4px); }
}
@keyframes pulse {
0% { transform: scale(0.96); opacity: 0.8; }
100% { transform: scale(1.04); opacity: 1; }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
@@ -1,11 +1,13 @@
@page "/my-books"
@attribute [Authorize]
@implements IDisposable
@using NexusReader.UI.Shared.Components.Organisms
@using NexusReader.Application.DTOs.User
@using NexusReader.UI.Shared.Services
@using System.Net.Http.Json
@inject HttpClient Http
@inject IReaderNavigationService ReaderNavigation
@inject ILibraryStateService LibraryStateService
<div class="my-books-page">
<header class="my-books-header">
@@ -108,6 +110,11 @@
private bool _isLoading = true;
private List<LastReadBookDto>? _books;
protected override void OnInitialized()
{
LibraryStateService.OnBooksChanged += HandleBooksChanged;
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
@@ -116,6 +123,11 @@
}
}
private void HandleBooksChanged()
{
_ = InvokeAsync(LoadBooksAsync);
}
private async Task LoadBooksAsync()
{
_isLoading = true;
@@ -149,4 +161,9 @@
{
ReaderNavigation.NavigateToBook(bookId);
}
public void Dispose()
{
LibraryStateService.OnBooksChanged -= HandleBooksChanged;
}
}
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using NexusReader.Application.DTOs.User;
namespace NexusReader.UI.Shared.Services;
public interface ILibraryStateService
{
List<LastReadBookDto>? OwnedBooks { get; set; }
event Action? OnBooksChanged;
void NotifyBooksChanged();
}
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using NexusReader.Application.DTOs.User;
namespace NexusReader.UI.Shared.Services;
public class LibraryStateService : ILibraryStateService
{
private List<LastReadBookDto>? _ownedBooks;
public List<LastReadBookDto>? OwnedBooks
{
get => _ownedBooks;
set
{
_ownedBooks = value;
NotifyBooksChanged();
}
}
public event Action? OnBooksChanged;
public void NotifyBooksChanged()
{
OnBooksChanged?.Invoke();
}
}
@@ -0,0 +1,72 @@
using System;
namespace NexusReader.UI.Shared.Services;
/// <summary>
/// AOT-safe string parsing utility to isolate paywall teaser details without regex overhead.
/// </summary>
public static class PaywallParser
{
public static bool TryParsePaywallTrigger(
string rawText,
out string displayTeaserText,
out Guid lockedBookId,
out string lockedBookTitle,
out int localScore,
out int globalScore)
{
displayTeaserText = rawText;
lockedBookId = Guid.Empty;
lockedBookTitle = string.Empty;
localScore = 0;
globalScore = 0;
if (string.IsNullOrEmpty(rawText))
return false;
ReadOnlySpan<char> span = rawText.AsSpan();
int tokenStartIndex = span.IndexOf("[PAYWALL_TRIGGER:");
if (tokenStartIndex == -1)
return false;
displayTeaserText = span.Slice(0, tokenStartIndex).Trim().ToString();
ReadOnlySpan<char> tokenContent = span.Slice(tokenStartIndex + "[PAYWALL_TRIGGER:".Length);
int tokenEndIndex = tokenContent.IndexOf(']');
if (tokenEndIndex == -1)
return false;
tokenContent = tokenContent.Slice(0, tokenEndIndex);
int firstColonIdx = tokenContent.IndexOf(':');
if (firstColonIdx == -1)
return false;
ReadOnlySpan<char> guidSpan = tokenContent.Slice(0, firstColonIdx);
if (!Guid.TryParse(guidSpan, out lockedBookId))
return false;
ReadOnlySpan<char> remaining = tokenContent.Slice(firstColonIdx + 1);
int lastColonIdx = remaining.LastIndexOf(':');
if (lastColonIdx == -1)
return false;
ReadOnlySpan<char> globalScoreSpan = remaining.Slice(lastColonIdx + 1);
if (!int.TryParse(globalScoreSpan, out globalScore))
return false;
remaining = remaining.Slice(0, lastColonIdx);
int secondLastColonIdx = remaining.LastIndexOf(':');
if (secondLastColonIdx == -1)
return false;
ReadOnlySpan<char> localScoreSpan = remaining.Slice(secondLastColonIdx + 1);
if (!int.TryParse(localScoreSpan, out localScore))
return false;
lockedBookTitle = remaining.Slice(0, secondLastColonIdx).ToString();
return true;
}
}
+1
View File
@@ -27,6 +27,7 @@ builder.Services.AddScoped<IReaderNavigationService, ReaderNavigationService>();
builder.Services.AddScoped<IKnowledgeGraphService, KnowledgeGraphService>();
builder.Services.AddScoped<IReaderInteractionService, ReaderInteractionService>();
builder.Services.AddScoped<IReaderStateService, ReaderStateService>();
builder.Services.AddScoped<ILibraryStateService, LibraryStateService>();
builder.Services.AddScoped<KnowledgeCoordinator>();
builder.Services.AddScoped<ISyncService, SyncService>();
@@ -2,6 +2,8 @@ using System.Net.Http.Json;
using FluentResults;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.DTOs.AI;
using NexusReader.Application.Common;
using NexusReader.Application.Queries.Intelligence;
namespace NexusReader.Web.Client.Services;
@@ -113,6 +115,34 @@ public class WasmKnowledgeService : IKnowledgeService
}
}
public async Task<Result<IntelligenceResponse>> GetGlobalIntelligenceAsync(string queryText, string userId, string tenantId, CancellationToken cancellationToken = default)
{
try
{
var response = await _httpClient.PostAsJsonAsync(
"/api/intelligence",
new GetGlobalIntelligenceRequest(queryText),
AppJsonContext.Default.GetGlobalIntelligenceRequest,
cancellationToken);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<IntelligenceResponse>(
AppJsonContext.Default.IntelligenceResponse,
cancellationToken: cancellationToken);
return result != null ? Result.Ok(result) : Result.Fail("Failed to deserialize global intelligence response.");
}
var errorBody = await response.Content.ReadAsStringAsync(cancellationToken);
return Result.Fail($"Server error ({response.StatusCode}): {errorBody}");
}
catch (Exception ex)
{
return Result.Fail(new Error($"Network error: {ex.Message}").CausedBy(ex));
}
}
private async Task<Result<KnowledgePacket>> CallKnowledgeApiAsync(string endpoint, string text, Guid? ebookId, CancellationToken cancellationToken)
{
try
+80
View File
@@ -36,6 +36,11 @@ builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, NexusReader.Application.Common.AppJsonContext.Default);
});
// Enable detailed circuit errors for ServerSide Blazor components
builder.Services.AddServerSideBlazor()
.AddCircuitOptions(options =>
@@ -57,6 +62,7 @@ builder.Services.AddScoped<IReaderNavigationService, ReaderNavigationService>();
builder.Services.AddScoped<IKnowledgeGraphService, KnowledgeGraphService>();
builder.Services.AddScoped<IReaderInteractionService, ReaderInteractionService>();
builder.Services.AddScoped<IReaderStateService, ReaderStateService>();
builder.Services.AddScoped<ILibraryStateService, LibraryStateService>();
builder.Services.AddScoped<KnowledgeCoordinator>();
builder.Services.AddScoped<ISyncService, SyncService>();
@@ -414,6 +420,37 @@ knowledgeApi.MapDelete("/", async (IKnowledgeService knowledgeService) =>
return Results.BadRequest(errorMsg);
});
app.MapPost("/api/intelligence", async (
[FromBody] NexusReader.Application.Queries.Intelligence.GetGlobalIntelligenceRequest request,
ClaimsPrincipal user,
IMediator mediator) =>
{
var userId = user.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(userId)) return Results.Unauthorized();
var tenantId = user.FindFirstValue("TenantId") ?? "global";
var result = await mediator.Send(new NexusReader.Application.Queries.Intelligence.GetGlobalIntelligenceQuery(request.QueryText, userId, tenantId));
if (result.IsSuccess) return Results.Ok(result.Value);
var errorMsg = result.Errors.Count > 0 ? result.Errors[0].Message : "Failed to execute global intelligence query";
return Results.BadRequest(errorMsg);
}).RequireAuthorization();
app.MapGet("/api/recommendations", async (
ClaimsPrincipal user,
IMediator mediator) =>
{
var userId = user.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(userId)) return Results.Unauthorized();
var result = await mediator.Send(new NexusReader.Application.Queries.Recommendations.GetContextualRecommendationsQuery(userId));
if (result.IsSuccess) return Results.Ok(result.Value);
var errorMsg = result.Errors.Count > 0 ? result.Errors[0].Message : "Failed to fetch contextual recommendations";
return Results.BadRequest(errorMsg);
}).RequireAuthorization();
app.MapPost("/api/library/ingest", async ([FromBody] IngestEbookRequest request, ClaimsPrincipal user, IMediator mediator) =>
{
var userId = user.FindFirstValue(ClaimTypes.NameIdentifier);
@@ -454,6 +491,48 @@ app.MapGet("/api/library/books", async (ClaimsPrincipal user, IMediator mediator
return Results.BadRequest(errorMsg);
}).RequireAuthorization();
app.MapPost("/api/library/purchase", async (
ClaimsPrincipal user,
[FromBody] PurchaseBookRequest request,
IDbContextFactory<AppDbContext> dbContextFactory) =>
{
var userId = user.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(userId)) return Results.Unauthorized();
using var dbContext = await dbContextFactory.CreateDbContextAsync();
// Find or create author
var authorName = "Nexus Architect";
var author = await dbContext.Authors.FirstOrDefaultAsync(a => a.Name == authorName);
if (author == null)
{
author = new Author { Name = authorName };
dbContext.Authors.Add(author);
await dbContext.SaveChangesAsync();
}
// Check if the book already exists for the user
var bookExists = await dbContext.Ebooks.AnyAsync(e => e.UserId == userId && e.Title == request.Title);
if (!bookExists)
{
var newBook = new Ebook
{
Title = request.Title,
AuthorId = author.Id,
UserId = userId,
FilePath = "wwwroot/assets/book.epub",
AddedDate = DateTime.UtcNow,
Progress = 0,
Description = "Zaawansowany kurs budowania skalowalnych SaaS z Native AOT, CQRS, MediatR, FluentResults i izolowanym systemem stylów Blazor CSS.",
IsReadyForReading = true
};
dbContext.Ebooks.Add(newBook);
await dbContext.SaveChangesAsync();
}
return Results.Ok();
}).RequireAuthorization();
app.MapGet("/api/book/{bookId:guid}/concepts-map", async (
Guid bookId,
ClaimsPrincipal user,
@@ -729,3 +808,4 @@ public record KnowledgeRequest(string Text, Guid? EbookId = null);
public record GroundednessRequest(string Answer, string Context);
public record SemanticSearchRequest(string QueryText, int Limit = 5);
public record AskQuestionRequest(string Question, Guid? EbookId = null, int Limit = 5);
public record PurchaseBookRequest(string Title);
+6 -1
View File
@@ -9,5 +9,10 @@
"AllowRegistration": false,
"AllowPasswordReset": false
},
"ApiBaseUrl": "http://localhost:5000"
"RagMonetization": {
"BaselineThreshold": 0.45,
"DeltaThreshold": 0.15,
"UpgradeThreshold": 0.70
},
"ApiBaseUrl": "http://localhost:5104"
}
+6 -1
View File
@@ -31,5 +31,10 @@
"MaxOutputTokens": 8192
}
},
"ApiBaseUrl": "http://localhost:5000"
"RagMonetization": {
"BaselineThreshold": 0.45,
"DeltaThreshold": 0.15,
"UpgradeThreshold": 0.70
},
"ApiBaseUrl": "http://localhost:5104"
}
@@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using NexusReader.Application.Abstractions.Persistence;
using NexusReader.Application.Queries.Recommendations;
using NexusReader.Infrastructure.Queries;
using Xunit;
namespace NexusReader.Application.Tests.Queries;
public class GetContextualRecommendationsQueryTests
{
private readonly Mock<IUserReadingStateStore> _readingStateStoreMock;
private readonly Mock<IUserLibraryStore> _libraryStoreMock;
private readonly Mock<IVectorSearchStore> _vectorSearchStoreMock;
private readonly GetContextualRecommendationsQueryHandler _handler;
public GetContextualRecommendationsQueryTests()
{
_readingStateStoreMock = new Mock<IUserReadingStateStore>();
_libraryStoreMock = new Mock<IUserLibraryStore>();
_vectorSearchStoreMock = new Mock<IVectorSearchStore>();
_handler = new GetContextualRecommendationsQueryHandler(
_readingStateStoreMock.Object,
_libraryStoreMock.Object,
_vectorSearchStoreMock.Object
);
}
[Fact]
public async Task Handle_WithNoActiveReadingState_ReturnsEmptyRecommendations()
{
// Arrange
var userId = "user-123";
_readingStateStoreMock.Setup(s => s.GetActiveReadingStateAsync(userId, It.IsAny<CancellationToken>()))
.ReturnsAsync((null, null, null));
var query = new GetContextualRecommendationsQuery(userId);
// Act
var result = await _handler.Handle(query, CancellationToken.None);
// Assert
result.IsSuccess.Should().BeTrue();
result.Value.Recommendations.Should().BeEmpty();
}
[Fact]
public async Task Handle_WithActiveReadingState_PerformsSimilaritySearchAndReturnsRecommendations()
{
// Arrange
var userId = "user-123";
var activeEbookId = Guid.NewGuid();
var activeChapterId = "chapter-1";
var tenantId = "tenant-abc";
var chapterContent = "Active chapter content description";
_readingStateStoreMock.Setup(s => s.GetActiveReadingStateAsync(userId, It.IsAny<CancellationToken>()))
.ReturnsAsync((activeEbookId, activeChapterId, tenantId));
_readingStateStoreMock.Setup(s => s.GetChapterContentAsync(activeChapterId, It.IsAny<CancellationToken>()))
.ReturnsAsync(chapterContent);
// Mock vector search results using clean VectorChunk list
var targetEbookId1 = Guid.NewGuid();
var targetEbookId2 = Guid.NewGuid();
var mockChunks = new List<VectorChunk>
{
new VectorChunk(
Content: "Result pattern details",
EbookId: targetEbookId1.ToString(),
Score: 0.88,
MetadataJson: "",
BookTitle: "Clean Architecture deep dive",
ChapterTitle: "Chapter 3: Result Pattern"
),
new VectorChunk(
Content: "Performance optimizations",
EbookId: targetEbookId2.ToString(),
Score: 0.72,
MetadataJson: "",
BookTitle: "Advanced C# 14",
ChapterTitle: "Chapter 5: Span and Performance"
)
};
_vectorSearchStoreMock.Setup(v => v.SearchGlobalExcludeAsync(
chapterContent,
tenantId,
activeEbookId,
2,
It.IsAny<CancellationToken>()))
.ReturnsAsync(mockChunks);
// User owns the second book but not the first one
_libraryStoreMock.Setup(l => l.GetOwnedBookIdsAsync(userId, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<Guid> { targetEbookId2 });
var query = new GetContextualRecommendationsQuery(userId);
// Act
var result = await _handler.Handle(query, CancellationToken.None);
// Assert
result.IsSuccess.Should().BeTrue();
result.Value.Recommendations.Should().HaveCount(2);
var firstRec = result.Value.Recommendations.First();
firstRec.BookTitle.Should().Be("Clean Architecture deep dive");
firstRec.ChapterTitle.Should().Be("Chapter 3: Result Pattern");
firstRec.MatchPercentage.Should().Be(88);
firstRec.IsPremiumUpsell.Should().BeTrue(); // User does not own book 1
firstRec.TargetBookId.Should().Be(targetEbookId1);
var secondRec = result.Value.Recommendations.Last();
secondRec.BookTitle.Should().Be("Advanced C# 14");
secondRec.ChapterTitle.Should().Be("Chapter 5: Span and Performance");
secondRec.MatchPercentage.Should().Be(72);
secondRec.IsPremiumUpsell.Should().BeFalse(); // User owns book 2
secondRec.TargetBookId.Should().Be(targetEbookId2);
}
}
@@ -0,0 +1,81 @@
using System;
using FluentAssertions;
using NexusReader.UI.Shared.Services;
using Xunit;
namespace NexusReader.Application.Tests.Services;
public class PaywallParserTests
{
[Fact]
public void TryParsePaywallTrigger_WithValidSimpleToken_ReturnsTrueAndCorrectValues()
{
// Arrange
var guid = Guid.NewGuid();
var rawText = $"Teaser sentence. [PAYWALL_TRIGGER:{guid}:Clean Book Title:45:82]";
// Act
var result = PaywallParser.TryParsePaywallTrigger(
rawText,
out var teaser,
out var bookId,
out var title,
out var localScore,
out var globalScore);
// Assert
result.Should().BeTrue();
teaser.Should().Be("Teaser sentence.");
bookId.Should().Be(guid);
title.Should().Be("Clean Book Title");
localScore.Should().Be(45);
globalScore.Should().Be(82);
}
[Fact]
public void TryParsePaywallTrigger_WithColonsInBookTitle_ReturnsTrueAndCorrectValues()
{
// Arrange
var guid = Guid.NewGuid();
var rawText = $"Teaser text. [PAYWALL_TRIGGER:{guid}:Architektura: .NET 10 i C# 14:15:99]";
// Act
var result = PaywallParser.TryParsePaywallTrigger(
rawText,
out var teaser,
out var bookId,
out var title,
out var localScore,
out var globalScore);
// Assert
result.Should().BeTrue();
teaser.Should().Be("Teaser text.");
bookId.Should().Be(guid);
title.Should().Be("Architektura: .NET 10 i C# 14");
localScore.Should().Be(15);
globalScore.Should().Be(99);
}
[Theory]
[InlineData("")]
[InlineData("Just plain text with no trigger token.")]
[InlineData("Plain text [PAYWALL_TRIGGER:invalid-guid:Title:50:80]")]
[InlineData("Plain text [PAYWALL_TRIGGER:00000000-0000-0000-0000-000000000000:Title:50:invalid]")]
[InlineData("Plain text [PAYWALL_TRIGGER:00000000-0000-0000-0000-000000000000:Title:invalid:80]")]
[InlineData("Plain text [PAYWALL_TRIGGER:00000000-0000-0000-0000-000000000000:Title]")]
public void TryParsePaywallTrigger_WithInvalidInputs_ReturnsFalse(string rawText)
{
// Act
var result = PaywallParser.TryParsePaywallTrigger(
rawText,
out var teaser,
out var bookId,
out var title,
out var localScore,
out var globalScore);
// Assert
result.Should().BeFalse();
}
}