diff --git a/Docs/WritingSolver/CuratedV2/CleanResultUrls/Report.md b/Docs/WritingSolver/CuratedV2/CleanResultUrls/Report.md new file mode 100644 index 00000000..da578e4a --- /dev/null +++ b/Docs/WritingSolver/CuratedV2/CleanResultUrls/Report.md @@ -0,0 +1,28 @@ +# Permanent result URLs + +Baseline: `f9cd616` (Development runtime `127a85d`). Development only; Production unchanged. + +Previously the answer POST redirected to the transient solver Index with protected answer history in `?state=...`, including completed diagnoses. The permanent slug action separately rendered a generic article. + +A completed genuine diagnosis now saves its accepted choices server-side and redirects directly to the existing primary diagnosis slug. Completed state-bearing GETs also bridge and redirect. Reassurance and insufficient evidence remain transient. No solver graph, coefficients, thresholds, evidence gates or routing data changed. + +`WritingSolverResultContext` uses the existing application memory-cache service with an absolute two-hour lifetime. A cryptographically random 256-bit opaque HttpOnly, SameSite=Lax, path-scoped cookie identifies the browser; HTTPS requests set Secure. Cache keys hash the token, authentication subject/scheme and diagnosis slug. Entries contain only graph version and accepted choice IDs. No manuscript, workspace, scores, evidence prose or answer history enters the cookie or permanent URL. This single-instance implementation intentionally loses temporary enhancements after restart; another instance without the entry renders generic content. A distributed deployment would need a shared cache if cross-instance persistence is desired. + +The slug GET re-evaluates accepted choices against the current graph and checks that the primary diagnosis still matches. Expiry, eviction, absent cookie or graph mismatch produces the ordinary useful generic page. Responses are private/no-store with Vary: Cookie, preventing shared HTML caches from leaking evidence. Anonymous/authenticated identities and different authenticated subjects do not share entries. Visitors sharing only a URL receive no original evidence. + +The same permanent page now uses the authored result component for generic and contextual arrivals: diagnosis, concise explanation, Start here, Look for, approved optional secondary/article, real screenshot placeholder and existing signed-in/out CTA. Only contextual arrivals add actual evidence, supporting patterns, history and Back. Existing generic editorial prose remains in a compact disclosure; related diagnosis and primary feature links remain crawlable. No article catalogue was restored. + +The final POST redirects straight to the slug so browser Back returns to the last question. Explicit Back also carries the protected prefix for that question. Forward and refresh retain context while available. Revising a prefix discards stale answers through the unchanged engine and can redirect to a different slug. + +SEO uses the existing page title, description, canonical, OG and WebPage JSON-LD metadata, with the same clean URL for either presentation. State pages stay noindex. Existing sitemap generation includes all active/indexable diagnoses and never includes state. Owner explicitly chose to preserve Development's `WritingSolver__EnableIndexing=false`; indexability and the 52 sitemap entries are verified in the isolated test host with indexing enabled. Development remains noindex and omits solver sitemap entries, as intended. + +Validation and live deployment evidence: see Deployment.md after verification. + +## Automated validation + +- Solution build passed (two pre-existing nullable warnings). +- Full executable regression harness: **392 PASS**, including the new clean transition/privacy fixture and unchanged solver acceptance, prefix, reachability, neutral and presentation suites. +- Indexing-enabled browser host: all **52** direct permanent slugs return 200 with one diagnosis heading, primary capability, clean canonical and crawlable feature link. Sitemap includes all 52, without state URLs. +- Browser completion, personal evidence, refresh, fresh-session isolation, Back/Forward, explicit Back prefix revision to a different diagnosis, clean metadata and no horizontal overflow passed at **390/1440px**, with **JavaScript on/off**. +- Context tests cover opaque HttpOnly cookie, refresh, Back prefix, private/no-store, fresh visitors, anonymous vs authenticated isolation, different authenticated subjects, cache loss and graph-version mismatch. +- No solver graph files changed. Existing repair regression still proves all 60 cases / 290 prefixes, all 52 primary-capable, and zero confirmed-problem dead ends. diff --git a/PlotLine.Tests/Browser/writing-solver-clean-urls.cjs b/PlotLine.Tests/Browser/writing-solver-clean-urls.cjs new file mode 100644 index 00000000..45465b38 --- /dev/null +++ b/PlotLine.Tests/Browser/writing-solver-clean-urls.cjs @@ -0,0 +1,51 @@ +const {chromium}=require('playwright'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const graph=JSON.parse(fs.readFileSync('PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/writing-solver-curated-v2-stage1-repair.json')); +const base=process.env.SOLVER_BASE_URL||'http://127.0.0.1:5238'; +assert(['127.0.0.1:5238','dev.plotdirector.com'].includes(new URL(base).host)); +const indexed=process.env.PD_SOLVER_TEST_INDEXING==='true'; +(async()=>{const browser=await chromium.launch();try{ + for(const width of [1440,390])for(const javaScriptEnabled of [true,false]){ + const context=await browser.newContext({viewport:{width,height:1000},javaScriptEnabled}); + await context.addCookies([{name:'solver-anonymous',value:'true',url:base}]); + const page=await context.newPage(); + async function choose(choice){await page.locator(`input[name=choices][value="${choice}"]`).check();await page.locator('.solver-form button[type=submit]').click();} + await page.goto(base+'/writing-problems'); + for(const c of ['story-not-working','too-many','lost'])await choose(c); + assert.equal(await page.locator('meta[name=robots]').getAttribute('content'),'noindex, follow'); + await choose('unwanted'); + const slug=graph.solutions.find(s=>s.id==='d01').slug; + assert.equal(page.url(),base+'/writing-problems/'+slug); + assert((await page.locator('.solver-result-evidence > p').count())>1); + const personal=await page.locator('.solver-result-evidence').innerText(); + await page.reload();assert.equal(await page.locator('.solver-result-evidence').innerText(),personal); + const fresh=await browser.newContext();const direct=await fresh.newPage();await direct.goto(page.url()); + assert.equal(await direct.locator('.solver-result-panel').count(),1); + assert.equal(await direct.locator('.solver-result-evidence > p').count(),1); + assert.equal(await direct.locator('nav[aria-label="Areas discussed"]').count(),0); + assert.equal(await direct.locator('.solver-result-cta').count(),1); + await fresh.close(); + await page.goBack();assert.equal(await page.locator('input[name=node]').inputValue(),'intent-threads'); + await page.goForward();assert.equal(page.url(),base+'/writing-problems/'+slug); + // Explicit Back preserves the prior accepted answers independently of browser caching. + await page.getByRole('link',{name:'← Back',exact:true}).click(); + await page.getByRole('link',{name:'← Back',exact:true}).click(); + await page.getByRole('link',{name:'← Back',exact:true}).click(); + await choose('dont-connect');await choose('gap');await choose('unwanted'); + assert.equal(page.url(),base+'/writing-problems/'+graph.solutions.find(s=>s.id==='d02').slug); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false); + const canonical=await page.locator('link[rel=canonical]').getAttribute('href'); + assert.equal(new URL(canonical).pathname,new URL(page.url()).pathname);assert(!canonical.includes('?')); + assert.equal(await page.locator('meta[property="og:url"]').getAttribute('content'),canonical); + assert((await page.locator('script[type="application/ld+json"]').allTextContents()).join('').includes(canonical)); + assert.equal(await page.locator('meta[name=robots]').getAttribute('content'),indexed?'index, follow':'noindex, follow'); + await context.close(); + } + const context=await browser.newContext();const page=await context.newPage(); + for(const solution of graph.solutions){const response=await page.goto(base+'/writing-problems/'+solution.slug);assert.equal(response.status(),200);assert.equal(await page.locator('h1').innerText(),solution.title);assert.equal(await page.locator('.solver-result-cta').count(),1);assert.equal(await page.locator('meta[name=robots]').getAttribute('content'),indexed?'index, follow':'noindex, follow');assert.equal(new URL(await page.locator('link[rel=canonical]').getAttribute('href')).pathname,'/writing-problems/'+solution.slug);assert((await page.locator('meta[name=description]').getAttribute('content')).length>10);assert(await page.locator('a[href^=\"/features/\"]').count()>0);} + const sitemap=await (await context.request.get(base+'/sitemap.xml')).text();assert(!sitemap.includes('state=')); + if(indexed)for(const solution of graph.solutions)assert(sitemap.includes('/writing-problems/'+solution.slug)); + console.log('PASS clean URLs: 52 direct pages; private evidence/refresh/fresh sharing; Back/Forward; revised diagnosis; 390/1440; JS/no-JS; canonical/OG/structured data; robots; sitemap'+(indexed?' all 52 indexable':' Development noindex')); + await context.close(); +}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index cce2dd1e..f97f76e8 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -96,6 +96,7 @@ var tests = new (string Name, Action Test)[] ("Curated V2 preserves 60 literal paths and enforces eight explicit Development review exceptions", WritingSolverCuratedV2Tests.Acceptance), ("Curated V2 exhausts real-engine states and preserves revision/multi-select behaviour", WritingSolverCuratedV2Tests.ReachabilityAndRevision), ("Curated V2 passes normal validation and invalid publication stays guarded", WritingSolverCuratedV2Tests.ExistingValidatorBoundary), + ("Clean solver completion preserves private evidence and permanent indexable URLs", WritingSolverCleanUrlTests.TransitionAndIsolation), ("Writing Solver anonymous state is protected, expires and rejects stale versions", WritingSolverTests.AnonymousState), ("Writing Solver scoring, multi-select, revision, fallback and graph routes", WritingSolverTests.RoutingAndRevision), ("Writing Solver import rejects invalid graphs and editorial identities", WritingSolverTests.Validation), diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 689ca3ba..d5b33b5d 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -77,6 +77,8 @@ internal static class ToolbarBrowserHost builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddMemoryCache(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(new WritingSolverResults(Path.GetFullPath("PlotLine/Content/WritingSolver/Presentation/results-v1.json"))); builder.Services.AddSingleton(); builder.Services.AddScoped(services => new ToolbarTestUser(int.Parse(services.GetRequiredService().HttpContext!.User.FindFirstValue(ClaimTypes.NameIdentifier)!))); @@ -346,7 +348,7 @@ internal sealed class WritingSolverFixtureRepository(IHttpContextAccessor access var path=Environment.GetEnvironmentVariable("PD_WRITING_SOLVER_CANDIDATE"); if(string.IsNullOrEmpty(path)) return null; var graph=WritingSolverRepository.Parse(File.ReadAllText(path)); - foreach(var page in graph.Solutions.Cast().Concat(graph.Features)) page.Index=false; + foreach(var page in graph.Solutions.Cast().Concat(graph.Features)) page.Index=Environment.GetEnvironmentVariable("PD_SOLVER_TEST_INDEXING")=="true"; return System.Text.Json.JsonSerializer.Serialize(graph,WritingSolverRepository.JsonOptions); }); public Task GetAsync() diff --git a/PlotLine.Tests/WritingSolverCleanUrlTests.cs b/PlotLine.Tests/WritingSolverCleanUrlTests.cs new file mode 100644 index 00000000..e5ef5ef4 --- /dev/null +++ b/PlotLine.Tests/WritingSolverCleanUrlTests.cs @@ -0,0 +1,60 @@ +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using PlotLine.Controllers; +using PlotLine.Data; +using PlotLine.Models.WritingSolver; +using PlotLine.Services; +using System.Security.Claims; +using System.Text.Json; +public static class WritingSolverCleanUrlTests +{ + private sealed class Repository(SolverGraph graph):IWritingSolverRepository + { + public Task GetAsync()=>Task.FromResult(graph); + public Task PublishAsync(string json,string editor)=>throw new NotSupportedException(); + } + public static void TransitionAndIsolation() + { + void Check(bool ok,string text) { if(!ok)throw new Exception(text); } + var graph=WritingSolverRepository.Parse(File.ReadAllText("PlotLine/Content/WritingSolver/demo.json")); + foreach(var page in graph.Solutions)page.Index=true; + var answers=new[]{new SolverAnswer("welcome",["story"]),new SolverAnswer("plot",["threads","crossing"]),new SolverAnswer("focus",["weave"])}; + var provider=new EphemeralDataProtectionProvider(); + using var cache=new MemoryCache(new MemoryCacheOptions()); + var contexts=new WritingSolverResultContext(cache); + var config=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary{["WritingSolver:EnableIndexing"]="true"}).Build(); + WritingProblemsController Controller(DefaultHttpContext http)=>new(new Repository(graph),provider,config,contexts){ControllerContext=new(){HttpContext=http}}; + var http=new DefaultHttpContext();var controller=Controller(http); + var state=provider.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector().Protect(JsonSerializer.Serialize(new{Version=graph.Version,Answers=answers.Take(2)}),TimeSpan.FromHours(2)); + var redirect=(RedirectToActionResult)controller.Answer(state,"focus",["weave"]).GetAwaiter().GetResult(); + var slug=WritingSolverEngine.Evaluate(graph,answers).Solutions[0].Slug; + Check(redirect.ActionName=="Solution" && (string?)redirect.RouteValues!["slug"]==slug && !redirect.RouteValues.ContainsKey("state"),"Completion must redirect to clean slug."); + var cookie=http.Response.Headers.SetCookie.ToString().Split(';')[0]; + Check(cookie.StartsWith("pd-solver-result=") && http.Response.Headers.SetCookie.ToString().Contains("httponly",StringComparison.OrdinalIgnoreCase),"Opaque HttpOnly cookie missing."); + DefaultHttpContext Visitor(){var h=new DefaultHttpContext();h.Request.Headers.Cookie=cookie;return h;} + foreach(var h in new[]{Visitor(),Visitor()}) + { + var c=Controller(h);var page=(SolverPageView)((ViewResult)c.Solution(slug).GetAwaiter().GetResult()).Model!; + Check(page.Journey?.Outcome.Answers.Count==3 && c.ViewData["BackState"] is string,"Refresh must preserve evidence and Back history."); + Check(!h.Response.Headers.ContainsKey("X-Robots-Tag") && (string?)c.ViewData["Robots"]=="index, follow","Permanent page should be indexable when enabled."); + Check(h.Response.Headers.CacheControl.ToString()=="private, no-store","Personal pages must never enter shared caches."); + } + var fresh=(SolverPageView)((ViewResult)Controller(new()).Solution(slug).GetAwaiter().GetResult()).Model!; + Check(fresh.Journey is null,"Shared fresh visit leaked evidence."); + var signed=Visitor();signed.User=new(new ClaimsIdentity(new[]{new Claim(ClaimTypes.NameIdentifier,"other-user")},"test")); + Check(contexts.Read(signed,graph,slug) is null,"Different identity inherited anonymous evidence."); + contexts.Save(signed,graph,WritingSolverEngine.Evaluate(graph,answers),slug); + Check(contexts.Read(signed,graph,slug) is not null,"Signed-in owner lost context."); + signed.User=new(new ClaimsIdentity(new[]{new Claim(ClaimTypes.NameIdentifier,"another-user")},"test")); + Check(contexts.Read(signed,graph,slug) is null,"Different signed-in subject inherited evidence."); + cache.Compact(1);Check(contexts.Read(Visitor(),graph,slug) is null,"Expired/evicted context must fall back safely."); + http.Request.Headers.Cookie=cookie; + contexts.Save(http,graph,WritingSolverEngine.Evaluate(graph,answers),slug); + graph.Version+="changed";Check(contexts.Read(Visitor(),graph,slug) is null,"Old graph context must expire safely."); + var transient=Controller(new());transient.Index(state).GetAwaiter().GetResult(); + Check(transient.Response.Headers["X-Robots-Tag"].ToString().Contains("noindex"),"Journey must stay noindex."); + } +} diff --git a/PlotLine.Tests/WritingSolverTests.cs b/PlotLine.Tests/WritingSolverTests.cs index e7fee709..efd144f4 100644 --- a/PlotLine.Tests/WritingSolverTests.cs +++ b/PlotLine.Tests/WritingSolverTests.cs @@ -49,7 +49,7 @@ internal static class WritingSolverTests { var provider = new EphemeralDataProtectionProvider(); var protector = provider.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector(); - var controller = new WritingProblemsController(new MemoryGraph(Graph()),provider,new ConfigurationBuilder().Build()) + var controller = new WritingProblemsController(new MemoryGraph(Graph()),provider,new ConfigurationBuilder().Build(),new WritingSolverResultContext(new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()))) { ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } }; diff --git a/PlotLine/Controllers/WritingProblemsController.cs b/PlotLine/Controllers/WritingProblemsController.cs index 1fd2294d..a68d828d 100644 --- a/PlotLine/Controllers/WritingProblemsController.cs +++ b/PlotLine/Controllers/WritingProblemsController.cs @@ -9,7 +9,7 @@ using PlotLine.Services; namespace PlotLine.Controllers; [AllowAnonymous] -public sealed class WritingProblemsController(IWritingSolverRepository repository, IDataProtectionProvider protection, IConfiguration configuration) : Controller +public sealed class WritingProblemsController(IWritingSolverRepository repository, IDataProtectionProvider protection, IConfiguration configuration, WritingSolverResultContext resultContext) : Controller { private readonly ITimeLimitedDataProtector protector = protection.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector(); private sealed record History(string Version, List Answers); @@ -34,6 +34,8 @@ public sealed class WritingProblemsController(IWritingSolverRepository repositor catch (Exception ex) when (ex is CryptographicException or JsonException or InvalidDataException) { error = "Your previous conversation has expired or changed. Let’s start afresh."; } var outcome = WritingSolverEngine.Evaluate(graph,history); + if (state is not null) Response.Headers["X-Robots-Tag"] = "noindex, follow"; + if (Complete(graph, outcome) is {} completed) return completed; SetSeo("The Writing Problem Solver", "Tell us what’s making your novel complicated and find a practical way to untangle it.", "/writing-problems", state is null); ViewData["BackState"] = outcome.Answers.Count > 0 ? Encode(graph,outcome.Answers.Take(outcome.Answers.Count-1)) : null; return View(new SolverJourney(graph,outcome,Encode(graph,outcome.Answers),error)); @@ -51,11 +53,18 @@ public sealed class WritingProblemsController(IWritingSolverRepository repositor history.Add(new(node, choices)); var after = WritingSolverEngine.Evaluate(graph,history); if (after.Answers.Count != history.Count) return RedirectToAction(nameof(Index), new { state, choose = true }); + if (Complete(graph, after) is {} completed) return completed; return RedirectToAction(nameof(Index), new { state = Encode(graph, after.Answers) }); } catch (Exception ex) when (ex is CryptographicException or JsonException or InvalidDataException) { return RedirectToAction(nameof(Index)); } } + private IActionResult? Complete(SolverGraph graph, SolverOutcome outcome) + { + if (outcome.Next is not null || outcome.Reassurance is not null || outcome.Solutions.FirstOrDefault() is not {} solution) return null; + resultContext.Save(HttpContext, graph, outcome, solution.Slug); + return RedirectToAction(nameof(Solution), new { slug = solution.Slug }); + } [HttpGet("/writing-problems/{slug}")] public async Task Solution(string slug) => await Page(slug,false); [HttpGet("/features/{slug}")] @@ -66,7 +75,19 @@ public sealed class WritingProblemsController(IWritingSolverRepository repositor SolverPage? page = feature ? graph.Features.FirstOrDefault(p => p.Active && p.Slug == slug) : graph.Solutions.FirstOrDefault(p => p.Active && p.Slug == slug); if (page is null) return NotFound(); SetSeo(page.PageTitle,page.Description,$"/{(feature ? "features" : "writing-problems")}/{page.Slug}",page.Index,page.SocialImage); - return View("Page",new SolverPageView(graph,page,feature)); + SolverJourney? journey = null; + if (!feature) + { + Response.Headers.CacheControl = "private, no-store"; + Response.Headers.Vary = "Cookie"; + Response.Headers["Referrer-Policy"] = "no-referrer"; + if (resultContext.Read(HttpContext, graph, slug) is {} outcome) + { + journey = new(graph, outcome, Encode(graph, outcome.Answers)); + ViewData["BackState"] = Encode(graph, outcome.Answers.Take(outcome.Answers.Count - 1)); + } + } + return View("Page",new SolverPageView(graph,page,feature,journey)); } private void SetSeo(string title,string description,string path,bool index,string? image=null) { diff --git a/PlotLine/Models/WritingSolver/SolverGraph.cs b/PlotLine/Models/WritingSolver/SolverGraph.cs index 76546833..5253d90f 100644 --- a/PlotLine/Models/WritingSolver/SolverGraph.cs +++ b/PlotLine/Models/WritingSolver/SolverGraph.cs @@ -101,4 +101,4 @@ public sealed class SolverFeatureLink public sealed record SolverAnswer(string Node, string[] Choices); public sealed record SolverOutcome(SolverNode? Next, IReadOnlyList Solutions, IReadOnlyDictionary Scores, IReadOnlyList Answers, SolverReassurance? Reassurance = null); public sealed record SolverJourney(SolverGraph Graph, SolverOutcome Outcome, string History, string? Error = null); -public sealed record SolverPageView(SolverGraph Graph, SolverPage Page, bool IsFeature); +public sealed record SolverPageView(SolverGraph Graph, SolverPage Page, bool IsFeature, SolverJourney? Journey = null); diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 12d9de0a..c16e0dc1 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -115,6 +115,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(services => new WritingSolverResults(Path.Combine(services.GetRequiredService().ContentRootPath,"Content/WritingSolver/Presentation/results-v1.json"))); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/WritingSolverResultContext.cs b/PlotLine/Services/WritingSolverResultContext.cs new file mode 100644 index 00000000..aa1e7f5e --- /dev/null +++ b/PlotLine/Services/WritingSolverResultContext.cs @@ -0,0 +1,45 @@ +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using Microsoft.Extensions.Caching.Memory; +using PlotLine.Models.WritingSolver; +namespace PlotLine.Services; + +// Only an opaque browser identifier leaves the server. Context expires absolutely, +// is bound to the signed-in subject, and is disposable on restart or graph change. +public sealed class WritingSolverResultContext(IMemoryCache cache) +{ + private const string Cookie = "pd-solver-result"; + private static readonly TimeSpan Lifetime = TimeSpan.FromHours(2); + private sealed record Entry(string Version, SolverAnswer[] Answers); + private static string? Token(HttpContext context) => context.Request.Cookies[Cookie] is { Length: 64 } token + && token.All(Uri.IsHexDigit) ? token : null; + private static string Key(HttpContext context, string token, string slug) + { + var identity = context.User.Identity?.IsAuthenticated == true + ? "user:" + context.User.FindFirstValue(ClaimTypes.NameIdentifier) + ":" + context.User.Identity.AuthenticationType + : "anonymous"; + return "solver-result:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token + "|" + identity + "|" + slug))); + } + public void Save(HttpContext context, SolverGraph graph, SolverOutcome outcome, string slug) + { + if (context.User.Identity?.IsAuthenticated == true && string.IsNullOrEmpty(context.User.FindFirstValue(ClaimTypes.NameIdentifier))) return; + var token = Token(context) ?? Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + context.Response.Cookies.Append(Cookie, token, new CookieOptions + { + HttpOnly = true, Secure = context.Request.IsHttps, SameSite = SameSiteMode.Lax, + Path = "/writing-problems", MaxAge = Lifetime, IsEssential = true + }); + cache.Set(Key(context, token, slug), new Entry(graph.Version, + outcome.Answers.Select(a => new SolverAnswer(a.Node, a.Choices.ToArray())).ToArray()), Lifetime); + } + public SolverOutcome? Read(HttpContext context, SolverGraph graph, string slug) + { + if (context.User.Identity?.IsAuthenticated == true && string.IsNullOrEmpty(context.User.FindFirstValue(ClaimTypes.NameIdentifier))) return null; + var token = Token(context); + if (token is null || !cache.TryGetValue(Key(context, token, slug), out var entry) + || entry is null || entry.Version != graph.Version) return null; + var outcome = WritingSolverEngine.Evaluate(graph, entry.Answers); + return outcome.Next is null && outcome.Reassurance is null && outcome.Solutions.FirstOrDefault()?.Slug == slug ? outcome : null; + } +} diff --git a/PlotLine/Views/WritingProblems/Page.cshtml b/PlotLine/Views/WritingProblems/Page.cshtml index dec6bc24..063a6bd2 100644 --- a/PlotLine/Views/WritingProblems/Page.cshtml +++ b/PlotLine/Views/WritingProblems/Page.cshtml @@ -1,5 +1,6 @@ @using PlotLine.Models.WritingSolver @model SolverPageView +@inject PlotLine.Services.WritingSolverResults Results @{ Layout="_PublicLayout"; }
@@ -18,8 +19,31 @@ } else { - + var presentation = Model.Journey is {} journey ? Results.Present(journey.Outcome) : Results.Present(new SolverOutcome(null, new[] { (SolverSolution)Model.Page }, new Dictionary(), Array.Empty())); + @if(presentation is not null) { } + else { } + @if(Model.Journey is {} completed) + { +
+ @if(ViewData["BackState"] is string back) { ← Back } + Start again +
+ + } var solution=(SolverSolution)Model.Page; + @if(presentation is not null) + { +
More about this writing problem +

@solution.Summary

+ @foreach(var paragraph in solution.Content.Split("\n\n")) {

@paragraph

} + @foreach(var link in solution.Features.Where(f=>f.Primary)) + { var feature=Model.Graph.Features.Single(f=>f.Id==link.Feature);

Explore @feature.Title →

} +
+ } @if(solution.Related.Count>0) {

You might also find this useful

} @foreach(var id in solution.Related) {