From 0aeb9d1005b892858c7f5ed4f1689351f2b3c125 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Fri, 20 Nov 2026 21:30:24 +0000 Subject: [PATCH] Fix Review fallback targets and fence historical Word navigation --- .../Browser/reader-word-freshness.cjs | 2 +- .../Browser/writer-phase21-word.cjs | 2 +- .../Browser/writer-phase3b1-review.cjs | 43 +++++++++ PlotLine.Tests/NativeReviewNavigationTests.cs | 87 +++++++++++++++++++ PlotLine.Tests/Program.cs | 3 + PlotLine.Tests/ToolbarBrowserHost.cs | 4 +- .../Controllers/NativeWorkspaceController.cs | 9 +- PlotLine/Program.cs | 1 + .../NativeCompanion/NativeReviewNavigation.cs | 45 ++++++++++ PlotLine/Views/NativeWorkspace/Review.cshtml | 3 +- PlotLine/wwwroot/js/narrative-focus-review.js | 2 +- PlotLine/wwwroot/js/writer-review.js | 10 ++- 12 files changed, 202 insertions(+), 9 deletions(-) create mode 100644 PlotLine.Tests/Browser/writer-phase3b1-review.cjs create mode 100644 PlotLine.Tests/NativeReviewNavigationTests.cs create mode 100644 PlotLine/Services/NativeCompanion/NativeReviewNavigation.cs diff --git a/PlotLine.Tests/Browser/reader-word-freshness.cjs b/PlotLine.Tests/Browser/reader-word-freshness.cjs index ab6d7494..22545d6d 100644 --- a/PlotLine.Tests/Browser/reader-word-freshness.cjs +++ b/PlotLine.Tests/Browser/reader-word-freshness.cjs @@ -1,2 +1,2 @@ const{chromium}=require('playwright'),assert=require('node:assert/strict'); -(async()=>{const b=await chromium.launch();try{for(const pwa of[false,true]){const c=await b.newContext();if(pwa)await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const p=await c.newPage();let stamp='2026-11-16T12:00:00Z',checks=0;await p.route('**/manuscript/reader/changes?*',r=>{checks++;const u=new URL(r.request().url());return r.fulfill({json:{revision:u.searchParams.get('knownRevision'),version:u.searchParams.get('knownVersion'),changed:false,lastSuccessfulSyncUtc:stamp,snapshotCapturedUtc:'2026-11-15T12:00:00Z'}})});await p.goto('http://127.0.0.1:5238/manuscript/reader?bookId=12&chapterId=21&focus=true');await p.locator('#reader-timestamps time[datetime="'+stamp+'"]').waitFor();const row=await p.locator('[data-paragraph-id]').first().elementHandle();await row.evaluate(n=>{const r=document.createRange();r.selectNodeContents(n);getSelection().removeAllRanges();getSelection().addRange(r)});const selected=await p.evaluate(()=>getSelection().toString());const before=checks;stamp='2026-11-16T13:00:00Z';await p.evaluate(()=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{bookId:12,snapshotRevision:99999}]})));await p.locator('#reader-timestamps time[datetime="'+stamp+'"]').waitFor();assert(checks>before);assert(await row.evaluate(n=>n===document.querySelector('[data-paragraph-id]')));assert.equal(await p.evaluate(()=>getSelection().toString()),selected);assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');const next=p.locator('a[rel=next]');if(await next.count())assert(new URL(await next.getAttribute('href'),'http://fixture').searchParams.get('focus')==='true');await c.close();}console.log('PASS Reader accepted-metadata notification updates timestamps without replacing prose, selected text or Focused Reading; Next preserves focus. Browser/simulated PWA.');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1}); +(async()=>{const b=await chromium.launch();try{for(const pwa of[false,true]){const c=await b.newContext();if(pwa)await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const p=await c.newPage();let stamp='2026-11-16T12:00:00Z',checks=0;await p.route('**/manuscript/reader/changes?*',r=>{checks++;const u=new URL(r.request().url());return r.fulfill({json:{revision:u.searchParams.get('knownRevision'),version:u.searchParams.get('knownVersion'),changed:false,lastSuccessfulSyncUtc:stamp,snapshotCapturedUtc:'2026-11-15T12:00:00Z'}})});await p.goto('http://127.0.0.1:5238/manuscript/reader?bookId=12&chapterId=21&focus=true');await p.locator('#reader-timestamps time[datetime="'+stamp+'"]').waitFor({state:'attached'});const row=await p.locator('[data-paragraph-id]').first().elementHandle();await row.evaluate(n=>{const r=document.createRange();r.selectNodeContents(n);getSelection().removeAllRanges();getSelection().addRange(r)});const selected=await p.evaluate(()=>getSelection().toString());const before=checks;stamp='2026-11-16T13:00:00Z';await p.evaluate(()=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{bookId:12,snapshotRevision:99999}]})));await p.locator('#reader-timestamps time[datetime="'+stamp+'"]').waitFor({state:'attached'});assert(checks>before);assert(await row.evaluate(n=>n===document.querySelector('[data-paragraph-id]')));assert.equal(await p.evaluate(()=>getSelection().toString()),selected);assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');const next=p.locator('a[rel=next]');if(await next.count())assert(new URL(await next.getAttribute('href'),'http://fixture').searchParams.get('focus')==='true');await c.close();}console.log('PASS Reader accepted-metadata notification updates timestamps without replacing prose, selected text or Focused Reading; Next preserves focus. Browser/simulated PWA.');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/writer-phase21-word.cjs b/PlotLine.Tests/Browser/writer-phase21-word.cjs index bf50dda0..c097f25a 100644 --- a/PlotLine.Tests/Browser/writer-phase21-word.cjs +++ b/PlotLine.Tests/Browser/writer-phase21-word.cjs @@ -1,2 +1,2 @@ const{chromium}=require('playwright'),assert=require('node:assert/strict'); -(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true]){const c=await browser.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()})));if(pwa)await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const lease={instanceId:'11111111-1111-1111-1111-111111111111',sessionId:'22222222-2222-2222-2222-222222222222',manuscriptId:'33333333-3333-3333-3333-333333333333',bookId:12,wordAvailable:true,wordSaved:true,canAcknowledgeNavigation:true,canChapterSync:true,revision:2,documentTitle:'Synthetic Word source',expires:new Date(Date.now()+3600000).toISOString()};const packet={leases:[lease],canonical:{manuscriptID:lease.manuscriptId},verifiedPositions:[]};const posts=[];await c.route('**/native-companion/status*',r=>r.fulfill({json:packet}));await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null}}));await c.route('**/WriterWord/Availability?*',r=>r.fulfill({json:{chapter:true,scene:true,paragraph:true}}));await c.route('**/WriterWord/Navigate',r=>{posts.push(Object.fromEntries(new URLSearchParams(r.request().postData())));return r.fulfill({status:202,json:{}})});await c.route('**/WriterWord/Navigation?*',r=>r.fulfill({json:{state:'completed'}}));const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto('http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=12&objective=true');if(await p.locator('[data-ribbon-collapse]').getAttribute('aria-expanded')==='false')await p.locator('[data-ribbon-collapse]').click();await p.waitForFunction(()=>!document.querySelector('[data-ribbon-word=chapter]').disabled);const times=[];for(let i=0;i<3;i++){const start=Date.now();await p.locator('[data-ribbon-word=chapter]').click();await p.locator('[data-word-command]').filter({hasText:'Word confirmed navigation.'}).waitFor();times.push(Date.now()-start);}assert.equal(new Set(posts.map(x=>x.navigationId)).size,3);assert(posts.every(x=>x.chapterId==='21'));await p.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:focus-saved',{detail:{chapterID:22,sceneID:null}})));await p.locator('[data-ribbon-word=chapter]').click();await p.locator('[data-word-command]').filter({hasText:'Word confirmed navigation.'}).waitFor();assert.equal(posts.at(-1).chapterId,'22');assert(await p.locator('[data-ribbon-word=scene]').isDisabled());await p.evaluate(v=>window.dispatchEvent(new CustomEvent('writer-word-state',{detail:{...v,leases:[{...v.leases[0],bookId:13}]}})),packet);assert(await p.locator('[data-ribbon-word=chapter]').isDisabled());assert.deepEqual(errors,[]);console.log('PASS repeated unique navigation, immediate new focus targets, cross-book refusal, '+(pwa?'simulated PWA':'browser')+'; browser simulated transport confirmation ms '+times.join(','));await c.close();}}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1}); +(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true]){const c=await browser.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()})));if(pwa)await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const lease={instanceId:'11111111-1111-1111-1111-111111111111',sessionId:'22222222-2222-2222-2222-222222222222',manuscriptId:'33333333-3333-3333-3333-333333333333',bookId:12,wordAvailable:true,wordSaved:true,canAcknowledgeNavigation:true,canChapterSync:true,revision:2,documentTitle:'Synthetic Word source',expires:new Date(Date.now()+3600000).toISOString()};const packet={leases:[lease],canonical:{manuscriptID:lease.manuscriptId},verifiedPositions:[]};const posts=[];await c.route('**/native-companion/status*',r=>r.fulfill({json:packet}));await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null}}));await c.route('**/WriterWord/Availability?*',r=>r.fulfill({json:{chapter:true,scene:true,paragraph:true}}));await c.route('**/WriterWord/Navigate',r=>{posts.push(Object.fromEntries(new URLSearchParams(r.request().postData())));return r.fulfill({status:202,json:{}})});await c.route('**/WriterWord/Navigation?*',r=>r.fulfill({json:{state:'completed'}}));const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto('http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=12&objective=true');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await p.evaluate(()=>window.PlotDirectorNarrativeFocus.set({bookID:12,chapterID:21,sceneID:31}));if(await p.locator('[data-ribbon-collapse]').getAttribute('aria-expanded')==='false')await p.locator('[data-ribbon-collapse]').click();await p.waitForFunction(()=>!document.querySelector('[data-ribbon-word=chapter]').disabled);const times=[];for(let i=0;i<3;i++){const start=Date.now();await p.locator('[data-ribbon-word=chapter]').click();await p.locator('[data-word-command]').filter({hasText:'Word confirmed navigation.'}).waitFor();times.push(Date.now()-start);}assert.equal(new Set(posts.map(x=>x.navigationId)).size,3);assert(posts.every(x=>x.chapterId==='21'));const savedObjective=await p.locator('[data-writer-focus]').getAttribute('data-saved-chapter');await p.evaluate(()=>window.PlotDirectorNarrativeFocus.set({bookID:12,chapterID:22,sceneID:null}));assert.equal(await p.locator('[data-writer-focus]').getAttribute('data-saved-chapter'),savedObjective,'Global Focus never retargets the saved objective');await p.locator('[data-ribbon-word=chapter]').click();await p.locator('[data-word-command]').filter({hasText:'Word confirmed navigation.'}).waitFor();assert.equal(posts.at(-1).chapterId,'22');assert(await p.locator('[data-ribbon-word=scene]').isDisabled());await p.evaluate(v=>window.dispatchEvent(new CustomEvent('writer-word-state',{detail:{...v,leases:[{...v.leases[0],bookId:13}]}})),packet);assert(await p.locator('[data-ribbon-word=chapter]').isDisabled());assert.deepEqual(errors,[]);console.log('PASS repeated unique navigation, immediate new focus targets, cross-book refusal, '+(pwa?'simulated PWA':'browser')+'; browser simulated transport confirmation ms '+times.join(','));await c.close();}}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/writer-phase3b1-review.cjs b/PlotLine.Tests/Browser/writer-phase3b1-review.cjs new file mode 100644 index 00000000..9e1b55c0 --- /dev/null +++ b/PlotLine.Tests/Browser/writer-phase3b1-review.cjs @@ -0,0 +1,43 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'); +const base=process.env.PD_BROWSER_FIXTURE_URL||'http://127.0.0.1:5238'; +(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true]){ +const c=await browser.newContext({viewport:{width:1666,height:1050}});let writes=0,commands=0; +await c.addInitScript(pwa=>{localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()}));if(pwa)Object.defineProperty(navigator,'standalone',{value:true});window.positions=[];document.addEventListener('reader:focus-positioned',e=>window.positions.push(e.detail));},pwa); +await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null,defaultPauseOnEdit:true}})); +await c.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}})); +await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected'}})); +await c.route('**/hubs/**',r=>r.abort()); +await c.route('**/WriterReview/Save',r=>{writes++;return r.abort();}); +await c.route('**/WriterWord/Navigate',r=>{commands++;return r.abort();}); +const cookie=async value=>c.addCookies([{name:'fixture-focus-reader',value,url:base}]);await cookie('mapped'); +const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message)); +await p.goto(base+'/Writer/Review?projectId=7&bookId=12'); +const set=async(chapter,scene)=>{await p.evaluate(()=>window.positions=[]);await p.evaluate(t=>window.PlotDirectorNarrativeFocus.set(t),{bookID:12,chapterID:chapter,sceneID:scene});await p.waitForFunction(t=>window.positions.some(p=>p.chapterID===t.chapter&&p.sceneID===t.scene),{chapter,scene});}; +const clean=async(chapter,scene)=>{await p.waitForFunction(()=>document.querySelector('[data-review-panel]')?.dataset.selectedScene==='');const value=await p.evaluate(()=>({focus:window.PlotDirectorNarrativeFocus.state,chapter:Number(document.querySelector('.manuscript-reader').dataset.chapterId),word:{...document.querySelector('[data-writer-word]').dataset},scene:document.querySelector('[data-review-panel]').dataset.selectedScene}));assert.equal(value.focus.chapterID,chapter);assert.equal(value.focus.sceneID,scene);assert.equal(value.chapter,chapter);assert.equal(value.word.paragraphId,'');assert.equal(value.word.sceneId,'');assert.equal(value.scene,'');assert.equal(writes,0);assert.equal(commands,0); +await p.locator('[data-review-new]').click();const form=p.locator('[data-review-form]');for(const name of ['StartParagraph','EndParagraph','SceneID'])assert.equal(await form.locator(`[name=${name}]`).inputValue(),'');await form.locator('[data-review-cancel]').click();}; +const mapped=async(scene)=>{await p.waitForFunction(id=>document.querySelector('[data-review-panel]')?.dataset.selectedScene===String(id),scene);assert(await p.locator('[data-writer-word]').getAttribute('data-paragraph-id'));}; +await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus&&document.querySelector('[data-review-panel]'));await set(21,31);await mapped(31); +await set(21,null);await clean(21,null); // Original browser reproduction. +await p.reload();await p.waitForFunction(()=>window.positions.some(p=>p.sceneID===null));await clean(21,null); +await p.evaluate(()=>{window.dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true}));window.dispatchEvent(new PageTransitionEvent('pageshow',{persisted:true}));});await clean(21,null); +await set(21,31);await mapped(31);await set(21,101);await mapped(101); // Normal precise transition. +await set(22,32);await mapped(32);await set(21,31);await mapped(31); // Cross-chapter. +await cookie('same-chapter-unmapped');await set(21,101); // Still-rendered mapped DOM until accepted update arrives. +await p.evaluate(()=>window.dispatchEvent(new Event('online')));await p.waitForFunction(()=>document.querySelector('.manuscript-reader').dataset.revision==='8');await clean(21,101); // Accepted association removed; same paragraph GUIDs. +assert.match(await p.locator('[data-review-focus-notice]').textContent(),/Precise scene positioning is unavailable/); +await set(21,31);await mapped(31);await set(21,101);await clean(21,101); // Mapped to already-unmapped scene, same chapter. +// Explicit passage selection remains available after fallback. +await p.locator('[data-paragraph-id][data-scene-id="31"]').first().click();await mapped(31); +// Dirty annotation defers reset and preserves its original reference and text. +await p.locator('[data-review-new]').click();const form=p.locator('[data-review-form]');await form.locator('[name=Observation]').fill('Retain my original draft');const original=await form.locator('[name=StartParagraph]').inputValue(); +await p.evaluate(()=>window.PlotDirectorNarrativeFocus.set({bookID:12,chapterID:21,sceneID:null}));await p.locator('[data-review-focus-notice]').filter({hasText:'Save or cancel'}).waitFor();assert.equal(await form.locator('[name=Observation]').inputValue(),'Retain my original draft');assert.equal(await form.locator('[name=StartParagraph]').inputValue(),original); +await form.locator('[data-review-cancel]').click();await p.locator('[data-review-focus-notice] button').click();await clean(21,null); +// Dirty chapter/scene note likewise defers; resuming explicitly clears the obsolete target. +await set(21,31);await mapped(31);await p.locator('[data-authoring-edit]').first().click();const note=p.locator('[data-authoring-form]:not([hidden])');await note.locator('textarea').first().fill('Retain note draft'); +await p.evaluate(()=>window.PlotDirectorNarrativeFocus.set({bookID:12,chapterID:21,sceneID:null}));await p.locator('[data-review-focus-notice]').filter({hasText:'Save or cancel'}).waitFor();assert.equal(await note.locator('textarea').first().inputValue(),'Retain note draft');await note.locator('[data-authoring-cancel]').click();await p.locator('[data-review-focus-notice] button').click();await clean(21,null); +// Deliver an obsolete same-chapter panel AFTER the chapter-only request completed. +await cookie('mapped');await p.reload();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await set(21,31);await mapped(31);let release;const gate=new Promise(r=>release=r);let held=false; +await p.route('**/WriterReview/Panel?*',async r=>{if(!held&&new URL(r.request().url()).searchParams.has('paragraphId')){held=true;const response=await r.fetch();await gate;await r.fulfill({response}).catch(()=>{});}else await r.continue();}); +const requested=p.waitForRequest(r=>r.url().includes('/WriterReview/Panel?')&&new URL(r.url()).searchParams.has('paragraphId'));await p.evaluate(()=>window.PlotDirectorNarrativeFocus.set({bookID:12,chapterID:21,sceneID:101}));await requested;await set(21,null);release();await p.unroute('**/WriterReview/Panel?*');await clean(21,null); +assert.equal(writes,0);assert.equal(commands,0);assert.deepEqual(errors,[]);await c.close();console.log('PASS Phase3B.1 Review '+(pwa?'simulated PWA':'Chromium')+': same/cross-chapter, unmapped/removed associations, dirty annotation/note deferral, late panel, refresh/return, explicit reselection; zero annotation writes/Word commands.'); +}}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1;}); diff --git a/PlotLine.Tests/NativeReviewNavigationTests.cs b/PlotLine.Tests/NativeReviewNavigationTests.cs new file mode 100644 index 00000000..9e7f632c --- /dev/null +++ b/PlotLine.Tests/NativeReviewNavigationTests.cs @@ -0,0 +1,87 @@ +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text.Json; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using PlotDirector.Companion.Protocol; +using PlotLine.Controllers; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services.NativeCompanion; + +internal static class NativeReviewNavigationTests +{ + private sealed class Clock : TimeProvider + { + public DateTimeOffset Now = DateTimeOffset.UtcNow; + public override DateTimeOffset GetUtcNow() => Now; + } + private sealed class TempData : ITempDataProvider + { + public IDictionary LoadTempData(HttpContext context) => new Dictionary(); + public void SaveTempData(HttpContext context, IDictionary values) { } + } + public static async Task Run() + { + void Check(bool ok,string message) { if (!ok) throw new Exception(message); } + var protection = new EphemeralDataProtectionProvider(); + var protector = protection.CreateProtector("NativeImport.Source.v1"); + var clock = new Clock(); + foreach(var scenario in new[]{"valid", "failed ack", "timeout ack", "new session", "equal revision reopen", "changed prefix reopen", "copied properties", "missing session", "missing revision", "ambiguous session", "missing source", "source session mismatch", "changed content", "changed revision", "unsaved", "wrong manuscript", "wrong book", "wrong author", "wrong instance", "expired", "replaced", "invalid offset"}) + { + var store = new NativePresenceStore(clock); + var instance = Guid.NewGuid(); var session = Guid.NewGuid(); var manuscript = Guid.NewGuid(); + var capture = new AiChapterRequest {RequestId=Guid.NewGuid(),BookId=3,ManuscriptId=manuscript,SessionId=session,Revision=2,ChapterStart=10,ChapterEnd=30,Paragraphs=[new(){Index=1,Start=10,End=20,Text="First prose\r"},new(){Index=2,Start=20,End=30,Text="Second prose\r"}]}; + var result = new AiChapterResult {State="complete",DocumentRevision=2,Scenes=[new(){Title="First",Start=10,End=20}]}; + var row = new NativeReview {ReviewID=capture.RequestId,UserID=7,BookID=3,ManuscriptID=manuscript,SourceSession=session,SourceRevision=2,ChapterStart=10,ChapterEnd=30, + ContentHash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{capture.ChapterStart,capture.ChapterEnd,capture.Paragraphs})))}; + var liveSession=session; var liveManuscript=manuscript; var liveBook=3; var liveRevision=2L; var saved=true; + if(scenario is "new session" or "equal revision reopen" or "changed prefix reopen" or "copied properties")liveSession=Guid.NewGuid(); + if(scenario=="new session")liveRevision=0; + if(scenario=="changed prefix reopen")capture.Paragraphs[0].Text="Changed preceding text\r"; + if(scenario=="missing session")row.SourceSession=null; + if(scenario=="missing revision")row.SourceRevision=null; + if(scenario=="source session mismatch")capture.SessionId=Guid.NewGuid(); + if(scenario=="changed content")capture.Paragraphs[0].Text="Different content\r"; // Retained content no longer agrees with the stored hash. + if(scenario=="changed revision")liveRevision++; + if(scenario=="unsaved")saved=false; + if(scenario=="wrong manuscript")liveManuscript=Guid.NewGuid(); + if(scenario=="wrong book")liveBook=4; + if(scenario=="invalid offset")result.Scenes[0].Start=11; + row.EncryptedSource=scenario=="missing source"?null:protector.Protect(JsonSerializer.Serialize(capture)); + row.ResultJson=JsonSerializer.Serialize(result); + var reviews=new MemoryNativeReviews();await reviews.Save(row); + var before=JsonSerializer.Serialize(row); + var access=NativeWorkflowTests.Proxy((n,a)=>n=="GetBookStructureAsync"?Task.FromResult(new(){BookId=(int)a![0]!}):throw new Exception("Unexpected canonical write: "+n)); + var books=NativeWorkflowTests.Proxy((n,a)=>n=="GetAsync"?Task.FromResult(new(){BookID=3,ProjectID=1}):throw new Exception("Unexpected write: "+n)); + NativePresence State(long sequence)=>new(){Sequence=sequence,BookId=liveBook,ManuscriptId=liveManuscript,Revision=liveRevision,WordAvailable=true,WordSaved=saved,CanAcknowledgeNavigation=true,DocumentTitle="Disposable source"}; + store.Put(7,"grant",clock.Now.AddHours(1),instance,liveSession,State(1)); + if(scenario=="ambiguous session")store.Put(7,"grant",clock.Now.AddHours(1),Guid.NewGuid(),liveSession,State(1)); + if(scenario=="expired")clock.Now=clock.Now.AddSeconds(46); + if(scenario=="replaced"){store.Remove(7,"grant",instance,liveSession);store.Put(7,"replacement",clock.Now.AddHours(1),instance,Guid.NewGuid(),State(2));} + var http=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,scenario=="wrong author"?"8":"7")],"fixture"))}; + var api=new NativeWorkspaceController(access,books,reviews,store,new NativeReviewNavigation(protection)){ControllerContext=new(){HttpContext=http},TempData=new TempDataDictionary(http,new TempData())}; + var response=await api.Navigate(row.ReviewID,0,scenario=="wrong instance"?Guid.NewGuid():instance,liveSession); + var valid=scenario is "valid" or "failed ack" or "timeout ack"; + Check(valid?response is RedirectToActionResult:response is ConflictObjectResult or NotFoundResult,scenario+": navigation outcome"); + var command=store.TakeNavigation(7,"grant",instance,liveSession); + Check(valid?command?.Chapter?.Start==10:command==null,scenario+": unsafe offsets issue no native command/range selection"); + if(valid) + { + Check(store.NavigationState(7,3,instance,liveSession,command!.Id)=="requested","queued never means completed"); + if(scenario=="timeout ack"){clock.Now=clock.Now.AddSeconds(26);Check(store.NavigationState(7,3,instance,liveSession,command.Id)=="timed-out","bounded timeout");} + else {var ack=State(2);ack.NavigationAcknowledgedId=command.Id;ack.NavigationResult=scenario=="failed ack"?"failed":"completed";store.Put(7,"grant",clock.Now.AddHours(1),instance,liveSession,ack);Check(store.NavigationState(7,3,instance,liveSession,command.Id)==ack.NavigationResult,"correlated exact-session acknowledgement");} + } + Check(JsonSerializer.Serialize(row)==before,scenario+": navigation never rewrites source or decisions"); + if(scenario!="wrong author") + { + var view=(ViewResult)await api.Review(row.ReviewID); + Check(view.Model is NativeReviewModel,scenario+": review remains readable"); + if(!valid&&scenario!="wrong instance")Check(((NativeReviewModel)view.Model!).Sessions.Length==0,scenario+": unsafe navigation chooser disabled"); + Check(await api.Decide(row.ReviewID,1,[new(){Index=0,State="approved",Title="Author decision",Summary="Preserved"}]) is RedirectToActionResult,scenario+": decisions remain available"); + } + } + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index a0ce4653..8e5660dd 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -179,6 +179,8 @@ if(args.Contains("--native-companion")){await NativeCompanionTests.Run();Console if(args.Contains("--sql-architecture-check")){DatabaseArchitectureTests.Run();Console.WriteLine("PASS stored procedure architecture guard");return;} if(args.Contains("--sql-architecture-inventory")){Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(DatabaseArchitectureTests.Scan(Directory.GetCurrentDirectory()),new System.Text.Json.JsonSerializerOptions{WriteIndented=true}));return;} +if(args.Contains("--native-review-navigation")){await NativeReviewNavigationTests.Run();Console.WriteLine("PASS historical review navigation session/content guards and acknowledgements");return;} + var tests = new (string Name, Action Test)[] { ("Settlement boundaries preserve anchors, routes and backup/import contracts",MapSettlementTests.Run), @@ -196,6 +198,7 @@ var tests = new (string Name, Action Test)[] ("Development SQL correlation, privacy and bounded queue polling",()=>SqlLaunchDiagnosticsTests.Run()), ("Writer Phase21 repeated navigation acknowledgement and book isolation",()=>WriterPhase21Tests.Run()), ("Review accepted anchors, immutable provenance and author decisions",()=>WriterReviewTests.Run()), + ("Historical native review offsets require original session and source proof",()=>NativeReviewNavigationTests.Run().GetAwaiter().GetResult()), ("Writer Word verified navigation and acknowledgement",()=>WriterWordTests.Run().GetAwaiter().GetResult()), ("Writer inline authoring validation",()=>WriterAuthoringTests.Run()), ("Narrative navigation action boundary",()=>NarrativeNavigationTests.Run().GetAwaiter().GetResult()), diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 245c4f9f..e5e49544 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -22,6 +22,8 @@ internal static class ToolbarBrowserHost private static readonly ParagraphManuscript readerFixture = ReviewSnapshot(); private static ParagraphManuscript ReviewSnapshot(){var state=ManuscriptReaderTests.Snapshot();var scene=Guid.NewGuid();state.Scenes=[new(){Id=scene,CanonicalId=31,ChapterId=21}];foreach(var p in state.Paragraphs.Where(p=>p.ChapterId==21&&p.Story))p.SceneId=scene;return state;} private static readonly ParagraphManuscript readerFocusFixture=ManuscriptReaderTests.FocusSnapshot(); + private static readonly ParagraphManuscript readerSameChapterUnmapped=SameChapterUnmapped(); + private static ParagraphManuscript SameChapterUnmapped(){var state=PlotLine.Services.Manuscript.ParagraphManuscriptEngine.Clone(readerFocusFixture);var target=state.Scenes.Single(s=>s.CanonicalId==101).Id;foreach(var p in state.Paragraphs.Where(p=>p.SceneId==target))p.SceneId=null;state.Revision++;return state;} private static readonly ParagraphManuscript readerUnmappedFixture=ManuscriptReaderTests.FocusSnapshot(true); private static readonly ParagraphManuscript readerLongFixture = ManuscriptReaderTests.LongSnapshot(); private static readonly System.Collections.Concurrent.ConcurrentDictionary<(int User, int Chapter), ChapterGoal> writerGoals = new(); @@ -158,7 +160,7 @@ internal static class ToolbarBrowserHost builder.Services.AddSingleton(); builder.Services.AddScoped(services => ManuscriptReaderTests.FixtureService(() => services.GetRequiredService().HttpContext!.Request.Query["reader-error"] == "true" - ? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService().HttpContext!.Request.Cookies["fixture-focus-reader"]=="mapped"?readerFocusFixture:services.GetRequiredService().HttpContext!.Request.Cookies["fixture-focus-reader"]=="unmapped"?readerUnmappedFixture:services.GetRequiredService().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture,allowSecondBook:true)); + ? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService().HttpContext!.Request.Cookies["fixture-focus-reader"]=="same-chapter-unmapped"?readerSameChapterUnmapped:services.GetRequiredService().HttpContext!.Request.Cookies["fixture-focus-reader"]=="mapped"?readerFocusFixture:services.GetRequiredService().HttpContext!.Request.Cookies["fixture-focus-reader"]=="unmapped"?readerUnmappedFixture:services.GetRequiredService().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture,allowSecondBook:true)); builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/PlotLine/Controllers/NativeWorkspaceController.cs b/PlotLine/Controllers/NativeWorkspaceController.cs index 6971be19..f62cafc6 100644 --- a/PlotLine/Controllers/NativeWorkspaceController.cs +++ b/PlotLine/Controllers/NativeWorkspaceController.cs @@ -8,7 +8,7 @@ using PlotLine.Models; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [Authorize,Route("native-companion")] -public sealed class NativeWorkspaceController(IWordCompanionRepository access,IBookRepository books,INativeReviewRepository reviews,NativePresenceStore presence):Controller +public sealed class NativeWorkspaceController(IWordCompanionRepository access,IBookRepository books,INativeReviewRepository reviews,NativePresenceStore presence,NativeReviewNavigation? navigation=null):Controller { private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); [HttpGet("workspace")] @@ -69,13 +69,16 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB { var row=await reviews.Get(Author,id);if(row==null)return NotFound();if(await access.GetBookStructureAsync(row.BookID,Author)==null)return Forbid(); var book=await books.GetAsync(row.BookID);if(book==null)return NotFound(); - return View(new NativeReviewModel(row,JsonSerializer.Deserialize(row.ResultJson)!,string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize(row.DecisionsJson)!,presence.Read(Author,row.BookID).Where(l=>l.Position.WordAvailable&&l.Position.ManuscriptId==row.ManuscriptID&&l.Position.Revision==JsonSerializer.Deserialize(row.ResultJson)!.DocumentRevision).ToArray(),book.ProjectID)); + var result=JsonSerializer.Deserialize(row.ResultJson)!; + return View(new NativeReviewModel(row,result,string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize(row.DecisionsJson)!,navigation?.Candidates(Author,row,result,presence.Read(Author,0))??[],book.ProjectID)); } [HttpPost("reviews/{id:guid}/navigate"),ValidateAntiForgeryToken] public async Task Navigate(Guid id,int index,Guid instanceId,Guid sessionId) { var row=await reviews.Get(Author,id);if(row==null)return NotFound();if(await access.GetBookStructureAsync(row.BookID,Author)==null)return Forbid();var result=JsonSerializer.Deserialize(row.ResultJson)!; - if(index<0||index>=result.Scenes.Length)return BadRequest();if(!presence.Navigate(Author,row.BookID,instanceId,sessionId,row.ManuscriptID,result.DocumentRevision,result.Scenes[index].Start))return Conflict("Word session is unavailable or this snapshot changed. Detect and review again."); + if(!ModelState.IsValid||index<0||index>=result.Scenes.Length||instanceId==Guid.Empty||sessionId==Guid.Empty)return BadRequest(); + var lease=navigation?.Candidates(Author,row,result,presence.Read(Author,0)).SingleOrDefault(l=>l.Instance==instanceId&&l.Session==sessionId); + if(lease==null||navigation?.Current(Author,row,result,lease)!=true||!presence.Navigate(Author,row.BookID,instanceId,sessionId,row.ManuscriptID,result.DocumentRevision,result.Scenes[index].Start,requireSaved:true,requireAcknowledgement:true))return Conflict(NativeReviewNavigation.Unavailable); TempData["NativeReviewSaved"]="Navigation requested for the selected Word session. No text changes.";return RedirectToAction(nameof(Review),new{id}); } [HttpPost("reviews/{id:guid}"),ValidateAntiForgeryToken,RequestSizeLimit(2*1024*1024),RequestFormLimits(ValueCountLimit=2200)] diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 1c05ef75..13c4b385 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -112,6 +112,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/PlotLine/Services/NativeCompanion/NativeReviewNavigation.cs b/PlotLine/Services/NativeCompanion/NativeReviewNavigation.cs new file mode 100644 index 00000000..dd5e12f2 --- /dev/null +++ b/PlotLine/Services/NativeCompanion/NativeReviewNavigation.cs @@ -0,0 +1,45 @@ +using System.Security.Cryptography; +using System.Text.Json; +using Microsoft.AspNetCore.DataProtection; +using PlotDirector.Companion.Protocol; +using PlotLine.Data; + +namespace PlotLine.Services.NativeCompanion; + +// Historical offsets are usable only with authenticated source content and its original live session. +// Word revisions are local to an open session; a reopened/copy document cannot inherit this proof. +public sealed class NativeReviewNavigation(IDataProtectionProvider protection) +{ + public const string Unavailable = "The original Word position can no longer be verified. Review decisions remain available; resubmit the chapter from Word to establish a current position."; + private readonly IDataProtector source = protection.CreateProtector("NativeImport.Source.v1"); + + public NativeLease[] Candidates(int author, NativeReview row, AiChapterResult result, IEnumerable leases) + { + var matching = leases.Where(l => l.Session == row.SourceSession).Take(2).ToArray(); + return matching.Length == 1 && Current(author, row, result, matching[0]) ? matching : []; + } + + public bool Current(int author, NativeReview row, AiChapterResult result, NativeLease lease) + { + if (result.Scenes == null || result.Scenes.Length == 0 || row.BookID <= 0 || row.UserID != author || lease.User != author || lease.Instance == Guid.Empty || + row.SourceSession is not Guid session || session == Guid.Empty || session != lease.Session || + row.SourceRevision is not long revision || revision < 0 || revision != result.DocumentRevision || + lease.Position.Revision != revision || lease.Position.BookId != row.BookID || + lease.Position.ManuscriptId != row.ManuscriptID || row.ManuscriptID == Guid.Empty || + !lease.Position.WordAvailable || lease.Position.WordSaved != true || !lease.Position.CanAcknowledgeNavigation || + string.IsNullOrEmpty(row.EncryptedSource)) return false; + try + { + var capture = JsonSerializer.Deserialize(source.Unprotect(row.EncryptedSource)); + if (capture == null || capture.SessionId != session || capture.Revision != revision || + capture.BookId != row.BookID || capture.ManuscriptId != row.ManuscriptID || + capture.ChapterStart != row.ChapterStart || capture.ChapterEnd != row.ChapterEnd) return false; + NativeChapterMapping.Build(capture); + var hash = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new { capture.ChapterStart, capture.ChapterEnd, capture.Paragraphs }))); + return hash == row.ContentHash && result.Scenes.All(scene => + scene.Start >= capture.ChapterStart && scene.End <= capture.ChapterEnd && scene.End > scene.Start && + capture.Paragraphs.Any(p => p.Start == scene.Start) && capture.Paragraphs.Any(p => p.End == scene.End)); + } + catch (Exception e) when (e is CryptographicException or JsonException or ArgumentException) { return false; } + } +} diff --git a/PlotLine/Views/NativeWorkspace/Review.cshtml b/PlotLine/Views/NativeWorkspace/Review.cshtml index 6372a866..33c1092b 100644 --- a/PlotLine/Views/NativeWorkspace/Review.cshtml +++ b/PlotLine/Views/NativeWorkspace/Review.cshtml @@ -20,6 +20,7 @@ @if(Model.Sessions.Length>0){
Locate a suggested scene in Word
@Html.AntiForgeryToken() -

