Verify compiled PWA review forms and preserve book navigation scope

This commit is contained in:
Nick Beckley 2026-11-05 21:36:09 +00:00
parent 18688fed3a
commit fb747869a5
4 changed files with 19 additions and 5 deletions

View File

@ -1,13 +1,14 @@
const {chromium}=require('playwright');const fs=require('node:fs');const path=require('node:path');const assert=require('node:assert/strict');
(async()=>{const browser=await chromium.launch();try{
const page=await browser.newPage();await page.goto('about:blank');await page.setContent('<main id="native-workspace" data-book="3" data-project="1" data-instance="instance" data-session="session" data-mode="context"><p id="native-presence-status"></p><select id="native-session"></select><input type="checkbox" id="native-follow"><iframe id="native-story-workspace" hidden></iframe></main>');
await page.evaluate(()=>{window.polls=[];window.setInterval=f=>{polls.push(f);return 1;};window.live=[{instanceId:'instance',sessionId:'session',bookId:3,chapterId:10,sceneId:20,documentTitle:'Synthetic manuscript',wordAvailable:true,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];window.fetch=async()=>({ok:true,json:async()=>live});const OriginalURL=URL;window.URL=class extends OriginalURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}};});
await page.evaluate(()=>{window.polls=[];window.setInterval=f=>{polls.push(f);return 1;};window.live=[{instanceId:'instance',sessionId:'session',bookId:3,chapterId:10,sceneId:20,documentTitle:'Synthetic manuscript',wordAvailable:true,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];window.requestCount=0;window.fetch=async()=>(requestCount++,{ok:true,json:async()=>live});window.hubHandlers={};window.signalR={HubConnectionBuilder:class{withUrl(){return this;}withAutomaticReconnect(){return this;}build(){return{on:(name,callback)=>hubHandlers[name]=callback,onreconnected:()=>{},start:async()=>{},stop:async()=>{}};}}};const OriginalURL=URL;window.URL=class extends OriginalURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}};});
await page.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-companion-workspace.js'),'utf8')});
await assert.doesNotReject(()=>page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('connected')));
await page.check('#native-follow');await page.waitForFunction(()=>document.querySelector('iframe').src.includes('sceneId=20'));assert.ok((await page.locator('iframe').getAttribute('src')).includes('pinned=true'));
await page.evaluate(()=>{document.querySelector('#native-follow').checked=false;live[0].sceneId=21;polls[0]();});await page.waitForTimeout(30);assert.ok((await page.locator('iframe').getAttribute('src')).includes('sceneId=20'),'manual mode does not snap back to Word');
await page.evaluate(()=>{live=[];polls[0]();});await page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('disconnected'));assert.equal(await page.isChecked('#native-follow'),false);
await page.evaluate(()=>{live=[{wordAvailable:false,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];polls[0]();});await page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('Word unavailable'));
await page.evaluate(()=>{window.beforeEvents=requestCount;for(let i=0;i<20;i++)hubHandlers.NativePresenceChanged();});await page.waitForTimeout(350);assert.equal(await page.evaluate(()=>requestCount-beforeEvents),1,'SignalR burst coalesces to one authorised refresh');
console.log('PASS native PWA exact-session following, pinned scope, manual pause, disconnection and Word-unavailable states');
const badge=await browser.newPage();await badge.goto('about:blank');await badge.setContent('<div id="native-companion-status" hidden><a id="native-companion-status-link"></a><span id="native-companion-status-text"></span></div>');await badge.evaluate(()=>{window.tick=null;window.setInterval=f=>(tick=f,1);window.live=[];window.fetch=async()=>({ok:true,json:async()=>live});});
await badge.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-companion-status.js'),'utf8')});assert.equal(await badge.locator('#native-companion-status').isHidden(),true);

View File

