From d55206d8c328fb025f5215ca66e4fe06956807bb Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Mon, 23 Nov 2026 14:07:59 +0000 Subject: [PATCH] Harden focus recovery and canonical chapter boundaries --- .../Unified-Manuscript-Focus-20261123.md | 10 +-- .../Browser/shared-manuscript-focus.cjs | 3 +- PlotLine.Tests/SharedFocusDatabaseTests.cs | 14 +++- .../SharedFocusNativeDeliveryTests.cs | 10 ++- PlotLine/Services/SharedManuscriptFocus.cs | 2 +- .../Sql/317_SharedFocusChapterBoundaries.sql | 83 +++++++++++++++++++ .../wwwroot/js/native-companion-status.js | 1 + .../wwwroot/js/shared-manuscript-focus.js | 6 +- PlotLine/wwwroot/js/writer-word.js | 2 +- 9 files changed, 115 insertions(+), 16 deletions(-) create mode 100644 PlotLine/Sql/317_SharedFocusChapterBoundaries.sql diff --git a/Docs/Writer/Unified-Manuscript-Focus-20261123.md b/Docs/Writer/Unified-Manuscript-Focus-20261123.md index 6cba58da..e9173a14 100644 --- a/Docs/Writer/Unified-Manuscript-Focus-20261123.md +++ b/Docs/Writer/Unified-Manuscript-Focus-20261123.md @@ -12,11 +12,11 @@ The implementation extends these paths. It does not introduce another hub, Conte ## Server contract -Forward-only migrations **314–316** extend the existing `NarrativeFocus` row with canonical manuscript/paragraph and originating-window IDs; add a per-origin sequence replay ledger; replace implicit objective seeding and read-time redirection; and resolve Word positions from exact-session verified chapter evidence. Backup `/var/opt/mssql/backup/shared-manuscript-focus-20261123T125506Z.bak` completed with COPY_ONLY/CHECKSUM and passed VERIFYONLY before migration. VERIFYONLY is not a restore test. +Forward-only migrations **314–317** extend the existing `NarrativeFocus` row with canonical manuscript/paragraph and originating-window IDs; add a per-origin sequence replay ledger; replace implicit objective seeding and read-time redirection; and resolve Word positions from exact-session verified chapter evidence. Backup `/var/opt/mssql/backup/shared-manuscript-focus-20261123T125506Z.bak` completed with COPY_ONLY/CHECKSUM and passed VERIFYONLY before the initial migrations. The chapter-only/empty-chapter boundary correction in 317 used a further verified backup, `/var/opt/mssql/backup/shared-focus-boundary-20261123T134529Z.bak`. VERIFYONLY is not a restore test. `GET /NarrativeFocus/Shared?projectID=…&bookID=…` retrieves authoritative focus. Antiforgery-protected POSTs to `/NarrativeFocus/Shared/Publish`, `/Resolve` and `/Validate` accept existing identifiers. `Resolve` performs held local navigation; `Validate` checks a retained reference; neither publishes. Every operation verifies active authenticated access, project/book membership, canonical manuscript identity and chapter/scene/paragraph compatibility in stored procedures accessed through Dapper. Navigation remains available to read-only subscription accounts. -The packet contains `ProjectID`, `BookID`, `ManuscriptID`, `ChapterID`, optional `SceneID`/`ParagraphID`, `OriginWindowID`, `Version`, `IsValid` and `Changed`. It contains no prose, Word offsets or contextual datasets. The server locks the existing focus row and assigns increasing revisions atomically. Different clients are ordered by accepted server revisions, without client timestamps. Duplicate/older per-window sequences and unchanged effective targets do not create another revision. A stale stored reference is returned as invalid, without silently moving it. +The packet contains `ProjectID`, `BookID`, `ManuscriptID`, `ChapterID`, optional `SceneID`/`ParagraphID`, `OriginWindowID`, `Version`, `IsValid` and `Changed`. It contains no prose, Word offsets or contextual datasets. The server locks the existing focus row and assigns increasing revisions atomically. Different clients are ordered by accepted server revisions, without client timestamps. Duplicate/older per-window sequences and unchanged effective targets do not create another revision. A stale stored reference is returned as invalid, without silently moving it. Clients process validity metadata even when the focus revision is unchanged, so Release never reuses a cached valid flag for a now-invalid shared point. `ManuscriptFocusChanged` uses the existing authenticated `NativeCompanionPresenceHub.UserGroup`. `ManuscriptFocusDelivery` reports unavailable Word mapping without blocking other clients. Browser clients scope-filter messages, reject obsolete/duplicate revisions, serialize rapid local intent and recover on connect/reconnect. Ordinary GETs, refreshes, passive observations and received navigation do not publish. Existing explicit browser navigation delegates to the coordinator; server GET hooks no longer write focus. @@ -40,8 +40,8 @@ Explicit Open in Word controls are retained, including paragraph navigation: phy - Solution build: zero warnings/errors; full executable regression harness: **786 passing checks**. - Native portable regression harness: **320 passing checks**, including the dedicated per-window Hold/revision cases. These exercise managed production logic and IPC, not Word COM. -- Development rollback-only SQL tests cover no initial publication, canonical paragraph resolution, monotonic revisions, unchanged-target suppression, replay rejection, held resolution without mutation, canonical cross-chapter stepping, invalid references, verified Word offsets, exact-session isolation and authorisation. The updated historical six-phase SQL regression also passes with no implicit seed/redirection. -- Sixteen real concurrent SQL connections verify contiguous unique accepted revisions and a final durable read equal to the highest revision. Real coordinator/SQL/native-queue integration also verifies Word-only publication, browser-to-Word chapter crossing, passive suppression, Hold/release, failed receipts, unsaved documents and exact-session isolation through a recording transport. +- Development rollback-only SQL tests cover no initial publication, canonical paragraph resolution, monotonic revisions, unchanged-target suppression, replay rejection, held resolution without mutation, canonical cross-chapter stepping, chapter-only and empty-chapter boundaries, endpoint paragraph preservation, invalid references, verified Word offsets, exact-session isolation and authorisation. The updated historical six-phase SQL regression also passes with no implicit seed/redirection. +- Sixteen real concurrent SQL connections verify contiguous unique accepted revisions and a final durable read equal to the highest revision. Real coordinator/SQL/native-queue integration also verifies Word-only publication, browser-to-Word chapter crossing, passive suppression, Hold/release, failed receipts, unsaved documents, delivery renewal after a saved Word/snapshot revision, and exact-session isolation through a recording transport. - Real authenticated Chromium and installed standalone Chromium PWA tests use the actual controllers, SQL and SignalR with a synthetic isolated project/manuscript. They cover Context alone; Review/Context without Word; local scrolling; exact paragraphs and chapter crossing; independent Hold; local held Review navigation; refresh and release without publication; rapid and obsolete ordering; new/duplicated-window isolation; reconnect; responsive widths; hidden tabs; and relationship edits in an earlier scene refreshing both held panes. The refreshed later-scene graph is checked for the new note, not just a refresh request. - Actual loopback server restart passed: durable focus recovered, SignalR reconnected, and the held window detected an offline structural change without redirecting. Browser structural archival acceptance passed. Final public Development smoke results are recorded in deployment evidence. Browser fixtures are isolated and archived after testing; no real manuscript text or relationships are edited. @@ -59,6 +59,6 @@ This Linux host cannot compile/load the Office/VSTO project or run physical Word 6. Close each client in turn, including Word unexpectedly, and verify remaining pairs still navigate. Reconnect/restart the agent/service, rapidly alternate publications, and replay/delay notifications; verify newest accepted focus wins without an echo. Test saved/unsaved and stale/expired mapping transitions and independent manuscripts/accounts. 7. Repeat the earlier-scene relationship edit while a later-scene diagram is Held; verify data changes without movement. Archive a disposable held scene and verify explicit invalid-reference recovery. Confirm existing editing, synchronization, review tools, launch actions and ribbon layout. -Older native installations do not advertise the new capability and retain their existing behavior. Precise native following requires fresh verified saved chapter positions; legacy paragraph-only offsets are not guessed. Historical Office.js hosting requires separate host-specific implementation/qualification before shared-focus support can be claimed there. +Older native installations do not advertise the new capability. They retain editing, content synchronisation and explicit Word navigation, but must be updated before participating in shared focus; passive legacy cursor-following is replaced rather than promoted into deliberate focus. Existing connection details and Review status make that upgrade requirement explicit. Precise native following requires fresh verified saved chapter positions; legacy paragraph-only offsets are not guessed. Historical Office.js hosting requires separate host-specific implementation/qualification before shared-focus support can be claimed there. Deployment evidence: [Unified-Manuscript-Focus-Deployment-20261123.md](Unified-Manuscript-Focus-Deployment-20261123.md). diff --git a/PlotLine.Tests/Browser/shared-manuscript-focus.cjs b/PlotLine.Tests/Browser/shared-manuscript-focus.cjs index 2e6dd4a5..99e860a0 100644 --- a/PlotLine.Tests/Browser/shared-manuscript-focus.cjs +++ b/PlotLine.Tests/Browser/shared-manuscript-focus.cjs @@ -38,11 +38,12 @@ const base=process.env.PD_SHARED_FOCUS_URL||'http://127.0.0.1:5258'; await a.waitForFunction(()=>window.PlotDirectorSharedFocus.held===true);await a.waitForTimeout(1800);assert(refreshed.has('/Writing/Context/Tabs/relationships')&&refreshed.has('/Writing/Context/Tabs/characters'),'both affected visible panes refreshed');assert.equal(graphAfter?.links?.find(l=>l.id===s.relationship)?.notes,changeNote,'held later-scene graph contains the new earlier-scene note');await scene(a,s.scene2);assert.equal((await current(a)).sceneID,s.scene3); step='reconnect catches current shared reference';await b.evaluate(async()=>{const c=document.querySelector('[data-context-workspace]').contextController.connection;await c.stop();await c.start();await PlotDirectorSharedFocus.refresh(true);});await scene(b,s.scene3); step='new window does not inherit Hold';const fresh=await surface(contextURL);await ready(fresh);await scene(fresh,s.scene3);assert.equal(await fresh.evaluate(()=>PlotDirectorSharedFocus.held),false); + if(s.emptyChapter){step='chapter-only and empty-chapter toolbar boundaries';const command=async name=>{const menu=review.locator('.pd-ribbon-panel:not([hidden]) .pd-ribbon-focus details[data-compact=true]');if(await menu.count()&&!await menu.evaluate(n=>n.open))await menu.locator('summary').click();await review.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus='+name+']').click();await review.waitForFunction(()=>document.querySelector('.pd-ribbon-panel:not([hidden]) [data-global-focus=previous]')?.disabled===false);};await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.chapter2}),s);await review.waitForFunction(s=>PlotDirectorSharedFocus.local.chapterID===s.chapter2&&!PlotDirectorSharedFocus.local.sceneID,s);await command('next');await scene(b,s.scene3);await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.emptyChapter}),s);await review.waitForFunction(s=>document.querySelector('.manuscript-reader').dataset.chapterId===String(s.emptyChapter),s);await command('next');await scene(b,s.scene3);await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.emptyChapter}),s);await review.waitForFunction(s=>document.querySelector('.manuscript-reader').dataset.chapterId===String(s.emptyChapter),s);await command('previous');await scene(b,s.scene2);await scene(a,s.scene2);await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.chapter2,sceneID:s.scene3}),s);await scene(b,s.scene3);console.log('PASS actual Review toolbar: chapter-only Next stays in its own chapter; empty-chapter Previous/Next reaches the canonical neighbor without moving held Context.');} step='duplicated session state cannot inherit Hold';const clone=await c.newPage();const storage=await a.evaluate(()=>Object.fromEntries(Object.entries(sessionStorage).filter(([k])=>k.startsWith('pd.shared-focus')||k==='plotdirector.context.window.v1')));await clone.addInitScript(values=>{for(const[k,v]of Object.entries(values))sessionStorage.setItem(k,v);},storage);await clone.goto(contextURL);await ready(clone);await clone.waitForFunction(id=>!PlotDirectorSharedFocus.held&&PlotDirectorSharedFocus.windowID!==id,await a.evaluate(()=>PlotDirectorSharedFocus.windowID));await scene(clone,s.scene3); step='hidden affected tab is fetched when activated';const beforeHidden=invalidated;await a.selectOption('[data-context-pane="1"] [data-context-tab]','overview');await a.waitForTimeout(600);assert(invalidated>beforeHidden);await scene(a,s.scene2); step='responsive Hold control';for(const width of[1500,760,390]){await a.setViewportSize({width,height:900});assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),'Context overflow at '+width);}await a.setViewportSize({width:1500,height:1000}); if(process.argv.includes('--restart')){step='actual server restart recovery';const revision=(await current(b)).version;await b.evaluate(()=>{const root=document.querySelector('[data-context-workspace]');root.contextController.connection.onreconnected(()=>window.__sharedFocusRestartRecovered=true);root.addEventListener('context-connection-ready',()=>window.__sharedFocusRestartRecovered=true,{once:true});});fs.writeFileSync('/tmp/shared-focus-restart-ready','ready');await b.waitForFunction(()=>window.__sharedFocusRestartRecovered,null,{timeout:55000});await scene(b,s.scene3);await a.waitForFunction(()=>[...document.querySelectorAll('[data-shared-focus-status]')].some(n=>/no longer valid/.test(n.textContent)));await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);assert.equal((await current(b)).version,revision);await a.selectOption('[data-context-scene]',String(s.scene1));await scene(a,s.scene1);assert.equal((await current(a)).version,revision);console.log('PASS actual loopback server restart: latest focus persisted, SignalR reconnected, held scene retained and an offline structural change was validated without redirect.');} - if(process.argv.includes('--structure')){step='structural archive retains held reference';const result=await edit.evaluate(async s=>{const token=document.querySelector('[name=__RequestVerificationToken]').value;const response=await fetch('/Scenes/Archive',{method:'POST',body:new URLSearchParams({id:s.scene2,chapterId:s.chapter1,__RequestVerificationToken:token})});return response.status;},s);assert.equal(result,200);await a.waitForFunction(()=>[...document.querySelectorAll('[data-shared-focus-status]')].some(n=>/no longer valid/.test(n.textContent)));await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);await a.selectOption('[data-context-scene]',String(s.scene1));await scene(a,s.scene1);assert.equal((await current(a)).sceneID,s.scene3);} + if(process.argv.includes('--structure')){step='structural archive retains held reference';const result=await edit.evaluate(async s=>{const token=document.querySelector('[name=__RequestVerificationToken]').value;const response=await fetch('/Scenes/Archive',{method:'POST',body:new URLSearchParams({id:s.scene2,chapterId:s.chapter1,__RequestVerificationToken:token})});return response.status;},s);assert.equal(result,200);await a.waitForFunction(()=>[...document.querySelectorAll('[data-shared-focus-status]')].some(n=>/no longer valid/.test(n.textContent)));await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);await a.selectOption('[data-context-scene]',String(s.scene1));await scene(a,s.scene1);assert.equal((await current(a)).sceneID,s.scene3);const version=(await current(a)).version;const archived=await edit.evaluate(async s=>{const token=document.querySelector('[name=__RequestVerificationToken]').value;return(await fetch('/Scenes/Archive',{method:'POST',body:new URLSearchParams({id:s.scene3,chapterId:s.chapter2,__RequestVerificationToken:token})})).status;},s);assert.equal(archived,200);await a.evaluate(()=>PlotDirectorSharedFocus.refresh());assert.equal((await current(a)).isValid,false);await a.evaluate(()=>{const conn=document.querySelector('[data-context-workspace]').contextController.connection;const handlers=Object.values(conn).find(v=>Array.isArray(v?.manuscriptfocuschanged))?.manuscriptfocuschanged;for(const handler of handlers||[])handler({...PlotDirectorSharedFocus.shared,isValid:true});});assert.equal((await current(a)).isValid,false,'duplicate focus packets cannot undo authoritative same-revision invalidity');await a.click('[data-shared-focus-hold]');await a.waitForFunction(()=>!PlotDirectorSharedFocus.held);await scene(a,s.scene1);assert.equal((await current(a)).version,version);assert.equal((await current(a)).isValid,false,'same-revision invalidity must replace cached validity before Release');await b.selectOption('[data-context-scene]',String(s.scene1));await b.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene1&&PlotDirectorSharedFocus.shared.isValid,s);console.log('PASS structural safety: local invalid reference retained; Release rejects an invalid shared point even at the same revision, retains valid local position, and does not publish.');} assert.equal(wordCommands,0,'shared navigation never depends on or automatically invokes Word navigation');for(const p of[a,b,fresh,clone])assert.equal(sockets.get(p).filter(s=>!s.closed&&s.url.includes('/hubs/native-companion')).length,1,'one existing SignalR connection per Context window');assert.deepEqual(errors,[]);console.log('PASS real authenticated browser + SQL + SignalR: Context alone, Review↔Context without Word, scroll local, exact paragraphs/chapter crossing, per-window Hold, refresh/release, rapid/obsolete ordering, cross-scene relationship save refreshes both held panes, reconnect, new/duplicated-window isolation, Previous/Go without Word, hidden tabs and responsive Hold.'); }catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await persistent?.close();await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});} })(); diff --git a/PlotLine.Tests/SharedFocusDatabaseTests.cs b/PlotLine.Tests/SharedFocusDatabaseTests.cs index 94b70003..2eea1d4f 100644 --- a/PlotLine.Tests/SharedFocusDatabaseTests.cs +++ b/PlotLine.Tests/SharedFocusDatabaseTests.cs @@ -8,7 +8,7 @@ using PlotLine.Services.Manuscript; using PlotDirector.Companion.Protocol.Manuscript; internal static class SharedFocusDatabaseTests { - internal sealed record Fixture(int user,int project,int book,int chapter1,int chapter2,int scene1,int scene2,int scene3,Guid paragraph1,Guid paragraph2,Guid paragraph3,Guid manuscript,Guid session,int character1,int character2,int relationship,int relationshipEvent); + internal sealed record Fixture(int user,int project,int book,int chapter1,int chapter2,int scene1,int scene2,int scene3,Guid paragraph1,Guid paragraph2,Guid paragraph3,Guid manuscript,Guid session,int character1,int character2,int relationship,int relationshipEvent,int emptyChapter=0); public static async Task Concurrent(bool cleanup=false) { var fixture=JsonSerializer.Deserialize(File.ReadAllText("/tmp/shared-focus-browser-scope.json"))!; @@ -45,6 +45,7 @@ internal static class SharedFocusDatabaseTests INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@c2,1,N'Focus fixture next chapter',10,@time,@confidence,@revision);DECLARE @s3 int=SCOPE_IDENTITY(); SELECT @book Book,@c1 C1,@c2 C2,@s1 S1,@s2 S2,@s3 S3; """,new{project},tx); + int emptyChapter=await db.QuerySingleAsync("DECLARE @revision int=(SELECT RevisionStatusID FROM dbo.Chapters WHERE ChapterID=@chapter);INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,100,N'Focus fixture empty boundary',15,@revision);SELECT CAST(SCOPE_IDENTITY() AS int);",new{book=ids.Book,chapter=ids.C1},tx); Guid manuscript=Guid.NewGuid(),session=Guid.NewGuid(),p1=Guid.NewGuid(),p2=Guid.NewGuid(),p3=Guid.NewGuid(),sk1=Guid.NewGuid(),sk2=Guid.NewGuid(),sk3=Guid.NewGuid();string hash=new('A',64); var state=new ParagraphManuscript{BookId=ids.Book,ProjectId=project,ManuscriptId=manuscript,SessionId=session,WordRevision=1,Revision=1,LastRequestId=Guid.NewGuid(),UpdatedUtc=DateTime.UtcNow,Paragraphs=[new(){ChapterId=ids.C1,SceneId=sk1,Story=true,PositionVerified=true,Occurrence=new(){Id=p1,Start=10,End=20,Text="Isolated focus paragraph one."}},new(){ChapterId=ids.C1,SceneId=sk2,Story=true,PositionVerified=true,Occurrence=new(){Id=p2,Start=20,End=30,Text="Isolated focus paragraph two."}},new(){ChapterId=ids.C2,SceneId=sk3,Story=true,PositionVerified=true,Occurrence=new(){Id=p3,Start=40,End=50,Text="Isolated focus paragraph three."}}],Scenes=[new(){Id=sk1,CanonicalId=ids.S1,ChapterId=ids.C1},new(){Id=sk2,CanonicalId=ids.S2,ChapterId=ids.C1},new(){Id=sk3,CanonicalId=ids.S3,ChapterId=ids.C2}],ChapterCheckpoints=[new(){ChapterId=ids.C1,ContentHash=hash,IdentityHash=hash,MappingHash=hash},new(){ChapterId=ids.C2,ContentHash=hash,IdentityHash=hash,MappingHash=hash}]}; await db.ExecuteAsync("INSERT dbo.BookParagraphManuscripts(BookID,ManuscriptID,Revision,RequestID,Payload) VALUES(@book,@manuscript,1,NEWID(),@payload)",new{book=ids.Book,manuscript,payload=JsonSerializer.Serialize(state)},tx); @@ -60,8 +61,8 @@ internal static class SharedFocusDatabaseTests DECLARE @role int=(SELECT TOP(1) CharacterRoleInSceneTypeID FROM dbo.CharacterRoleInSceneTypes ORDER BY CharacterRoleInSceneTypeID),@presence int=(SELECT TOP(1) PresenceTypeID FROM dbo.PresenceTypes WHERE TypeName=N'Present'); INSERT dbo.SceneCharacters(SceneID,CharacterID,RoleInSceneTypeID,PresenceTypeID) SELECT s.ID,c.ID,@role,@presence FROM (VALUES(@s1),(@s2),(@s3))s(ID) CROSS JOIN(VALUES(@ca),(@cb))c(ID); """,new{s1=ids.S1,s2=ids.S2,s3=ids.S3,ca,cb},tx); - var fixture=new Fixture(user,project,ids.Book,ids.C1,ids.C2,ids.S1,ids.S2,ids.S3,p1,p2,p3,manuscript,session,ca,cb,rel,ev); - if(persist){tx.Commit();File.WriteAllText("/tmp/shared-focus-browser-scope.json",JsonSerializer.Serialize(fixture));Console.WriteLine("PASS isolated shared-focus browser fixture prepared; no real manuscript used.");return;} + var fixture=new Fixture(user,project,ids.Book,ids.C1,ids.C2,ids.S1,ids.S2,ids.S3,p1,p2,p3,manuscript,session,ca,cb,rel,ev,emptyChapter); + if(persist){await db.ExecuteAsync("DECLARE @revision int,@time int,@confidence int;SELECT @revision=RevisionStatusID,@time=TimeModeID,@confidence=TimeConfidenceID FROM dbo.Scenes WHERE SceneID=@scene;INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@chapter,2,N'Focus fixture archive guard',20,@time,@confidence,@revision);",new{scene=ids.S3,chapter=ids.C2},tx);tx.Commit();File.WriteAllText("/tmp/shared-focus-browser-scope.json",JsonSerializer.Serialize(fixture));Console.WriteLine("PASS isolated shared-focus browser fixture prepared; no real manuscript used.");return;} void Check(bool condition,string name){if(!condition)throw new Exception(name);Console.WriteLine("PASS shared focus SQL: "+name);} async Task Run(string action,Guid? window=null,long sequence=0,int? chapter=null,int? scene=null,Guid? paragraph=null,int direction=0)=>await db.QuerySingleAsync("dbo.NarrativeFocus_Coordinate",new{Action=action,UserID=user,ProjectID=project,BookID=ids.Book,WindowID=window,Sequence=sequence,ChapterID=chapter,SceneID=scene,ParagraphID=paragraph,Direction=direction},tx,commandType:CommandType.StoredProcedure); var a=Guid.NewGuid();var b=Guid.NewGuid();var empty=await Run("read");Check(empty.Version==0&&!empty.IsValid,"new clients do not manufacture or publish initial focus"); @@ -70,8 +71,13 @@ internal static class SharedFocusDatabaseTests var second=await Run("publish",b,1,paragraph:p2);Check(second.Version==2&&second.ParagraphID==p2&&second.SceneID==ids.S2,"accepted paragraph resolves canonical chapter and scene without text in the packet"); var duplicate=await Run("publish",a,1,scene:ids.S1);Check(duplicate.Version==2&&duplicate.ParagraphID==p2&&!duplicate.Changed,"replayed older client sequence cannot overwrite a newer window"); var held=await Run("resolve",a,3,scene:ids.S3);var still=await Run("read");Check(held.ChapterID==ids.C2&&still.Version==2&&still.ParagraphID==p2,"held local navigation validates without changing shared state"); + Check((await Run("resolve",chapter:ids.C2,direction:1)).SceneID==ids.S3,"chapter-only Next remains within its own nonempty chapter"); + Check((await Run("resolve",chapter:ids.C1,direction:-1)).SceneID==ids.S2,"chapter-only Previous selects the last scene of its chapter"); + Check((await Run("resolve",chapter:emptyChapter,direction:1)).SceneID==ids.S3&&(await Run("resolve",chapter:emptyChapter,direction:-1)).SceneID==ids.S2,"empty chapter boundaries use canonical neighboring chapters rather than book endpoints"); + Check((await Run("resolve",chapter:ids.C2,scene:ids.S3,paragraph:p3,direction:1)).ParagraphID==p3,"stepping beyond the final scene preserves the precise held paragraph"); var next=await Run("publish",b,2,direction:1);Check(next.SceneID==ids.S3&&next.Version==3,"scene stepping uses canonical sort order across chapter boundaries"); - await db.ExecuteAsync("UPDATE dbo.Scenes SET IsArchived=1 WHERE SceneID=@id",new{id=ids.S3},tx);var invalid=await Run("validate",scene:ids.S3,chapter:ids.C2);Check(!invalid.IsValid&&(await Run("read")).Version==3,"structural invalidation is explicit and never redirects a held reference"); + var precise=await Run("publish",b,3,paragraph:p3);var endpoint=await Run("publish",b,4,direction:1);Check(!endpoint.Changed&&endpoint.Version==precise.Version&&endpoint.ParagraphID==p3,"publishing Next at the final scene does not drop paragraph precision or increment revision"); + await db.ExecuteAsync("UPDATE dbo.Scenes SET IsArchived=1 WHERE SceneID=@id",new{id=ids.S3},tx);var invalid=await Run("validate",scene:ids.S3,chapter:ids.C2);Check(!invalid.IsValid&&(await Run("read")).Version==precise.Version,"structural invalidation is explicit and never redirects a held reference"); var mapped=await db.QuerySingleAsync("dbo.NarrativeFocus_WordPosition",new{Action="position",UserID=user,BookID=ids.Book,ManuscriptID=manuscript,SessionID=session,WordRevision=1,Cursor=12},tx,commandType:CommandType.StoredProcedure);Check(mapped.ParagraphID==p1,"native deliberate selection maps only through exact verified live evidence"); var missing=await db.QueryAsync("dbo.NarrativeFocus_WordPosition",new{Action="target",UserID=user,BookID=ids.Book,ManuscriptID=manuscript,SessionID=Guid.NewGuid(),WordRevision=1,ParagraphID=p1},tx,commandType:CommandType.StoredProcedure);Check(!missing.Any(),"a different Word session never receives another session's offsets"); var bad=await Run("validate",chapter:ids.C2,paragraph:p1);Check(!bad.IsValid,"incompatible paragraph/chapter references are rejected"); diff --git a/PlotLine.Tests/SharedFocusNativeDeliveryTests.cs b/PlotLine.Tests/SharedFocusNativeDeliveryTests.cs index 9785438b..7d13b439 100644 --- a/PlotLine.Tests/SharedFocusNativeDeliveryTests.cs +++ b/PlotLine.Tests/SharedFocusNativeDeliveryTests.cs @@ -1,4 +1,5 @@ using System.Data; +using Dapper; using Microsoft.AspNetCore.SignalR; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging.Abstractions; @@ -23,7 +24,7 @@ internal static class SharedFocusNativeDeliveryTests var store=new NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var window=Guid.NewGuid();var mode=Guid.NewGuid(); var service=new SharedManuscriptFocus(new Factory(value),hub,store,NullLogger.Instance); NativePresence Position(long sequence,bool held=false,bool saved=true)=>new(){BookId=f.book,ManuscriptId=f.manuscript,Revision=1,Sequence=sequence,WordSaved=saved,WordAvailable=true,WordRunning=true,CanAcknowledgeNavigation=true,CanSharedFocus=true,FocusHeld=held,AnyFollowingWindows=!held,FocusWindowID=window,FocusModeRequest=mode,CursorStart=12,DocumentTitle="Synthetic shared-focus fixture"}; - NativeLease Put(NativePresence position){Check(store.Put(f.user,"synthetic-focus-grant",DateTimeOffset.UtcNow.AddMinutes(10),instance,f.session,position),"exact native lease accepted");return store.Read(f.user,f.book).Single();} + NativeLease Put(NativePresence position){Check(store.Put(f.user,"synthetic-focus-grant",DateTimeOffset.UtcNow.AddMinutes(10),instance,f.session,position),"exact native lease accepted");return store.Read(f.user,f.book).Single(l=>l.Instance==instance&&l.Session==f.session);} AdapterCommand? Take()=>store.TakeNavigation(f.user,"synthetic-focus-grant",instance,f.session); var first=Position(1);first.DeliberateFocusSequence=1; await service.NativeObservation(f.user,f.project,Put(first),false); @@ -48,5 +49,12 @@ internal static class SharedFocusNativeDeliveryTests Check(store.Put(f.user,"synthetic-other-session",DateTimeOffset.UtcNow.AddMinutes(10),otherInstance,otherSession,other),"independent native session accepted"); var unmapped=await service.NativeObservation(f.user,f.project,store.Read(f.user,f.book).Single(l=>l.Instance==otherInstance),true); Check(unmapped=="word-unmapped"&&store.TakeNavigation(f.user,"synthetic-other-session",otherInstance,otherSession)==null,"unmapped sessions receive an explicit limitation and never another session's offsets"); + await using var validation=new SqlConnection(value);await validation.OpenAsync(); + try{ + await validation.ExecuteAsync("UPDATE dbo.BookChapterValidations SET WordRevision=2 WHERE BookID=@book AND UserID=@user AND SessionID=@session",new{book=f.book,user=f.user,session=f.session}); + var saved=Position(9);saved.Revision=2;saved.ParagraphRevision=2; + await service.NativeObservation(f.user,f.project,Put(saved),true);var renewed=Take(); + Check(renewed?.Revision==2&&renewed.Id!=command!.Id&&renewed.FocusVersion==next.Version,"saved Word revision and accepted snapshot receive a fresh delivery identity without manufacturing shared focus"); + }finally{await validation.ExecuteAsync("UPDATE dbo.BookChapterValidations SET WordRevision=1 WHERE BookID=@book AND UserID=@user AND SessionID=@session AND WordRevision=2",new{book=f.book,user=f.user,session=f.session});} } } diff --git a/PlotLine/Services/SharedManuscriptFocus.cs b/PlotLine/Services/SharedManuscriptFocus.cs index b661f8ab..f1e202f6 100644 --- a/PlotLine/Services/SharedManuscriptFocus.cs +++ b/PlotLine/Services/SharedManuscriptFocus.cs @@ -45,7 +45,7 @@ public sealed class SharedManuscriptFocus(ISqlConnectionFactory factory,IHubCont { var p=lease.Position;if(!p.CanSharedFocus)return "unsupported";if(!p.AnyFollowingWindows)return "held";if(p.WordSaved!=true)return "save-required";if(focus.ManuscriptID!=p.ManuscriptId)return "word-unmapped"; var target=await WordPosition(user,lease,"target",focus);if(target==null){await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync("ManuscriptFocusDelivery",new{focus.BookID,focus.Version,state="word-unmapped"});return "word-unmapped";} - var bytes=SHA256.HashData(Encoding.UTF8.GetBytes($"{user}/{focus.BookID}/{lease.Instance}/{lease.Session}/{p.FocusWindowID}/{p.FocusModeRequest}/{focus.Version}"));var command=new Guid(bytes.AsSpan(0,16)); + var bytes=SHA256.HashData(Encoding.UTF8.GetBytes($"{user}/{focus.BookID}/{lease.Instance}/{lease.Session}/{p.ManuscriptId}/{p.Revision}/{p.ParagraphRevision}/{p.FocusWindowID}/{p.FocusModeRequest}/{focus.Version}"));var command=new Guid(bytes.AsSpan(0,16)); var known=native.NavigationState(user,focus.BookID,lease.Instance,lease.Session,command,p.ManuscriptId,p.Revision);if(known is "failed" or "timed-out" or "invalidated")return "word-busy"; var sent=native.Navigate(user,focus.BookID,lease.Instance,lease.Session,p.ManuscriptId,p.Revision,target.StartPosition,true,command,true,backgroundFocus:true,focusVersion:focus.Version,focusOriginWindowID:focus.OriginWindowID??Guid.Empty);return sent?"following":"word-busy"; } diff --git a/PlotLine/Sql/317_SharedFocusChapterBoundaries.sql b/PlotLine/Sql/317_SharedFocusChapterBoundaries.sql new file mode 100644 index 00000000..3906d49d --- /dev/null +++ b/PlotLine/Sql/317_SharedFocusChapterBoundaries.sql @@ -0,0 +1,83 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +-- Preserve chapter-only boundaries and precise references at scene-order endpoints. +CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_Coordinate @Action varchar(12),@UserID int,@ProjectID int,@BookID int,@WindowID uniqueidentifier=NULL,@Sequence bigint=0,@ChapterID int=NULL,@SceneID int=NULL,@ParagraphID uniqueidentifier=NULL,@ManuscriptID uniqueidentifier=NULL,@Direction int=0 +AS +BEGIN + SET NOCOUNT ON;SET XACT_ABORT ON; + IF @Action NOT IN('read','publish','resolve','validate') OR @Direction NOT IN(-1,0,1) THROW 51000,'Invalid focus operation.',1; + BEGIN TRY + BEGIN TRANSACTION; + IF NOT EXISTS(SELECT 1 FROM dbo.Books b WITH(HOLDLOCK) JOIN dbo.Projects p WITH(HOLDLOCK) ON p.ProjectID=b.ProjectID JOIN dbo.ProjectUserAccess a WITH(HOLDLOCK) ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND p.IsArchived=0) THROW 51000,'Focus unavailable in this book.',1; + DECLARE @version bigint,@oldChapter int,@oldScene int,@oldParagraph uniqueidentifier,@oldManuscript uniqueidentifier,@canonical uniqueidentifier,@payload nvarchar(max),@last bigint,@changed bit=0; + SELECT @canonical=ManuscriptID,@payload=Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID; + IF @ManuscriptID IS NOT NULL AND (@canonical IS NULL OR @ManuscriptID<>@canonical) THROW 51000,'Manuscript identity changed.',1; + IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID) INSERT dbo.NarrativeFocus(UserID,BookID,Version) VALUES(@UserID,@BookID,0); + SELECT @version=Version,@oldChapter=ChapterID,@oldScene=SceneID,@oldParagraph=ParagraphID,@oldManuscript=ManuscriptID FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID; + IF @Action='publish' + BEGIN + IF @WindowID IS NULL OR @WindowID='00000000-0000-0000-0000-000000000000' OR @Sequence<1 OR @Sequence>9007199254740991 THROW 51000,'Invalid focus origin.',1; + SELECT @last=LastSequence FROM dbo.NarrativeFocusClients WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID AND WindowID=@WindowID; + IF @Sequence<=COALESCE(@last,0) SET @Action='read'; + ELSE IF @last IS NULL INSERT dbo.NarrativeFocusClients VALUES(@UserID,@BookID,@WindowID,@Sequence); + ELSE UPDATE dbo.NarrativeFocusClients SET LastSequence=@Sequence WHERE UserID=@UserID AND BookID=@BookID AND WindowID=@WindowID; + END; + IF @Action IN('read','validate') AND @Action<>'validate' BEGIN SET @ChapterID=@oldChapter;SET @SceneID=@oldScene;SET @ParagraphID=@oldParagraph;END; + IF @Direction<>0 AND @Action IN('publish','resolve') + BEGIN + IF @Action='publish' BEGIN SET @SceneID=@oldScene;SET @ChapterID=@oldChapter;SET @ParagraphID=@oldParagraph;END; + DECLARE @at bigint=(SELECT Ordinal FROM dbo.CharacterWorkspace_SceneOrder(@ProjectID) WHERE BookID=@BookID AND SceneID=@SceneID AND (@ChapterID IS NULL OR ChapterID=@ChapterID)); + IF @SceneID IS NOT NULL AND @at IS NULL THROW 51000,'The current scene reference is no longer valid. Choose another position.',1; + IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) THROW 51000,'The current chapter reference is no longer valid. Choose another position.',1; + DECLARE @stepScene int,@stepChapter int; + IF @at IS NOT NULL + SELECT TOP(1) @stepScene=SceneID,@stepChapter=ChapterID FROM dbo.CharacterWorkspace_SceneOrder(@ProjectID) + WHERE BookID=@BookID AND ((@Direction=1 AND Ordinal>@at) OR (@Direction=-1 AND Ordinal<@at)) + ORDER BY CASE WHEN @Direction=1 THEN Ordinal ELSE -Ordinal END; + ELSE + BEGIN + DECLARE @hasScenes bit=CASE WHEN EXISTS(SELECT 1 FROM dbo.CharacterWorkspace_SceneOrder(@ProjectID) WHERE BookID=@BookID AND ChapterID=@ChapterID) THEN 1 ELSE 0 END; + SELECT TOP(1) @stepScene=n.SceneID,@stepChapter=n.ChapterID + FROM dbo.CharacterWorkspace_SceneOrder(@ProjectID) n JOIN dbo.Chapters ch ON ch.ChapterID=n.ChapterID + LEFT JOIN dbo.Chapters currentChapter ON currentChapter.ChapterID=@ChapterID AND currentChapter.BookID=@BookID AND currentChapter.IsArchived=0 + WHERE n.BookID=@BookID AND (currentChapter.ChapterID IS NULL OR n.ChapterID=currentChapter.ChapterID OR (@hasScenes=0 AND + ((@Direction=1 AND (ISNULL(ch.SortOrder,0)>ISNULL(currentChapter.SortOrder,0) OR (ISNULL(ch.SortOrder,0)=ISNULL(currentChapter.SortOrder,0) AND ch.ChapterNumber>currentChapter.ChapterNumber))) OR + (@Direction=-1 AND (ISNULL(ch.SortOrder,0)@paraChapter) SET @valid=0; + SET @ChapterID=@paraChapter; + DECLARE @paraScene int=(SELECT CanonicalID FROM OPENJSON(@payload,'$.Scenes') WITH(ID uniqueidentifier '$.Id',CanonicalID int '$.CanonicalId',Retired bit) WHERE ID=@sceneKey AND Retired=0); + IF @SceneID IS NOT NULL AND (@paraScene IS NULL OR @SceneID<>@paraScene) SET @valid=0; + SET @SceneID=@paraScene; + END; + IF @SceneID IS NOT NULL + BEGIN + DECLARE @parent int=(SELECT s.ChapterID FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE s.SceneID=@SceneID AND c.BookID=@BookID AND s.IsArchived=0 AND c.IsArchived=0); + IF @parent IS NULL OR (@ChapterID IS NOT NULL AND @ChapterID<>@parent) SET @valid=0;ELSE SET @ChapterID=@parent; + END; + IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) SET @valid=0; + IF @ChapterID IS NULL SET @valid=0; + IF @Action IN('publish','resolve') AND @valid=0 THROW 51000,'This manuscript reference is no longer valid. Select another chapter or scene.',1; + IF @Action='read' AND @oldManuscript IS NOT NULL AND (@canonical IS NULL OR @oldManuscript<>@canonical) SET @valid=0; + IF @Action='publish' AND (ISNULL(@oldChapter,0)<>ISNULL(@ChapterID,0) OR ISNULL(@oldScene,0)<>ISNULL(@SceneID,0) OR ISNULL(CONVERT(varchar(36),@oldParagraph),'')<>ISNULL(CONVERT(varchar(36),@ParagraphID),'') OR ISNULL(CONVERT(varchar(36),@oldManuscript),'')<>ISNULL(CONVERT(varchar(36),@canonical),'')) + BEGIN + SET @changed=1;SET @version=@version+1; + UPDATE dbo.NarrativeFocus SET ChapterID=@ChapterID,SceneID=@SceneID,ParagraphID=@ParagraphID,ManuscriptID=@canonical,OriginWindowID=@WindowID,Version=@version WHERE UserID=@UserID AND BookID=@BookID; + DELETE dbo.NarrativeFocusHistory WHERE UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND ISNULL(SceneID,0)=ISNULL(@SceneID,0); + INSERT dbo.NarrativeFocusHistory VALUES(@UserID,@BookID,@version,@ChapterID,@SceneID); + DELETE h FROM dbo.NarrativeFocusHistory h WHERE h.UserID=@UserID AND h.BookID=@BookID AND h.Sequence NOT IN(SELECT TOP(20) Sequence FROM dbo.NarrativeFocusHistory WHERE UserID=@UserID AND BookID=@BookID ORDER BY Sequence DESC); + END; + SELECT @ProjectID ProjectID,@BookID BookID,@ChapterID ChapterID,@SceneID SceneID,@ParagraphID ParagraphID,@canonical ManuscriptID,@version Version,@valid IsValid,@changed Changed,CASE WHEN @changed=1 THEN @WindowID ELSE (SELECT OriginWindowID FROM dbo.NarrativeFocus WHERE UserID=@UserID AND BookID=@BookID) END OriginWindowID; + COMMIT; + END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;THROW;END CATCH; +END; +GO diff --git a/PlotLine/wwwroot/js/native-companion-status.js b/PlotLine/wwwroot/js/native-companion-status.js index a365e4f8..254978f0 100644 --- a/PlotLine/wwwroot/js/native-companion-status.js +++ b/PlotLine/wwwroot/js/native-companion-status.js @@ -26,6 +26,7 @@ const workspace=document.querySelector('[data-context-workspace]'),scopeBook=Number(workspace?.dataset.scopeBookId); const selectable=leases.filter(l=>l.wordAvailable&&(!scopeBook||Number(l.bookId)===scopeBook)); details.querySelector('[data-word-connection-description]').textContent=workspace&&scopeBook&&!selectable.length?'No live Word document is linked to this book. Saved scenes remain available; use Companion to change a manuscript’s book association.':root.title; + if(selectable.some(lease=>lease.canSharedFocus!==true))details.querySelector('[data-word-connection-description]').textContent+=' Shared manuscript focus requires an updated Word Companion. Existing editing and content synchronisation remain available.'; const previousLabel=documents.selectedOptions[0]?.textContent||'Selected manuscript'; const selected=documents.dataset.userSelected==='true'?documents.value:documents.value || (document.querySelector('[data-word-instance]')?.dataset.wordInstance && document.querySelector('[data-word-session]')?.dataset.wordSession ? document.querySelector('[data-word-instance]').dataset.wordInstance+'/'+document.querySelector('[data-word-session]').dataset.wordSession : ''); const signature=selectable.map(l=>l.instanceId+'/'+l.sessionId+':'+l.documentTitle).join('|'); diff --git a/PlotLine/wwwroot/js/shared-manuscript-focus.js b/PlotLine/wwwroot/js/shared-manuscript-focus.js index 03a7a6fd..8466029a 100644 --- a/PlotLine/wwwroot/js/shared-manuscript-focus.js +++ b/PlotLine/wwwroot/js/shared-manuscript-focus.js @@ -1,9 +1,9 @@ // One user/book/canonical-manuscript focus stream over the window's existing presence connection. (()=>{'use strict';function start(){const context=document.querySelector('[data-context-workspace]'),header=document.querySelector('[data-narrative-focus]'),reader=document.querySelector('.manuscript-reader');if(!context&&!header)return;const initial=window.PlotDirectorNarrativeFocus?.state||(header?JSON.parse(header.querySelector('[data-narrative-initial]').textContent):{});let project=Number(context?.dataset.scopeProjectId||initial.projectID),book=Number(context?.dataset.scopeBookId||initial.bookID),connection,disconnected=false,latest=null,local=null,epoch=0,sequence=0,held=false,publishing=false,selectionPublishing=false,queuedTarget=null;const user=document.body.dataset.pdUserId||context?.dataset.user||'',page=crypto.randomUUID(),buttons=[...document.querySelectorAll('[data-shared-focus-hold]')],outputs=[...document.querySelectorAll('[data-shared-focus-status]')];let id=context?.contextController?.windowId||sessionStorage.getItem('pd.shared-focus.window');if(!/^[\da-f-]{36}$/i.test(id||''))id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);const normal=p=>({projectID:Number(p.projectID||p.projectId||project),bookID:Number(p.bookID||p.bookId||book),chapterID:Number(p.chapterID||p.chapterId)||null,sceneID:Number(p.sceneID||p.sceneId)||null,paragraphID:p.paragraphID||p.paragraphId||null,manuscriptID:p.manuscriptID||p.manuscriptId||null,originWindowID:p.originWindowID||p.originWindowId||null,version:Number(p.version||0),isValid:p.isValid!==false});const key=()=>`pd.shared-focus.${user}.${id}`;const positionKey=p=>p&&[p.projectID,p.bookID,p.manuscriptID,p.chapterID,p.sceneID,p.paragraphID].join('/');function save(){try{sessionStorage.setItem(key(),JSON.stringify({held,local,sequence}));}catch{}}function restore(){try{const data=JSON.parse(sessionStorage.getItem(key())||'null');held=data?.held??context?.dataset.followMode==='snapshot';local=data?.local||normal(context?.contextController?.position||{...initial,chapterID:Number(reader?.dataset.chapterId)||initial.chapterID});sequence=data?.sequence||0;}catch{held=false;}} -function status(message=''){buttons.forEach(b=>{(b.querySelector('span')||b).textContent=held?'Held · Release Hold':'Following · Hold';b.setAttribute('aria-pressed',String(held));b.disabled=!book;});outputs.forEach(n=>n.textContent=message||(held?'Held at local manuscript position · data updates remain live':'Following shared manuscript focus'));document.documentElement.dataset.manuscriptFocusMode=held?'held':'follow';}function apply(position,reason){local=normal(position);save();window.dispatchEvent(new CustomEvent('plotdirector:shared-focus',{detail:{position:local,reason}}));status();}function accept(packet,force=false){const next=normal(packet);if(next.bookID!==book||next.projectID!==project)return false;if(latest&&(next.version{(b.querySelector('span')||b).textContent=held?'Held · Release Hold':'Following · Hold';b.setAttribute('aria-pressed',String(held));b.disabled=!book;});outputs.forEach(n=>n.textContent=message||(held?'Held at local manuscript position · data updates remain live':'Following shared manuscript focus'));document.documentElement.dataset.manuscriptFocusMode=held?'held':'follow';}function apply(position,reason){local=normal(position);save();window.dispatchEvent(new CustomEvent('plotdirector:shared-focus',{detail:{position:local,reason}}));status();}function accept(packet,force=false,metadata=false){const next=normal(packet);if(next.bookID!==book||next.projectID!==project)return false;if(latest&&next.versionnull);if(!response.ok||response.redirected)throw Error(packet?.message||'Focus could not be changed. Your local reference is retained.');return normal(packet);} -async function refresh(force=false){if(!book)return;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Shared?projectID=${project}&bookID=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const packet=await response.json();if(mine===epoch){const recovering=disconnected;disconnected=false;accept(packet,force);if(recovering){status();void validateLocal();}return true;}return false;}catch{disconnected=true;status('Shared focus disconnected · local position and data are retained. Reconnect to catch up.');return false;}} -async function navigate(target,forcePublication=false){const priorLocal=local;if(target.localSelection&&Number(target.bookID||book)===book){local=normal({...local,projectID:project,bookID:book,chapterID:target.chapterID,sceneID:target.sceneID||null,paragraphID:target.paragraphID});save();}if(publishing){queuedTarget=target;return true;}const effective=held?priorLocal:latest?.isValid?latest:null;if(!forcePublication&&Number(target.sceneID||target.sceneId)>0&&Number(target.sceneID||target.sceneId)===effective?.sceneID&&!effective.paragraphID&&!target.paragraphID&&!target.paragraphId)return true;const paragraph=target.paragraphID||target.paragraphId;if(!forcePublication&¶graph&¶graph===effective?.paragraphID&&Number(target.chapterID||target.chapterId)===effective.chapterID)return true;if(publishing)return false;if(target.bookID&&Number(target.bookID)!==book)return false;publishing=true;const localRequest=held;selectionPublishing=target.localSelection===true;try{const normalized={chapterID:target.chapterID||target.chapterId||null,sceneID:target.sceneID||target.sceneId||null,paragraphID:target.paragraphID||target.paragraphId||null,...(target.direction?{direction:target.direction}:{}),...(target.manuscriptID?{manuscriptID:target.manuscriptID}:{})};if(held&&target.direction)Object.assign(normalized,{chapterID:local.chapterID,sceneID:local.sceneID});const result=await request(localRequest?'Resolve':'Publish',normalized);if(result.bookID!==book||result.projectID!==project)return false;if(localRequest){if(held)apply(result,selectionPublishing?'selection':'local');else await refresh(true);}else accept(result,true);return true;}catch(error){status(error.message);return false;}finally{publishing=false;selectionPublishing=false;if(queuedTarget){const next=queuedTarget;queuedTarget=null;void navigate(next,true);}}} +async function refresh(force=false){if(!book)return;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Shared?projectID=${project}&bookID=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const packet=await response.json();if(mine===epoch){const recovering=disconnected;disconnected=false;accept(packet,force,true);if(recovering){status(!held&&latest?.isValid===false?'Shared focus is unavailable. Select another position; your local reference is retained.':'');void validateLocal();}return true;}return false;}catch{disconnected=true;status('Shared focus disconnected · local position and data are retained. Reconnect to catch up.');return false;}} +async function navigate(target,forcePublication=false){const priorLocal=local;if(target.localSelection&&Number(target.bookID||book)===book){local=normal({...local,projectID:project,bookID:book,chapterID:target.chapterID,sceneID:target.sceneID||null,paragraphID:target.paragraphID});save();}if(publishing){queuedTarget=target;return true;}const effective=held?priorLocal:latest?.isValid?latest:null;if(!forcePublication&&Number(target.sceneID||target.sceneId)>0&&Number(target.sceneID||target.sceneId)===effective?.sceneID&&!effective.paragraphID&&!target.paragraphID&&!target.paragraphId)return true;if(!forcePublication&&!target.direction&&!target.sceneID&&!target.sceneId&&!target.paragraphID&&!target.paragraphId&&Number(target.chapterID||target.chapterId)>0&&Number(target.chapterID||target.chapterId)===effective?.chapterID&&!effective.sceneID&&!effective.paragraphID)return true;const paragraph=target.paragraphID||target.paragraphId;if(!forcePublication&¶graph&¶graph===effective?.paragraphID&&Number(target.chapterID||target.chapterId)===effective.chapterID)return true;if(publishing)return false;if(target.bookID&&Number(target.bookID)!==book)return false;publishing=true;const localRequest=held;selectionPublishing=target.localSelection===true;try{const normalized={chapterID:target.chapterID||target.chapterId||null,sceneID:target.sceneID||target.sceneId||null,paragraphID:target.paragraphID||target.paragraphId||null,...(target.direction?{direction:target.direction}:{}),...(target.manuscriptID?{manuscriptID:target.manuscriptID}:{})};if(held&&target.direction)Object.assign(normalized,{chapterID:local.chapterID,sceneID:local.sceneID,paragraphID:local.paragraphID});const result=await request(localRequest?'Resolve':'Publish',normalized);if(result.bookID!==book||result.projectID!==project)return false;if(localRequest){if(held)apply(result,selectionPublishing?'selection':'local');else await refresh(true);}else accept(result,true);return true;}catch(error){status(error.message);return false;}finally{publishing=false;selectionPublishing=false;if(queuedTarget){const next=queuedTarget;queuedTarget=null;void navigate(next,true);}}} async function toggle(){queuedTarget=null;if(held){if(!await refresh()){status('Hold retained: reconnect before catching up to authoritative shared focus.');return;}held=false;save();if(latest?.isValid&&latest.chapterID)apply(latest,'release');else status('Following · no valid shared focus; local position retained.');}else{held=true;save();status();}window.dispatchEvent(new CustomEvent('plotdirector:focus-mode',{detail:{held}}));} async function validateLocal(){if(!held||!local?.chapterID)return;try{const result=await request('Validate',local);if(!result.isValid)status('Held reference is no longer valid. Select another local position or Release Hold.');}catch{status('Held reference cannot be resolved. Select another position; data updates remain connected.');}} function wire(c){if(!c||connection)return;connection=c;c.on('ManuscriptFocusChanged',packet=>accept(packet));c.on('ManuscriptFocusDelivery',packet=>{if(Number(packet.bookID||packet.bookId)===book&&Number(packet.version)===latest?.version)status('Word cannot follow this reference in the background. Save and synchronise Word; other windows remain independent.');});c.on('ContextInvalidated',hint=>{if(hint.bookId&&Number(hint.bookId)!==book||hint.projectId&&Number(hint.projectId)!==project)return;window.dispatchEvent(new CustomEvent('plotdirector:reference-invalidated',{detail:hint}));void validateLocal();});c.onreconnecting(()=>{disconnected=true;status('Shared focus reconnecting · local position retained.');});c.onclose(()=>{disconnected=true;status('Shared focus disconnected · local position retained.');});c.onreconnected(()=>{void refresh().then(()=>validateLocal());});void refresh();} diff --git a/PlotLine/wwwroot/js/writer-word.js b/PlotLine/wwwroot/js/writer-word.js index 79753933..ae286aa2 100644 --- a/PlotLine/wwwroot/js/writer-word.js +++ b/PlotLine/wwwroot/js/writer-word.js @@ -18,7 +18,7 @@ const identity=current&&data.canonical?.manuscriptID===current.manuscriptId;cons 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.'; 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;} +freshness.textContent=chapterStatus.text+(current&¤t.canSharedFocus!==true?' Update Word Companion to use shared manuscript focus.':'');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);