Requires the exact live manuscript and observed revision. Navigation is explicit and never triggered by following.

} +

Requires the original live session, saved revision and verified source content. Navigation is explicit and never triggered by following.

} + else{

@PlotLine.Services.NativeCompanion.NativeReviewNavigation.Unavailable

}

After saving decisions, return to the Companion workspace, select the reviewed chapters and preview the approved import. Only approved scenes are included. No import occurs until you confirm the preview. For older captures, reconnect the Companion, enable encrypted import capture in browser approval, then explicitly resubmit the chapter. Unchanged analysis can be reused.

diff --git a/PlotLine/wwwroot/js/narrative-focus-review.js b/PlotLine/wwwroot/js/narrative-focus-review.js index bd2212bc..f7869f8a 100644 --- a/PlotLine/wwwroot/js/narrative-focus-review.js +++ b/PlotLine/wwwroot/js/narrative-focus-review.js @@ -37,7 +37,7 @@ for(const [name,value]of reader._focusFilters||[]){const select=columns.querySelector(`[data-annotation-filter="${name}"]`);if(select){select.value=value;select.dispatchEvent(new Event('change',{bubbles:true}));}}delete reader._focusFilters; const resolved=reader.readerResolveFocus(focus); notice.hidden=!focus.sceneID||resolved.precise; - if(!notice.hidden)notice.textContent='Current Focus: '+focus.label+'. Precise scene positioning is unavailable: no accepted paragraph is mapped to this scene. Verified Review references are unchanged.'; + if(!notice.hidden)notice.textContent='Current Focus: '+focus.label+'. Precise scene positioning is unavailable: no accepted paragraph is mapped to this scene. Chapter context is shown; select an accepted passage for verified scene context.'; window.dispatchEvent(new Event('plotdirector:context-changed')); await frame();await frame(); if(mine!==generation||!same(focus,current())||!reader.isConnected||!canChange())return; diff --git a/PlotLine/wwwroot/js/writer-review.js b/PlotLine/wwwroot/js/writer-review.js index 3a961d19..c2dbaa9f 100644 --- a/PlotLine/wwwroot/js/writer-review.js +++ b/PlotLine/wwwroot/js/writer-review.js @@ -4,7 +4,15 @@ root.reviewDispose?.();const events=new AbortController();const onWindow=(name,h const editor=root.querySelector('[data-review-editor]');const editorial=root.closest('.writer21-editorial')||root;const form=root.querySelector('[data-review-form]'),context=root.querySelector('[data-review-context]'),message=root.querySelector('[data-review-message]'),reference=root.querySelector('[data-review-reference]'),error=root.querySelector('[data-review-error]'),newButton=root.querySelector('[data-review-new]'); let anchor=null,selected=null,page=1,dirty=false,busy=false,loading=false,allowLeave=false,pauseBefore=false,controller=null,generation=0,selectionTimer=null,lastContext=''; root.canChangeNarrative=()=>!dirty&&!busy&&!editorial.querySelector('[data-authoring-form]:not([hidden]),[data-busy="true"]')&&!document.querySelector('dialog[open]')&&(getSelection()?.isCollapsed!==false);root.reviewDispose=()=>{events.abort();++generation;clearTimeout(selectionTimer);controller?.abort();}; -root.selectNarrativeParagraph=async id=>{if(!root.canChangeNarrative())return false;clearTimeout(selectionTimer);if(id){const paragraph=reader.querySelector(`[data-paragraph-id="${CSS.escape(id)}"]`);if(!paragraph)return false;selected=id;anchor={StartParagraph:id,EndParagraph:id,StartOffset:0,EndOffset:paragraph.textContent.length};wordReference(id);reference.textContent='Accepted paragraph selected; nothing is saved until you record an observation.';}await load(true,true);return true;}; +root.selectNarrativeParagraph=async id=>{if(!root.canChangeNarrative())return false;clearTimeout(selectionTimer);if(id){const paragraph=reader.querySelector(`[data-paragraph-id="${CSS.escape(id)}"]`);if(!paragraph)return false;selected=id;anchor={StartParagraph:id,EndParagraph:id,StartOffset:0,EndOffset:paragraph.textContent.length};wordReference(id);reference.textContent='Accepted paragraph selected; nothing is saved until you record an observation.';}else{ + selected=null;anchor=null;wordReference(null);if(word)word.dataset.sceneId=''; + const panel=context.querySelector('[data-review-panel]');if(panel)panel.dataset.selectedScene=''; + document.querySelector('[data-review-scene-context]')?.replaceChildren(document.createTextNode('Chapter context; select an accepted passage for verified scene notes.')); + for(const note of editorial.querySelectorAll('[data-observation][data-scope=Scene]'))note.hidden=true; + for(const name of ['StartParagraph','EndParagraph','StartOffset','EndOffset','SceneID'])field(name).value=''; + reference.textContent='Chapter-level context; no precise passage or scene is selected.'; + window.dispatchEvent(new Event('review-reference-changed')); + }await load(true,true);return true;}; const field=n=>form.elements.namedItem(n),readerContent=reader.querySelector('#reader-content'),word=document.querySelector('[data-writer-word]'); const nodeParagraph=n=>(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest('[data-paragraph-id]'); function capture(){const s=getSelection();if(!s||s.isCollapsed||s.rangeCount!==1)return null;const r=s.getRangeAt(0),first=nodeParagraph(r.startContainer),last=nodeParagraph(r.endContainer);if(!first||!last||!readerContent.contains(first)||!readerContent.contains(last))return null;const before=document.createRange();before.selectNodeContents(first);before.setEnd(r.startContainer,r.startOffset);const after=document.createRange();after.selectNodeContents(last);after.setEnd(r.endContainer,r.endOffset);return{StartParagraph:first.dataset.paragraphId,EndParagraph:last.dataset.paragraphId,StartOffset:before.toString().length,EndOffset:after.toString().length};}