@ -57,6 +57,14 @@ internal static class NativeCompanionHttpTests
await using var app=builder.Build();app.UseRouting();app.UseRateLimiter();app.UseAuthentication();app.UseAuthorization();
app.MapGet("/fixture-login",async (Microsoft.AspNetCore.Http.HttpContext context)=>{await context.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.NameIdentifier,"7"),new("PlotLine.SecurityStamp",user.SecurityStamp.ToString())],CookieAuthenticationDefaults.AuthenticationScheme)));return "Fixture login";});
app.MapGet("/fixture-antiforgery",(IAntiforgery xsrf,Microsoft.AspNetCore.Http.HttpContext context)=>xsrf.GetAndStoreTokens(context).RequestToken);
app.MapGet("/fixture-render-review/{id:guid}",async (Guid id,Microsoft.AspNetCore.Http.HttpContext context)=>{
var row=await context.RequestServices.GetRequiredService<INativeReviewRepository>().Get(7,id);if(row==null)return Microsoft.AspNetCore.Http.Results.NotFound();
var action=new Microsoft.AspNetCore.Mvc.ActionContext(context,new Microsoft.AspNetCore.Routing.RouteData(),new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor());
var views=context.RequestServices.GetRequiredService<Microsoft.AspNetCore.Mvc.ViewEngines.ICompositeViewEngine>();var view=views.GetView(null,"/Views/NativeWorkspace/Review.cshtml",false);if(!view.Success)throw new Exception("Native review Razor view unavailable");
using var writer=new StringWriter();var data=new Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(),new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()){Model=new NativeReviewModel(row,JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!,string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize<NativeSceneDecision[]>(row.DecisionsJson)!,[],1)};
var temp=new Microsoft.AspNetCore.Mvc.ViewFeatures.TempDataDictionary(context,context.RequestServices.GetRequiredService<Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataProvider>());
await view.View.RenderAsync(new Microsoft.AspNetCore.Mvc.Rendering.ViewContext(action,view.View,data,temp,writer,new Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelperOptions()));return Microsoft.AspNetCore.Http.Results.Content(writer.ToString(),"text/html");
}).RequireAuthorization();
app.MapHub<PlotLine.Hubs.NativeCompanionPresenceHub>("/hubs/native-companion");app.MapControllers();await app.StartAsync();
try
{
@ -86,6 +94,10 @@ internal static class NativeCompanionHttpTests
var result=await response.Content.ReadFromJsonAsync<AiChapterResult>();Check(result?.State=="complete"&&result.Scenes.Single().Start==20&&provider.Prompts.Count==1,"Actual HTTP response maps scene to Word position");
Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).IsSuccessStatusCode&&provider.Prompts.Count==1,"HTTP retry reuses successful provider result");
Check(result!.ReviewPath.StartsWith("/native-companion/reviews/")&&!string.IsNullOrWhiteSpace(result.Scenes.Single().Summary),"AI summary is preserved and saved PWA review handoff returned");
var reviewId=Guid.Parse(result.ReviewPath.Split('/').Last());var reviewHtml=await browser.GetStringAsync("/fixture-render-review/"+reviewId);Check(reviewHtml.Contains("Save review decisions")&&reviewHtml.Contains("Summary")&&reviewHtml.Contains("scene"),"Actual compiled Razor review renders AI title/summary form");
var decisionFields=new Dictionary<string,string>{{"version","1"},{"scenes[0].Index","0"},{"scenes[0].State","approved"},{"scenes[0].Title","<script>not-executable</script>"},{"scenes[0].Summary","Edited summary"},{"__RequestVerificationToken",antiforgery}};
Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(decisionFields))).StatusCode==HttpStatusCode.Redirect,"Actual antiforgery-protected form binds and saves review decisions");
Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(decisionFields))).StatusCode==HttpStatusCode.Conflict,"Actual stale review form receives conflict without overwriting");reviewHtml=await browser.GetStringAsync("/fixture-render-review/"+reviewId);Check(!reviewHtml.Contains("<script>not-executable</script>")&&reviewHtml.Contains("Edited summary"),"Saved title is encoded while edited summary remains reviewable");
request.RequestId=Guid.NewGuid();var reused=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(reused.IsSuccessStatusCode&&provider.Prompts.Count==1,"Unchanged chapter content reuses durable suggestion across new request identifiers");
var negotiation=await browser.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null);Check(negotiation.IsSuccessStatusCode,"Native presence hub requires normal browser authentication and negotiates after sign-in");
var connectionToken=(await negotiation.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("connectionToken").GetString();

View File

@ -30,7 +30,7 @@ internal static class NativeTrayIntegrationTests
var repo=new MemoryNativeReviews();var result=new AiChapterResult{State="complete",ChapterTitle="Opening",Scenes=[new(){Kind="Scene",Origin="AI",Title="Arrival",Summary="A saved AI summary.",Start=0,End=100}]};
var row=await repo.Save(new(){ReviewID=Guid.NewGuid(),UserID=7,BookID=3,ManuscriptID=manuscript,ContentHash="hash",ResultJson=JsonSerializer.Serialize(result)});
var books=NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>Task.FromResult<Book?>(new(){BookID=3,ProjectID=1}));var workspace=new NativeWorkspaceController(access,books,repo,store){ControllerContext=new(){HttpContext=http},TempData=new TempDataDictionary(http,new TempData())};
Check(await workspace.Review(row.ReviewID) is ViewResult,"Saved AI title and summary can be reviewed in PWA without Word");
Check(await workspace.Review(row.ReviewID) is ViewResult{Model:NativeReviewModel{BookID:3,ProjectID:1}},"Saved AI title and summary can be reviewed in PWA without Word");
Check(await workspace.Decide(row.ReviewID,1,[new(){Index=0,State="approved",Title="Edited title",Summary="Edited summary"}]) is RedirectToActionResult,"Explicit approval/edit saves suggestions only");
Check(await workspace.Decide(row.ReviewID,1,[new(){Index=0,State="rejected",Title="Late edit",Summary=""}]) is ConflictObjectResult,"Stale review window cannot overwrite decisions");
Check(await workspace.Decide(row.ReviewID,2,[new(){Index=0,State="invented",Title="No",Summary=""}]) is BadRequestObjectResult,"Invalid decisions are refused");

