diff --git a/Docs/Codex/Notifications.md b/Docs/Codex/Notifications.md index c66e222e..f5f2b341 100644 --- a/Docs/Codex/Notifications.md +++ b/Docs/Codex/Notifications.md @@ -73,3 +73,13 @@ Toasts default to **Bottom left**. Open the account menu → **Customise PlotDir The account's `AppUser.ToastPosition` is read through `UserAppearance_Get` and saved through `UserAppearance_SaveToastPosition` (`295_UserToastPosition.sql`), using the existing appearance repository and authenticated, antiforgery-protected `/Appearance/ToastPosition` action. All three shell hosts render that server preference, including fresh sessions and installed PWA use. A user-scoped localStorage event relays confirmed changes to other open same-origin windows; localStorage does not override the database on a new page. Failed saves restore the previous position. Toasts stack upwards in arrival order across notification types. Safe-area margins apply on both sides and below; narrow viewports reserve additional space above bottom controls. A shell with additional fixed controls can increase `--pd-toast-bottom-offset`. Existing toast types, timing, deduplication, dismissal and announcements are unchanged. Run `PlotLine.Tests/Browser/toast-position.cjs` against the isolated toolbar browser fixture for position, immediate application, persistence, failure rollback, cross-window and narrow/standalone checks. + +## Word incident and current-chapter authority correction + +The heartbeat's `ChapterIssue` means the native reader's `FailedRevision` matches its current Word revision. It is not an accepted-checkpoint status. Previously `NativePresenceController` copied it into a synthetic cached `ChapterProgress=Needs review`, which remained after a clear heartbeat. That overwrite is removed: the current reading flag and server checking/acceptance progress remain separate. Reading-state transitions are logged without manuscript prose; native diagnostics are preserved. Companion Settings → Advanced mode → Troubleshooting exposes Connection and document diagnostics and Open logs folder. Do not promise that clicking Synchronise repairs a reader failure or constitutes chapter acceptance. + +`WriterWord_ChapterVerification` (migration 296) is SELECT-only. The selected chapter is verified only when its accepted checkpoint matches an unexpired validation for the authorised user, manuscript, session, Word revision, content hash, identity hash and mapping hash. Needs-review checkpoints stay needs-review. No canonical data or flags are changed. A historical content-acceptance timestamp is labelled as historical; current validation has its own timestamp. Document-wide progress, reading failure and current-chapter verification are distinct; another chapter's failure does not falsely invalidate a verified selected chapter. + +Word failure receipts live in the bounded, account-scoped `plotdirector.wordIncidents.v1.` localStorage journal. Reading, transfer and document-checking have separate incident identities. A displayed incident is remembered before announcement, so dismissal and navigation cannot reannounce it. Changed manuscript/revision/request/failure details or a new failure after an explicit resolved transition can notify again, subject to normal shared toast deduplication. Current-book scoping prevents an unrelated open document's failure from interrupting that workspace. Transfer acceptance does not clear a reading incident; an explicit cleared reading flag does. Actual successful checking clears its own incident. Resolution removes an obsolete visible toast, including across same-origin windows. Persistent details remain accessible even when no toast is shown. + +Focused checks: `word-state-lifecycle.cjs` tests disposable Book/Writer notification-shell lifetimes, dismissal, repeated polling, changed failures, independent recovery and scoping; `word-ribbon-verification.cjs` tests the real Writer Razor ribbon switching selected chapters and refusing sync acknowledgements as verification evidence. Existing manual-transfer and navigation/Reader regressions remain applicable. Development read-only checks confirmed a historical 15 November checkpoint with matching 21 November session validation; wrong-revision evidence is unverified and unauthorised users receive no rows. Canonical payload hashes are checked before/after deployment. No import, rescan, replay, flag reset or native Windows change is part of this correction. diff --git a/PlotLine.Tests/Browser/word-ribbon-verification.cjs b/PlotLine.Tests/Browser/word-ribbon-verification.cjs new file mode 100644 index 00000000..01678057 --- /dev/null +++ b/PlotLine.Tests/Browser/word-ribbon-verification.cjs @@ -0,0 +1,20 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'); +const base=process.env.PD_BROWSER_FIXTURE_URL||'http://127.0.0.1:5238'; +const hub=`window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return{state:'Connected',on:()=>{},onreconnected:()=>{},onreconnecting:()=>{},onclose:()=>{},start:async()=>{},stop:async()=>{},invoke:async()=>({windows:[],isConnected:false})}}}};`; +(async()=>{const browser=await chromium.launch();try{const context=await browser.newContext();await context.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:hub})); +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,canChapterSync:true,canParagraphSync:true,revision:19,chapterIssue:'',expires:new Date(Date.now()+3600000).toISOString()}; +let chapterState='Needs review',proof=false,reading=false,progress={state:'Synchronised'},packet;const errors=[]; +await context.route('**/native-companion/status*',r=>{const chapter=Number(new URL(r.request().url()).searchParams.get('writerChapterId'))||21;packet={bookId:12,chapterId:chapter,leases:[{...lease,chapterIssue:reading?'needs_review':'',chapterProgress:progress}],canonical:{manuscriptID:lease.manuscriptId,chapterAcceptedUtc:'2026-11-15T21:07:38Z'},verifiedPositions:[],chapterVerifications:[{bookId:12,chapterId:chapter,instanceId:lease.instanceId,sessionId:lease.sessionId,wordRevision:19,verification:{manuscriptID:lease.manuscriptId,checkpointStatus:chapter===21?'Synchronised':chapterState,checkpointMessage:'Synthetic checkpoint review required',lastAcceptedUtc:'2026-11-15T21:07:38Z',validatedUtc:chapter===21||proof?'2026-11-21T18:47:24Z':null,isCurrent:chapter===21||proof}}]};return r.fulfill({json:packet});}); +await context.route('**/WriterWord/Availability?*',r=>r.fulfill({json:{chapter:false,scene:false,paragraph:false}}));await context.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null}})); +const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/Writer/Write?projectId=7&bookId=12&objective=true'); +const label=page.locator('[data-word-ribbon-status]');await label.filter({hasText:'Chapter verified'}).waitFor();assert((await label.getAttribute('title')).includes('historical; not a current failure')); +const select=chapter=>page.evaluate(chapter=>dispatchEvent(new CustomEvent('plotdirector:narrative-focus-changed',{detail:{bookID:12,chapterID:chapter}})),chapter); +await select(22);await label.filter({hasText:'Chapter needs review'}).waitFor(); +chapterState='Synchronised';await page.evaluate(()=>dispatchEvent(new Event('plotdirector:refresh-word-status')));await label.filter({hasText:'Chapter not verified'}).waitFor(); +await page.evaluate(v=>dispatchEvent(new CustomEvent('writer-word-state',{detail:{...v,leases:v.leases.map(l=>({...l,paragraphTransfer:{kind:'chapter',state:'accepted',requestId:'manual-sync'}}))}})),packet);assert.equal(await label.textContent(),'Chapter not verified','manual sync transfer is not current-chapter proof'); +proof=true;await page.evaluate(()=>dispatchEvent(new Event('plotdirector:refresh-word-status')));await label.filter({hasText:'Chapter verified'}).waitFor();await select(21);await label.filter({hasText:'Chapter verified'}).waitFor();reading=true;progress=null;await page.evaluate(()=>dispatchEvent(new Event('plotdirector:refresh-word-status'))); +await page.locator('#native-companion-status').evaluate(n=>n.click());await page.locator('[data-word-sync-feedback]').filter({hasText:'Companion reports a chapter-reading failure'}).waitFor(); +reading=false;await page.evaluate(()=>dispatchEvent(new Event('plotdirector:refresh-word-status')));await page.locator('[data-word-sync-feedback]').filter({hasText:'No chapter-reading failure is currently reported'}).waitFor();assert.equal(await page.locator('.pd-toast--warning').count(),0,'resolved reading warning is removed while verification remains independent'); +assert.deepEqual(errors,[]); +console.log('PASS actual Writer ribbon: current selected chapter, historical accepted checkpoint vs live verification, genuine review, no false success from manual-sync acceptance, verified recovery.');await context.close(); +}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/word-state-lifecycle.cjs b/PlotLine.Tests/Browser/word-state-lifecycle.cjs new file mode 100644 index 00000000..12dc8095 --- /dev/null +++ b/PlotLine.Tests/Browser/word-state-lifecycle.cjs @@ -0,0 +1,27 @@ +// Production JS over disposable HTTP shells and real Writer Razor; no manuscript/DB writes. +const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path'); +const base=process.env.PD_BROWSER_FIXTURE_URL||'http://127.0.0.1:5238',assets=path.resolve(__dirname,'../../PlotLine/wwwroot/js'); +(async()=>{const browser=await chromium.launch();try{for(const standalone of [false,true]){ + const context=await browser.newContext();if(standalone)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true})); + await context.route('**/lifecycle-*',r=>r.fulfill({contentType:'text/html',body:'
'})); + const page=await context.newPage(); + const load=async name=>{await page.goto(base+'/lifecycle-'+name);for(const file of ['notifications','word-notifications','word-chapter-status'])await page.addScriptTag({path:assets+'/'+file+'.js'});}; + const lease={instanceId:'instance',sessionId:'session',manuscriptId:'manuscript',bookId:12,revision:19,wordAvailable:true,wordSaved:true,chapterIssue:'needs_review'}; + const pulse=async value=>page.evaluate(leases=>dispatchEvent(new CustomEvent('writer-word-state',{detail:{bookId:12,leases}})),value); + await load('book');await pulse([lease]);assert.equal(await page.locator('.pd-toast--warning').count(),1,'new reading failure warns once'); + await page.locator('.pd-toast--warning button').click();await pulse([lease]);assert.equal(await page.locator('.pd-toast').count(),0,'dismissal respected'); + await load('writer');await pulse([lease]);assert.equal(await page.locator('.pd-toast').count(),0,'navigation cannot reannounce same incident'); + await load('book');await pulse([lease]);assert.equal(await page.locator('.pd-toast').count(),0); + await pulse([{...lease,revision:20}]);assert.equal(await page.locator('.pd-toast--warning').count(),1,'new Word revision failure can notify'); + await pulse([{...lease,revision:20,paragraphTransfer:{state:'accepted',kind:'chapter'},chapterProgress:{state:'Synchronised'}}]);assert.equal(await page.locator('.pd-toast--warning').count(),1,'sync completion is not resolution of the reading failure'); + await pulse([{...lease,revision:20,chapterIssue:''}]);assert.equal(await page.locator('.pd-toast--warning').count(),0,'explicit cleared reading flag resolves warning'); + await page.evaluate(()=>{const now=Date.now;Date.now=()=>now()+6000;}); // retain the shared five-second toast deduplication window + await pulse([{...lease,revision:20}]);await page.locator('.pd-toast--warning').waitFor(); + await pulse([{...lease,chapterIssue:''}]); + await pulse([{...lease,bookId:13}]);assert.equal(await page.locator('.pd-toast--warning').count(),0,'unrelated book cannot interrupt current book'); + const status=await page.evaluate(lease=>{const packet={canonical:{manuscriptID:lease.manuscriptId},chapterVerifications:[{bookId:12,chapterId:21,instanceId:lease.instanceId,sessionId:lease.sessionId,wordRevision:lease.revision,verification:{manuscriptID:lease.manuscriptId,checkpointStatus:'Synchronised',isCurrent:true,lastAcceptedUtc:'2026-11-15T21:07:38Z',validatedUtc:'2026-11-21T18:47:24Z'}}]};return{verified:PlotDirector.wordChapterStatus(packet,{...lease,chapterIssue:''},12,21),reading:PlotDirector.wordChapterStatus(packet,lease,12,21),other:PlotDirector.wordChapterStatus(packet,lease,12,22),manual:PlotDirector.wordChapterStatus({...packet,chapterVerifications:packet.chapterVerifications.map(e=>({...e,verification:{...e.verification,isCurrent:false}}))},{...lease,chapterProgress:{state:'Synchronised'}},12,21)};},lease); + assert.equal(status.verified.label,'Chapter verified');assert(status.verified.text.includes('historical; not a current failure'));assert(status.reading.text.includes('separately reports a chapter-reading failure'));assert.equal(status.other.label,'Verification unavailable');assert.equal(status.manual.label,'Chapter not verified'); + // New browser session shares account-local incident receipts only when same device storage is retained. + console.log('PASS Word incident lifecycle: new/dismissed/navigation/new-revision/recovery/rearmed/scoped warnings; independent chapter verification and historical acceptance; standalone='+standalone); + await context.close(); +}}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/word-toast-outcomes.cjs b/PlotLine.Tests/Browser/word-toast-outcomes.cjs index a0724b2d..a167e522 100644 --- a/PlotLine.Tests/Browser/word-toast-outcomes.cjs +++ b/PlotLine.Tests/Browser/word-toast-outcomes.cjs @@ -24,7 +24,7 @@ const assets=path.resolve(__dirname,'../../PlotLine/wwwroot'); assert.equal(await page.locator('.pd-toast--success').count(),1,'exact manual accepted result reports once'); await pulse([{...lease,chapterProgress:{state:'Needs review',message:'Synthetic review required'}}]); await pulse([{...lease,chapterProgress:{state:'Needs review',message:'Synthetic review required'}}]);assert.equal(await page.locator('.pd-toast--warning').count(),1); - await pulse([{...lease,paragraphTransfer:{state:'failed',message:'Synthetic escalated failure'}}]);assert.equal(await page.locator('.pd-toast--warning').count(),0);assert.equal(await page.locator('.pd-toast--error').count(),1); + await pulse([{...lease,paragraphTransfer:{state:'failed',message:'Synthetic escalated failure'},chapterProgress:{state:'Synchronised'}}]);assert.equal(await page.locator('.pd-toast--warning').count(),0);assert.equal(await page.locator('.pd-toast--error').count(),1); await page.evaluate(()=>{PlotDirector.wordNotifications.syncState('office','accepted','Manual Office sync complete',true);PlotDirector.wordNotifications.connection('office',true);PlotDirector.wordNotifications.connection('office',false);PlotDirector.wordNotifications.connection('office',false);}); assert.equal(await page.locator('.pd-toast--warning').count(),1,'Office loss is deduplicated'); await page.evaluate(()=>PlotDirector.wordNotifications.connection('office',true));assert.equal(await page.locator('.pd-toast--warning').count(),0); diff --git a/PlotLine.Tests/Browser/word-toast-paths.cjs b/PlotLine.Tests/Browser/word-toast-paths.cjs index 7ac0af1d..ab2ed922 100644 --- a/PlotLine.Tests/Browser/word-toast-paths.cjs +++ b/PlotLine.Tests/Browser/word-toast-paths.cjs @@ -23,7 +23,7 @@ const hub=`window.signalR={HubConnectionBuilder:class{withUrl(){return this}with assert.equal(posts,1);assert.equal(await page.locator('.pd-toast').count(),0,'request acknowledgement is not success'); packet={...packet,leases:[{...lease,paragraphTransfer:{requestId,state:'accepted',kind:'chapter'}}]}; await page.evaluate(v=>dispatchEvent(new CustomEvent('writer-word-state',{detail:v})),packet); - await page.locator('.pd-toast--success').filter({hasText:'Saved manuscript check completed.'}).waitFor(); + await page.locator('.pd-toast--success').filter({hasText:'Word transfer accepted. Chapter verification is reported separately.'}).waitFor(); fail=true;await page.locator('[data-word-sync]').click();await page.locator('.pd-toast--error').filter({hasText:'Synthetic request failed'}).waitFor(); await page.waitForFunction(()=>document.querySelector('[data-word-navigate]').disabled===false); await page.locator('[data-word-navigate]').evaluate(n=>n.click()); diff --git a/PlotLine/Controllers/NativePresenceController.cs b/PlotLine/Controllers/NativePresenceController.cs index 9a17015d..48a53d93 100644 --- a/PlotLine/Controllers/NativePresenceController.cs +++ b/PlotLine/Controllers/NativePresenceController.cs @@ -40,9 +40,10 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC if(live!=null&&(before==null||before.Position.NavigationAcknowledgedId!=input.NavigationAcknowledgedId||before.Position.ParagraphRevision!=input.ParagraphRevision||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable||before.Position.WordRunning!=input.WordRunning||before.Position.WordSaved!=input.WordSaved||before.Position.CaptureRequestId!=input.CaptureRequestId||before.Position.CaptureProgress/5!=input.CaptureProgress/5))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted); if(input.CaptureRequestId.HasValue&&capture!=null&&wizard!=null){var progress=await capture.Progress(Author,Grant,input.CaptureRequestId.Value,input.CaptureProgress,instance,session,input.ManuscriptId,input.Revision);if(progress!=null)await wizard.Clients.Group(WordCompanionFollowHub.PresenceGroup(Author)).SendAsync("OnboardingScanProgress",progress,HttpContext.RequestAborted);} if(input.CanParagraphSync&&!input.CanChapterSync&&capture!=null){var lease=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);if(lease!=null)await capture.ObserveParagraphSave(Author,lease);} - if(input.CanChapterSync&&input.ChapterIssue=="needs_review"){ - var earlier=presence.ChapterProgress(Author,input.BookId,instance,session,input.Revision);presence.RecordChapterProgress(Author,input.BookId,instance,session,input.Revision,new(){Total=earlier?.Total??0,Checked=earlier?.Checked??0,Matching=earlier?.Matching??0,NeedsReview=Math.Max(1,(earlier?.Total??1)-(earlier?.Matching??0)),State="Needs review",Message="Chapter reading needs review or retry in Companion Troubleshooting. Independently accepted checkpoints are retained."}); - } + if(before==null||before.Position.ChapterIssue!=input.ChapterIssue) + logger?.LogInformation("Native chapter reading state User={User} Book={Book} Session={Session} WordRevision={WordRevision} ReadingIssue={ReadingIssue}; independent of accepted checkpoints",Author,input.BookId,session,input.Revision,input.ChapterIssue=="needs_review"?"needs_review":"clear"); + // ChapterIssue is the agent's current reading failure, not server chapter acceptance. + // Do not overwrite accepted/checking progress with a sticky synthetic Needs review state. input.ChapterProgress=presence.ChapterProgress(Author,input.BookId,instance,session,input.Revision); input.CatalogVersion=presence.CatalogVersion(Author);input.Navigation=presence.TakeNavigation(Author,Grant,instance,session); if(input.Navigation is {Kind:"navigate"} command)logger?.LogInformation("Deliver explicit Word navigation Id={NavigationId} User={User} Book={Book} Instance={Instance} Session={Session} Revision={Revision} Position={Position}",command.Id,Author,input.BookId,instance,session,command.Revision,command.Chapter?.Start); diff --git a/PlotLine/Controllers/NativeWorkspaceController.cs b/PlotLine/Controllers/NativeWorkspaceController.cs index f62cafc6..5b33224c 100644 --- a/PlotLine/Controllers/NativeWorkspaceController.cs +++ b/PlotLine/Controllers/NativeWorkspaceController.cs @@ -51,8 +51,11 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB if(writerStructure==null||writerChapterId.HasValue&&!writerStructure.Chapters.Any(c=>c.ChapterId==writerChapterId))return NotFound(); var metadata=await writerWords.Metadata(Author,writerBookId.Value,writerChapterId); var verified=new List(); + var chapterVerifications=new List(); foreach(var lease in leases.Where(l=>l.Position.BookId==writerBookId)) { + if(writerChapterId is int selectedChapter) + chapterVerifications.Add(new{instanceId=lease.Instance,sessionId=lease.Session,bookId=writerBookId,chapterId=selectedChapter,wordRevision=lease.Position.Revision,verification=await writerWords.Verification(Author,writerBookId.Value,selectedChapter,lease)}); var position=await writerWords.Position(Author,lease,metadata); if(position?.ChapterID is not int chapter)continue; var selected=writerStructure.Chapters.FirstOrDefault(c=>c.ChapterId==chapter); @@ -60,7 +63,7 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB verified.Add(new{instanceId=lease.Instance,sessionId=lease.Session,chapterId=chapter,sceneId=position.SceneID, chapterTitle=selected.Title,sceneTitle=selected.Scenes.FirstOrDefault(s=>s.SceneId==position.SceneID)?.Title}); } - return Json(new{leases=result,bookId=writerBookId,chapterId=writerChapterId,canonical=metadata==null?null:new{metadata.ManuscriptID,revision=metadata.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture),snapshotUtc=metadata.SnapshotUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ"),chapterAcceptedUtc=metadata.ChapterAcceptedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ")},verifiedPositions=verified}); + return Json(new{leases=result,bookId=writerBookId,chapterId=writerChapterId,canonical=metadata==null?null:new{metadata.ManuscriptID,revision=metadata.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture),snapshotUtc=metadata.SnapshotUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ"),chapterAcceptedUtc=metadata.ChapterAcceptedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ")},verifiedPositions=verified,chapterVerifications}); } return Json(result); } diff --git a/PlotLine/Services/Writer/WriterWordService.cs b/PlotLine/Services/Writer/WriterWordService.cs index 5cb32a2e..8e8c0e43 100644 --- a/PlotLine/Services/Writer/WriterWordService.cs +++ b/PlotLine/Services/Writer/WriterWordService.cs @@ -8,12 +8,23 @@ public sealed class WriterWordMetadata { public Guid ManuscriptID{get;set;}public long Revision{get;set;}public DateTime? SnapshotUtc{get;set;}public DateTime? ChapterAcceptedUtc{get;set;} } +public sealed class WriterChapterVerification +{ + public int ChapterID{get;set;} public Guid? ManuscriptID{get;set;} + public string? CheckpointStatus{get;set;} public string? CheckpointMessage{get;set;} + public DateTime? LastAcceptedUtc{get;set;} public DateTime? ValidatedUtc{get;set;} public bool IsCurrent{get;set;} +} public sealed class WriterWordService(ISqlConnectionFactory factory,IWordCompanionRepository access,IParagraphManuscriptRepository paragraphs,IChapterSyncRepository chapters,NativePresenceStore presence) { private readonly Dictionary<(int User,int Book),Task> acceptedReads=[]; private Task Accepted(int user,int book){if(!acceptedReads.TryGetValue((user,book),out var pending)){pending=paragraphs.Get(user,book);acceptedReads[(user,book)]=pending;}return pending;} private static T? One(IEnumerable rows) where T:class {var candidates=rows.Take(2).ToArray();return candidates.Length==1?candidates[0]:null;} public async Task Metadata(int user,int book,int? chapter){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync("dbo.WriterWord_Status",new{UserID=user,BookID=book,ChapterID=chapter},commandType:CommandType.StoredProcedure);} + public async Task Verification(int user,int book,int chapter,NativeLease lease) + { + using var db=factory.CreateConnection(); + return await db.QuerySingleOrDefaultAsync("dbo.WriterWord_ChapterVerification",new{UserID=user,BookID=book,ChapterID=chapter,ManuscriptID=lease.Position.ManuscriptId,SessionID=lease.Session,WordRevision=lease.Position.Revision},commandType:CommandType.StoredProcedure); + } public async Task Position(int user,NativeLease lease,WriterWordMetadata? metadata){var p=lease.Position;if(p.WordSaved!=true||!p.WordAvailable||!p.CursorStart.HasValue||metadata?.ManuscriptID!=p.ManuscriptId)return null;var position=p.CanChapterSync?await chapters.Position(user,p.BookId,p.ManuscriptId,lease.Session,p.Revision,p.CursorStart.Value):await paragraphs.Position(user,p.BookId,p.ManuscriptId,lease.Session,p.Revision,p.CursorStart.Value);return position?.HasSnapshot==true&&position.Revision==metadata.Revision?position:null;} public async Task Navigate(int user,int book,int chapter,int? scene,Guid instance,Guid session,Guid manuscript,long revision,Guid id,Guid? paragraphId=null,long? acceptedRevision=null,bool validateOnly=false) { diff --git a/PlotLine/Sql/296_WriterChapterVerification.sql b/PlotLine/Sql/296_WriterChapterVerification.sql new file mode 100644 index 00000000..64b57094 --- /dev/null +++ b/PlotLine/Sql/296_WriterChapterVerification.sql @@ -0,0 +1,27 @@ +-- Read-only current-chapter projection. Never refreshes or repairs manuscript evidence. +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.WriterWord_ChapterVerification + @UserID int,@BookID int,@ChapterID int,@ManuscriptID uniqueidentifier,@SessionID uniqueidentifier,@WordRevision bigint +AS +BEGIN + SET NOCOUNT ON; + SELECT ch.ChapterID,m.ManuscriptID,c.Status AS CheckpointStatus,c.Message AS CheckpointMessage, + c.LastSuccessfulSyncUtc AS LastAcceptedUtc,v.ValidatedUtc, + CAST(CASE WHEN v.ValidatedUtc IS NOT NULL AND c.Status='Synchronised' THEN 1 ELSE 0 END AS bit) IsCurrent + FROM dbo.Chapters ch + JOIN dbo.Books b ON b.BookID=ch.BookID AND b.IsArchived=0 + JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 + LEFT JOIN dbo.BookParagraphManuscripts m ON m.BookID=b.BookID AND m.ManuscriptID=@ManuscriptID + OUTER APPLY(SELECT cp.* FROM OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH + (ChapterID int '$.ChapterId',Status nvarchar(80),Message nvarchar(1000),LastSuccessfulSyncUtc datetime2,ContentHash char(64),IdentityHash char(64),MappingHash char(64)) cp WHERE cp.ChapterID=ch.ChapterID) c + OUTER APPLY(SELECT TOP(1) live.ValidatedUtc FROM dbo.BookChapterValidations live + WHERE live.BookID=b.BookID AND live.ChapterID=ch.ChapterID AND live.UserID=@UserID AND live.ManuscriptID=@ManuscriptID + AND live.SessionID=@SessionID AND live.WordRevision=@WordRevision AND live.ExpiresUtc>SYSUTCDATETIME() + AND live.ContentHash=c.ContentHash AND live.IdentityHash=c.IdentityHash AND live.MappingHash=c.MappingHash + ORDER BY live.ValidatedUtc DESC) v + WHERE ch.ChapterID=@ChapterID AND ch.BookID=@BookID AND ch.IsArchived=0; +END; +GO diff --git a/PlotLine/Views/Shared/_Layout.cshtml b/PlotLine/Views/Shared/_Layout.cshtml index dfd57b37..1ceaf6b2 100644 --- a/PlotLine/Views/Shared/_Layout.cshtml +++ b/PlotLine/Views/Shared/_Layout.cshtml @@ -361,6 +361,7 @@ } + diff --git a/PlotLine/wwwroot/js/native-companion-status.js b/PlotLine/wwwroot/js/native-companion-status.js index 4cafe1e7..48619486 100644 --- a/PlotLine/wwwroot/js/native-companion-status.js +++ b/PlotLine/wwwroot/js/native-companion-status.js @@ -42,9 +42,10 @@ else if(syncPending.requestId&&(!observed||observed.paragraphTransfer?.requestId!==syncPending.requestId||observed.paragraphTransfer.state==='failed')){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent='Word transfer ended without an accepted snapshot. Saved paragraphs are unchanged. Check Companion Troubleshooting, then retry.';} else if(observed?.captureRequestId)syncFeedback.textContent='Reading Word: '+Math.max(0,Math.min(100,Number(observed.captureProgress)||0))+'%. Keep Word open until PlotDirector acknowledges the snapshot.'; else if(Date.now()-syncPending.started>120000){window.PlotDirector?.wordNotifications?.forget(syncPending.key);syncPending=null;syncButton.disabled=false;syncFeedback.textContent='No accepted snapshot has been confirmed. Open Manuscript structure and evidence below or Companion Troubleshooting before retrying.';window.PlotDirector?.toast?.error(syncFeedback.textContent);} - }else if(selection?.chapterProgress){const progress=selection.chapterProgress;syncFeedback.textContent=progress.state+' · '+progress.matching+'/'+progress.total+' chapter mappings accepted. '+progress.message;}else if(!selection)syncFeedback.textContent='Open the intended manuscript in Word and select its current connection. Saved scene browsing remains available.'; + }else if(selection?.chapterIssue==='needs_review'){syncFeedback.textContent='Companion reports a chapter-reading failure. Open Companion Settings → Advanced mode → Troubleshooting to inspect the reading diagnostics and recovery options. Synchronise alone does not confirm chapter reading or acceptance.';}else if(['failed','needs-review','cancelled'].includes(selection?.paragraphTransfer?.state)){syncFeedback.textContent=selection.paragraphTransfer.message||'The last Word transfer needs attention. Accepted content is retained; inspect Companion details.';}else if(selection?.chapterProgress){const progress=selection.chapterProgress;syncFeedback.textContent=progress.state+' · '+progress.matching+'/'+progress.total+' chapter mappings accepted. '+progress.message;}else if(!selection)syncFeedback.textContent='Open the intended manuscript in Word and select its current connection. Saved scene browsing remains available.'; else if(selection.wordSaved!==true)syncFeedback.textContent='Save the manuscript in Word before requesting synchronisation.'; else if(selection.canParagraphSync!==true)syncFeedback.textContent='The connected add-in has not advertised paragraph synchronisation. Check the installed Companion and Word connection.'; + else syncFeedback.textContent='No chapter-reading failure is currently reported. Current chapter verification is shown in the ribbon; accepted content is retained.'; } const active=leases.filter(l=>l.active&&l.wordAvailable),available=leases.filter(l=>l.wordAvailable); diff --git a/PlotLine/wwwroot/js/word-chapter-status.js b/PlotLine/wwwroot/js/word-chapter-status.js new file mode 100644 index 00000000..d6cd7398 --- /dev/null +++ b/PlotLine/wwwroot/js/word-chapter-status.js @@ -0,0 +1,29 @@ +// Read-only presentation of selected-chapter evidence, separate from document reading/checking. +(() => { + const pd = window.PlotDirector ||= {}; + pd.wordChapterStatus = (packet, lease, bookId, chapterId) => { + if (!lease) return {label:'Word disconnected', text:'No current Word document connection. Saved accepted text remains available.'}; + if (!chapterId) return {label:'Choose a chapter', text:'Select a chapter to inspect its current Word verification.'}; + if (lease.wordSaved !== true) return {label:lease.wordSaved === false ? 'Save Word to verify' : 'Word state unknown', text:'Current saved Word state is not confirmed. Accepted chapter data is retained.'}; + const entry = packet.chapterVerifications?.find(row => row.instanceId === lease.instanceId && row.sessionId === lease.sessionId && Number(row.bookId) === bookId && Number(row.chapterId) === chapterId && String(row.wordRevision) === String(lease.revision)); + const evidence = entry?.verification; + const identity = evidence?.manuscriptID === lease.manuscriptId && packet.canonical?.manuscriptID === lease.manuscriptId; + let label, text; + if (!evidence) { + label = 'Verification unavailable'; text = 'Current chapter verification has not been returned. Saved accepted text remains available; a synchronisation acknowledgement is not chapter verification.'; + } else if (!identity || !evidence.checkpointStatus) { + label = 'No accepted chapter'; text = 'No accepted checkpoint for this chapter and manuscript identity was found. Inspect Manuscript structure and evidence; do not reimport just to clear a status.'; + } else if (evidence.checkpointStatus === 'Needs review') { + label = 'Chapter needs review'; text = evidence.checkpointMessage || 'This chapter checkpoint requires review in Manuscript structure and evidence. Accepted content is retained.'; + } else if (evidence.isCurrent === true) { + label = 'Chapter verified'; text = 'This chapter has matching accepted evidence for the current Word session and revision.'; + if (evidence.validatedUtc) text += ' Verified: ' + new Date(evidence.validatedUtc).toLocaleString() + '.'; + } else { + label = 'Chapter not verified'; text = 'The saved checkpoint exists, but this chapter has no matching unexpired verification for the current Word session and revision. Inspect the chapter-reading/checking status in Companion; Synchronise alone does not establish chapter acceptance.'; + } + if (identity && evidence.lastAcceptedUtc && new Date(evidence.lastAcceptedUtc).getUTCFullYear() > 1) text += ' Content checkpoint accepted: ' + new Date(evidence.lastAcceptedUtc).toLocaleString() + ' (historical; not a current failure).'; + if (lease.chapterIssue === 'needs_review') text += ' Companion separately reports a chapter-reading failure. Open Companion Settings → Advanced mode → Troubleshooting for diagnostics and reading recovery options.'; + else if (lease.chapterProgress?.state === 'Needs review') text += ' The document chapter-check operation needs review; other chapters may be affected. See Companion details.'; + return {label, text}; + }; +})(); diff --git a/PlotLine/wwwroot/js/word-notifications.js b/PlotLine/wwwroot/js/word-notifications.js index b1b66d7b..031995f9 100644 --- a/PlotLine/wwwroot/js/word-notifications.js +++ b/PlotLine/wwwroot/js/word-notifications.js @@ -18,17 +18,36 @@ } connected = next; } - function syncState(id, state, message, userRequested = false) { + // Account-scoped incident receipts survive page loads, navigation, dismissal and PWA windows. + const journalKey = 'plotdirector.wordIncidents.v1.' + (document.querySelector('[data-toast-host]')?.dataset.toastUser || document.body.dataset.pdUserId || 'anonymous'); + let fallback = new Map(); + function journal() { + try { return new Map(JSON.parse(localStorage.getItem(journalKey) || '[]')); } catch { return fallback; } + } + function remember(id, value) { + const entries = journal(); entries.delete(id); entries.set(id, value); + while (entries.size > 256) entries.delete(entries.keys().next().value); + fallback = entries; + try { localStorage.setItem(journalKey, JSON.stringify([...entries])); } catch { } + } + function syncState(id, state, message, userRequested = false, signature = state + ':' + message) { + const prior = journal().get(id); if (['failed', 'cancelled', 'needs-review'].includes(state)) { - if (failures.get(id)?.state !== state) { - failures.get(id)?.dismiss?.(); - failures.set(id, {state, dismiss: pd.toast[state === 'needs-review' ? 'warning' : 'error'](message)}); - } + if (prior?.active && prior.signature === signature) return; + failures.get(id)?.dismiss?.(); + remember(id, {active:true, signature}); // record before announcing, including if manually dismissed + failures.set(id, {state, dismiss: pd.toast[state === 'needs-review' ? 'warning' : 'error'](message)}); } else if (state === 'accepted') { failures.get(id)?.dismiss?.(); failures.delete(id); + if (prior?.active) remember(id, {...prior, active:false}); if (userRequested) pd.toast.success(message); } } + window.addEventListener('storage', event => { + if (event.key !== journalKey) return; + const entries = journal(); + for (const [id, failure] of failures) if (entries.get(id)?.active === false) { failure.dismiss?.(); failures.delete(id); } + }); pd.wordNotifications = { connection, syncState, forget(id) { manual.delete(id); }, @@ -39,18 +58,29 @@ }); window.addEventListener('plotdirector:office-presence', event => connection('office', event.detail.connected)); window.addEventListener('writer-word-state', event => { + const scope = Number(event.detail?.bookId || document.querySelector('[data-writer-word]')?.dataset.bookId || 0); for (const lease of event.detail?.leases || []) { + if (scope > 0 && Number(lease.bookId) !== scope) continue; const id = key(lease), transfer = lease.paragraphTransfer, progress = lease.chapterProgress; const operation = manual.get(id); const requested = operation && operation.requestId === transfer?.requestId; const accepted = transfer?.kind === 'chapter' || lease.mappingCurrent && Number(lease.snapshotRevision) > operation?.revision; const state = transfer?.state; + const base = [lease.bookId, lease.manuscriptId, lease.revision]; + if (Object.hasOwn(lease, 'chapterIssue')) { + syncState(id + '/reading', lease.chapterIssue === 'needs_review' ? 'needs-review' : 'accepted', + 'Companion reports a chapter-reading failure. Open Companion Settings → Advanced mode → Troubleshooting for reading diagnostics and recovery options. Synchronise alone does not confirm chapter acceptance.', false, JSON.stringify([...base, lease.chapterIssue])); + } if (['failed', 'cancelled', 'needs-review'].includes(state)) { - syncState(id, state, transfer.message || 'Word synchronisation did not complete. Check Companion details; accepted content is retained.'); - } else if (progress?.state === 'Needs review' || lease.chapterIssue === 'needs_review') { - syncState(id, 'needs-review', progress?.message || 'Manuscript checking needs attention in Companion. Accepted content is retained.'); - } else if (state === 'accepted' || progress?.state === 'Synchronised') { - syncState(id, 'accepted', 'Saved manuscript check completed.', requested && state === 'accepted' && accepted); + const text = transfer.message || 'Word synchronisation did not complete. Check Companion details; accepted content is retained.'; + syncState(id + '/transfer', state, text, false, JSON.stringify([...base, transfer.requestId, state, text])); + } else if (state === 'accepted') { + syncState(id + '/transfer', 'accepted', 'Word transfer accepted. Chapter verification is reported separately.', requested && accepted); + } + if (progress?.state === 'Needs review' && lease.chapterIssue !== 'needs_review') { + syncState(id + '/checking', 'needs-review', progress.message || 'The document chapter-check operation needs review in Companion; accepted chapters are retained.', false, JSON.stringify([...base, transfer?.kind === 'chapter' ? transfer.requestId : null, progress.state])); + } else if (progress?.state === 'Synchronised') { + syncState(id + '/checking', 'accepted', ''); } if (requested && (state === 'accepted' && accepted || ['failed', 'cancelled', 'needs-review'].includes(state))) manual.delete(id); } diff --git a/PlotLine/wwwroot/js/writer-word.js b/PlotLine/wwwroot/js/writer-word.js index c672d97a..79753933 100644 --- a/PlotLine/wwwroot/js/writer-word.js +++ b/PlotLine/wwwroot/js/writer-word.js @@ -17,8 +17,10 @@ if(syncPending&&(!current||syncPending.key!==key(current)||Date.now()-syncPendin const identity=current&&data.canonical?.manuscriptID===current.manuscriptId;const observed=current&&verified(current); state.textContent=data.unavailable?'Word Companion status unavailable. Your saved work is retained.':!current?(missingSelection?'Selected Word document is disconnected. Choose another document explicitly.':leases.length>1?'Choose the correct Word manuscript.':(data.leases||[]).some(l=>l.wordAvailable)?'The open Word manuscript is for another book.':'Word Companion is not connected to this manuscript.'):!identity?'Word is connected, but this manuscript has not been verified.':`Manuscript: ${current.documentTitle}`; position.textContent=observed?`Word is showing ${observed.chapterTitle||'the verified chapter'}${observed.sceneId&&observed.sceneTitle?' · '+observed.sceneTitle:''}. ${observed.chapterId!==chapter?(reviewing?'Your review selection is separate.':'Your working focus is separate.'):''}`:current?.wordSaved===false?'Word has unsaved changes. Current positions await verification; no save will be forced.':current?.wordSaved===null?'Word position awaits a fresh observation. Check the intended document in Word; accepted text is retained.':'Word position has not been verified.'; -let status=!identity?'Your latest changes have not yet been confirmed in PlotDirector.':current.chapterProgress?.state==='Needs review'||current.chapterIssue==='needs_review'?'Manuscript checking needs attention in Companion. Accepted content is retained.':current.paragraphTransfer?.state==='failed'?'Manuscript update failed. Accepted content is retained.':current.chapterProgress?.state==='Synchronised'&¤t.wordSaved===true?'The last manuscript check completed. Later edits may still be pending.':current.chapterProgress?.state?`${current.chapterProgress.state}: ${current.chapterProgress.message||'Latest changes are not yet confirmed.'}`:'Latest changes are not yet confirmed. Check synchronisation in Companion.'; -if(data.canonical?.chapterAcceptedUtc)status+=' This chapter last accepted: '+new Date(data.canonical.chapterAcceptedUtc).toLocaleString()+'.';else if(data.canonical?.snapshotUtc)status+=' Accepted snapshot recorded: '+new Date(data.canonical.snapshotUtc).toLocaleString()+'.';freshness.textContent=status;for(const ribbon of document.querySelectorAll('[data-word-ribbon-status]')){ribbon.textContent=!current?'Word disconnected':current.paragraphTransfer?.state==='failed'?'Sync failed':current.chapterProgress?.state||'Awaiting verification';ribbon.title=status;}const warning=document.querySelector('[data-review-word-warning]');if(warning)warning.textContent='Showing accepted text. '+(!current?state.textContent:current.wordSaved===false?'Word has unsaved changes; they are not shown here.':status); +const chapterStatus=window.PlotDirector.wordChapterStatus(data,current,book,chapter); +freshness.textContent=chapterStatus.text;for(const ribbon of document.querySelectorAll('[data-word-ribbon-status]')){ribbon.textContent=chapterStatus.label;ribbon.title=chapterStatus.text;} +const warning=document.querySelector('[data-review-word-warning]');if(warning)warning.textContent='Showing accepted text. '+(!current?state.textContent:current.wordSaved===false?'Word has unsaved changes; they are not shown here.':chapterStatus.text); + sync.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!(current.canChapterSync||current.canParagraphSync); for(const button of [nav,sceneNav,paragraphButton])if(button)button.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!current.canAcknowledgeNavigation; if(identity&&!current.canAcknowledgeNavigation)position.textContent+=' Update the Word add-in and Companion together to enable confirmed navigation.'; @@ -29,7 +31,7 @@ if(targetKey!==availabilityKey||(targetKey&&(availability.chapter===false||scene } if(nav)nav.disabled ||= availability.chapter!==true;if(sceneNav)sceneNav.disabled ||= availability.scene!==true;if(paragraphButton)paragraphButton.disabled ||= availability.paragraph!==true; if(nav)nav.disabled ||= !chapter;if(sceneNav)sceneNav.disabled ||= !scene;if(paragraphButton)paragraphButton.disabled ||= !root.dataset.paragraphId; -for(const button of document.querySelectorAll('[data-ribbon-word]')){const original=button.dataset.ribbonWord==='chapter'?nav:button.dataset.ribbonWord==='scene'?sceneNav:paragraphButton;button.disabled=!original||original.disabled;button.title=button.dataset.navigationTitle+(button.disabled?' Select a verified target, connect and synchronise its Word manuscript.':'');} +for(const button of document.querySelectorAll('[data-ribbon-word]')){const original=button.dataset.ribbonWord==='chapter'?nav:button.dataset.ribbonWord==='scene'?sceneNav:paragraphButton;button.disabled=!original||original.disabled;button.title=button.dataset.navigationTitle+(button.disabled?' Select a verified target and connect its saved Word manuscript; inspect Companion Troubleshooting if chapter reading failed.':'');} const params=new URLSearchParams(location.search),origin=current&¶ms.get('wordInstanceId')===current.instanceId&¶ms.get('wordSessionId')===current.sessionId; adopt.hidden=reviewing||!(origin&&observed&&observed.chapterId!==chapter);if(!adopt.hidden){adopt.querySelector('[name=ChapterID]').value=observed.chapterId;adopt.querySelector('[name=SceneID]').value=observed.sceneId||'';adopt.querySelector('[data-word-origin]').textContent='Opened from verified Word chapter '+(observed.chapterTitle||'in this manuscript')+'. Your saved objective is unchanged.';} } @@ -81,6 +83,6 @@ async function navigate(toScene,toParagraph=false){ sync.addEventListener('click',async()=>{if(sync.disabled||!current)return;const selected={...current};syncPending={key:key(selected),started:Date.now()};sync.disabled=true;const body=new URLSearchParams({bookId:String(book),instanceId:selected.instanceId,sessionId:selected.sessionId,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});try{const response=await fetch('/manuscript/paragraphs/snapshot',{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});const result=await response.json();if(!response.ok||response.redirected)throw Error(result.message||'Manuscript check unavailable.');if(syncPending)syncPending.requestId=result.requestId;window.PlotDirector?.wordNotifications?.requested(selected,result.requestId);message.textContent='Saved manuscript check requested; acceptance has not yet been confirmed. '+(result.message||'');}catch(error){syncPending=null;message.textContent=error.message||'Could not request manuscript check.';window.PlotDirector?.toast?.error(message.textContent);}finally{requestStatus();}}); paragraphButton?.addEventListener('click',()=>void navigate(false,true));window.addEventListener('review-reference-changed',()=>{if(packet)render(packet);}); nav?.addEventListener('click',()=>void navigate(false));sceneNav?.addEventListener('click',()=>void navigate(true)); -root.querySelector('[data-word-check]').addEventListener('click',()=>{if(checkBusy)return;checkBusy=true;availabilityKey='';availability={};message.textContent='Checking reported connection and accepted updates. Use Synchronise in Companion to request a bounded manuscript check.';requestStatus();setTimeout(()=>checkBusy=false,2000);}); +root.querySelector('[data-word-check]').addEventListener('click',()=>{if(checkBusy)return;checkBusy=true;availabilityKey='';availability={};message.textContent='Checking the reported connection and current chapter evidence. For a reading failure, inspect Companion Troubleshooting; synchronisation acknowledgement alone does not confirm verification.';requestStatus();setTimeout(()=>checkBusy=false,2000);}); window.addEventListener('writer-word-state',event=>render(event.detail));window.addEventListener('native-companion-presence',event=>{if(!event.detail.length&&packet&&!packet.leases?.length&&event.detail.connectionState==='Connected')state.textContent='Companion is connected; open and verify this manuscript in Word.';});window.addEventListener('pagehide',()=>abort?.abort());const initial=document.querySelector('#native-companion-status')?.writerWordState;if(initial)render(initial); })();