View File

@ -33,7 +33,8 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
public async Task<IActionResult> Review(Guid id)
{
var row=await reviews.Get(Author,id);if(row==null)return NotFound();if(await access.GetBookStructureAsync(row.BookID,Author)==null)return Forbid();
return View(new NativeReviewModel(row,JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!,string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize<NativeSceneDecision[]>(row.DecisionsJson)!,presence.Read(Author,row.BookID).Where(l=>l.Position.WordAvailable&&l.Position.ManuscriptId==row.ManuscriptID&&l.Position.Revision==JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!.DocumentRevision).ToArray()));
var book=await books.GetAsync(row.BookID);if(book==null)return NotFound();
return View(new NativeReviewModel(row,JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!,string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize<NativeSceneDecision[]>(row.DecisionsJson)!,presence.Read(Author,row.BookID).Where(l=>l.Position.WordAvailable&&l.Position.ManuscriptId==row.ManuscriptID&&l.Position.Revision==JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!.DocumentRevision).ToArray(),book.ProjectID));
}
[HttpPost("reviews/{id:guid}/navigate"),ValidateAntiForgeryToken]
public async Task<IActionResult> Navigate(Guid id,int index,Guid instanceId,Guid sessionId)
@ -53,6 +54,6 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
TempData["NativeReviewSaved"]="Review decisions saved. No manuscript or canonical story records were changed.";return RedirectToAction(nameof(Review),new{id});
}
}
public sealed record NativeWorkspaceModel(int Book,int Project,string Title,Guid? Instance,Guid? Session,string Mode,IReadOnlyList<NativeReview> Reviews);
public sealed record NativeReviewModel(NativeReview Row,AiChapterResult Result,NativeSceneDecision[] Decisions,NativeLease[] Sessions);
public sealed record NativeWorkspaceModel(int Book,int Project,string Title,Guid? Instance,Guid? Session,string Mode,IReadOnlyList<NativeReview> Reviews){public int BookID=>Book;public int ProjectID=>Project;}
public sealed record NativeReviewModel(NativeReview Row,AiChapterResult Result,NativeSceneDecision[] Decisions,NativeLease[] Sessions,int ProjectID=0){public int BookID=>Row.BookID;}
public sealed class NativeSceneDecision {public int Index {get;set;}public string State {get;set;}="pending";public string Title {get;set;}="";public string Summary {get;set;}="";}