From 8a719dae0acb5cf62a28a94fdcc18bcb9d1951ee Mon Sep 17 00:00:00 2001 From: nick Date: Mon, 23 Nov 2026 16:23:30 +0000 Subject: [PATCH] Repair queued Word focus intent, first-join reconciliation and Hold controls --- .../DeveloperVersion.props | 2 +- .../Protocol/FocusInputState.cs | 12 ++++++ .../Protocol/FocusWindowState.cs | 4 +- .../Tests/SharedFocusTests.cs | 11 +++++ .../Vsto/NativeRibbon.cs | 6 +-- .../Vsto/PlotDirector.WordAddIn.csproj | 2 +- PlotDirector.NativeCompanion/Vsto/Ribbon.xml | 2 +- .../Vsto/WordAdapter.cs | 7 +-- .../Vsto/WordFocus.cs | 12 +++--- .../Vsto/WordFocusInput.cs | 43 +++++++++++++++++++ .../WindowsValidation/Setup/Release.json | 6 +-- .../Browser/shared-focus-reliability.cjs | 17 ++++++++ PlotLine/Services/SharedManuscriptFocus.cs | 2 +- .../Views/Shared/_FocusFollowControl.cshtml | 2 +- .../Shared/_WritingConnectionDetails.cshtml | 1 + PlotLine/Views/Writing/Context.cshtml | 2 +- PlotLine/wwwroot/css/application-shell.css | 6 +-- PlotLine/wwwroot/js/context-workspace.js | 12 +++--- .../wwwroot/js/shared-manuscript-focus.js | 17 +++++--- 19 files changed, 126 insertions(+), 40 deletions(-) create mode 100644 PlotDirector.NativeCompanion/Protocol/FocusInputState.cs create mode 100644 PlotDirector.NativeCompanion/Vsto/WordFocusInput.cs create mode 100644 PlotLine.Tests/Browser/shared-focus-reliability.cjs diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index 9d40ad43..5635d912 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.45 +1.0.0.46 diff --git a/PlotDirector.NativeCompanion/Protocol/FocusInputState.cs b/PlotDirector.NativeCompanion/Protocol/FocusInputState.cs new file mode 100644 index 00000000..1ee1ca39 --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/FocusInputState.cs @@ -0,0 +1,12 @@ +namespace PlotDirector.Companion.Protocol; + +// A queued input belongs to one actual Word window. Selection callbacks may arrive +// after the mouse/key has been released; a sampled key-down bit is not evidence. +public sealed class FocusInputState +{ + private long sequence, pending, at;private int window;private bool confirmed; + public void Record(int owner,long milliseconds,bool manuscriptClick){window=owner;at=milliseconds;pending=++sequence;confirmed=manuscriptClick;} + public void Confirm(){if(pending!=0)confirmed=true;} + public void Clear(){pending=0;confirmed=false;} + public long Consume(int owner,long milliseconds){var result=owner==window&&confirmed&&milliseconds>=at&&milliseconds-at<=2000?pending:0;Clear();return result;} +} diff --git a/PlotDirector.NativeCompanion/Protocol/FocusWindowState.cs b/PlotDirector.NativeCompanion/Protocol/FocusWindowState.cs index 2ce4a16e..4bcb6f78 100644 --- a/PlotDirector.NativeCompanion/Protocol/FocusWindowState.cs +++ b/PlotDirector.NativeCompanion/Protocol/FocusWindowState.cs @@ -3,8 +3,8 @@ namespace PlotDirector.Companion.Protocol; public sealed class FocusWindowState { public Guid Id {get;}=Guid.NewGuid();public bool Held{get;private set;}public long Sequence{get;private set;}public long LastSharedRevision{get;private set;}public Guid ModeRequest{get;private set;}=Guid.NewGuid(); - private int start=-1,end=-1;private long appliedRevision=-1;private bool catchup; + private int start=-1,end=-1;private long appliedRevision=-1,lastInput;private bool catchup; public void Hold(bool held){if(Held==held)return;Held=held;if(!held){appliedRevision=-1;catchup=true;}ModeRequest=Guid.NewGuid();} - public long Observe(int nextStart,int nextEnd,bool deliberate){var changed=start!=nextStart||end!=nextEnd;start=nextStart;end=nextEnd;return changed&&deliberate&&!Held?++Sequence:0;} + public long Observe(int nextStart,int nextEnd,bool deliberate,long input=0){var changed=start!=nextStart||end!=nextEnd;start=nextStart;end=nextEnd;var fresh=input>lastInput;if(fresh)lastInput=input;return (input==0?changed:fresh)&&deliberate&&!Held?++Sequence:0;} public bool Accept(long revision,Guid origin){if(revision0&&input.Consume(10,151)==0,"queued manuscript click survives key release and is consumed once"); + check(a.Observe(50,50,true,click)==2&&a.Observe(50,50,true,click)==0,"fresh click at unchanged editing caret publishes once after remote reveal"); + input.Record(10,200,false);input.Confirm();check(input.Consume(10,250)>0,"navigation-pane selection confirms queued input"); + input.Record(10,300,false);check(input.Consume(10,350)==0,"ribbon click without selection does not publish"); + input.Record(10,400,true);input.Clear();check(input.Consume(10,450)==0,"typing and remote navigation discard pending input"); + input.Record(10,500,true);check(input.Consume(20,550)==0,"input cannot leak to another Word window"); + input.Record(10,600,true);check(input.Consume(10,3000)==0,"expired input cannot turn passive observations into navigation"); + input.Record(10,3100,true);check(input.Consume(10,3150)>0,"genuine click works immediately after suppression"); + a.Hold(true);check(a.Observe(60,60,true,99)==0,"held deliberate input never publishes");a.Hold(false);check(a.Observe(60,60,false)==0,"release never republishes held position"); } } diff --git a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs index 7e9f93dc..fa0cb71e 100644 --- a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs +++ b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs @@ -37,7 +37,7 @@ namespace PlotDirector.WordAddIn try { Refresh("PlotDirectorStatus", GetStatus(null)); - Refresh("PlotDirectorHold",adapter()?.FocusWindowKey+GetFocusHeld(null));Refresh("PlotDirectorFocusState",adapter()?.FocusWindowKey+GetFocusState(null)); + Refresh("PlotDirectorHold",adapter()?.FocusWindowKey+GetFocusHeld(null)+CanHoldFocus(null)); Refresh("PlotDirectorBook", GetBookTip(null)); Refresh("PlotDirectorChapter", GetChapterTip(null)); Refresh("PlotDirectorScene", GetSceneTip(null)); @@ -70,8 +70,8 @@ namespace PlotDirector.WordAddIn public bool GetFocusHeld(Office.IRibbonControl control)=>adapter()?.WindowFocusHeld(control?.Context)==true; public string GetFocusAction(Office.IRibbonControl control)=>GetFocusHeld(control)?"Release Hold":"Hold"; - public string GetFocusState(Office.IRibbonControl control)=>adapter()?.WindowFocusState(control?.Context)??"Following"; - public string GetFocusTip(Office.IRibbonControl control)=>GetFocusHeld(control)?"Release Hold: catch up to shared manuscript focus. Content synchronisation stays active.":"Hold this Word window at its local position. Other windows and content synchronisation continue."; + public bool CanHoldFocus(Office.IRibbonControl control)=>adapter()?.CanHoldFocus==true; + public string GetFocusTip(Office.IRibbonControl control)=>!CanHoldFocus(control)?"Connect Companion and select a linked Word manuscript.":GetFocusHeld(control)?"Release Hold: catch up to shared manuscript focus. Content synchronisation stays active.":"Hold this Word window at its local position. Other windows and content synchronisation continue."; public void ToggleFocusHold(Office.IRibbonControl control,bool pressed){adapter()?.SetFocusHeld(pressed);Invalidate();} public bool CanOpenBook(Office.IRibbonControl control) => adapter()?.HasRibbonBook == true; public string GetBookTip(Office.IRibbonControl control) => adapter()?.RibbonBook ?? "No linked book"; diff --git a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj index c182e0f2..d37e0899 100644 --- a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj +++ b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj @@ -23,7 +23,7 @@ PlotDirector.Companion.Protocol PlotDirector.Companion.Client ThisAddIn.cs - + ThisAddIn.cs diff --git a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml index df09b6f7..54d96ed7 100644 --- a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml +++ b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml @@ -7,7 +7,7 @@ - + ',contentType:'text/html'}));await page.goto('https://fixture.invalid/'); + await page.evaluate(()=>{window.reads=[];window.posts=[];window.moves=[];window.notices=[];window.PlotDirector={toast:{warning:m=>notices.push(m)}};window.addEventListener('plotdirector:shared-focus',e=>moves.push(e.detail));window.fetch=(url,options={})=>{if(options.method==='POST'){posts.push({url,body:String(options.body)});return Promise.resolve({ok:true,json:async()=>({...fixture,version:10})});}return new Promise(resolve=>reads.push({resolve,signal:options.signal}));};window.handlers={};window.lifecycle={};window.fixture={projectID:3,bookID:12,chapterID:1,sceneID:10,version:1,isValid:true};window.conn={state:'Disconnected',connectionId:null,on:(n,f)=>handlers[n]=f,onreconnecting:f=>lifecycle.reconnecting=f,onclose:f=>lifecycle.close=f,onreconnected:f=>lifecycle.reconnected=f};window.PlotDirectorPresenceConnection=conn;window.respond=(i,p)=>reads[i].resolve({ok:true,json:async()=>({...fixture,...p})});}); + await page.addScriptTag({content:script}); + assert.equal(await page.evaluate(()=>reads.length),0,'no authoritative read before group join');assert.equal(await page.getByRole('button',{name:'Hold',exact:true}).isEnabled(),false); + await page.evaluate(()=>{conn.state='Connected';conn.connectionId='first';document.dispatchEvent(new Event('pd-presence-ready'));document.dispatchEvent(new Event('pd-presence-ready'));});assert.equal(await page.evaluate(()=>reads.length),1,'first ready rereads once'); + await page.evaluate(()=>{handlers.ManuscriptFocusChanged({...fixture,version:3,sceneID:30});respond(0,{version:2,sceneID:20});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===3&&document.querySelector('button').disabled===false);assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),30,'late startup snapshot cannot overwrite notification');console.log('PASS initial connection race, coalescing and revision reconciliation'); + await page.getByRole('button',{name:'Hold',exact:true}).click();assert.equal(await page.getByRole('button',{name:'Release Hold',exact:true}).getAttribute('aria-pressed'),'true');const moves=await page.evaluate(()=>window.moves.length); + await page.evaluate(()=>{conn.state='Reconnecting';lifecycle.reconnecting();});assert.equal(await page.getByRole('button',{name:'Release Hold',exact:true}).isEnabled(),false); + await page.evaluate(()=>{conn.state='Connected';conn.connectionId='second';lifecycle.reconnected();document.dispatchEvent(new Event('pd-presence-ready'));respond(1,{version:4,sceneID:40});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===4&&document.querySelector('button').disabled===false);assert.equal(await page.evaluate(()=>window.moves.length),moves,'held recovery must retain local position');assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),30); + await page.getByRole('button',{name:'Release Hold',exact:true}).press('Enter');await page.waitForFunction(()=>reads.length===3);await page.evaluate(()=>respond(2,{version:5,sceneID:50}));await page.waitForFunction(()=>PlotDirectorSharedFocus.local.sceneID===50&&!PlotDirectorSharedFocus.held);assert.equal(await page.evaluate(()=>posts.length),1,'only held reference validation posts; release cannot publish');assert(await page.evaluate(()=>posts.every(p=>!p.url.endsWith('/Publish'))));assert.equal(await page.getByRole('button',{name:'Hold',exact:true}).getAttribute('aria-pressed'),'false');console.log('PASS reconnect preserves Hold; keyboard Release catches latest without publication'); + await page.evaluate(()=>{void PlotDirectorSharedFocus.refresh();conn.state='Reconnecting';lifecycle.reconnecting();conn.state='Connected';conn.connectionId='third';lifecycle.reconnected();respond(3,{version:99,sceneID:99});respond(4,{version:6,sceneID:60});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===6);assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),60,'abandoned transport cannot overwrite new connection');console.log('PASS disconnected read cancellation and new group recovery'); + const partial=fs.readFileSync(path.join(__dirname,'../../PlotLine/Views/Shared/_FocusFollowControl.cshtml'),'utf8');assert(!partial.includes('data-shared-focus-status'));assert(!partial.includes('Following'));assert(partial.includes('disabled'));const ribbon=fs.readFileSync(path.join(__dirname,'../../PlotDirector.NativeCompanion/Vsto/Ribbon.xml'),'utf8');assert(!ribbon.includes('PlotDirectorFocusState'));assert(ribbon.includes('getEnabled="CanHoldFocus"'));console.log('PASS concise accessible toggle and no adjacent state controls'); + }finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine/Services/SharedManuscriptFocus.cs b/PlotLine/Services/SharedManuscriptFocus.cs index d1f69c87..7dfb6d9b 100644 --- a/PlotLine/Services/SharedManuscriptFocus.cs +++ b/PlotLine/Services/SharedManuscriptFocus.cs @@ -30,7 +30,7 @@ public sealed class SharedManuscriptFocus(ISqlConnectionFactory factory,IHubCont { using var db=factory.CreateConnection();var result=await db.QuerySingleAsync("dbo.NarrativeFocus_Coordinate",new{Action=action,UserID=user,request.ProjectID,request.BookID,request.WindowID,request.Sequence,request.ChapterID,request.SceneID,request.ParagraphID,request.ManuscriptID,request.Direction},commandType:CommandType.StoredProcedure); if(action!="read")diagnostics?.Write(user,request.BookID,action+"-result",request.WindowID,request.Sequence,chapter:result.ChapterID,scene:result.SceneID,paragraph:result.ParagraphID,version:result.Version,outcome:result.Changed?"changed":result.IsValid?"unchanged":"invalid"); - if(result.Changed){try{await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync("ManuscriptFocusChanged",result);}catch(Exception e){logger.LogWarning("Focus notification unavailable: {Type}",e.GetType().Name);}foreach(var lease in native.Read(user,result.BookID).Where(l=>l.Position.CanSharedFocus))try{await FollowWord(user,result,lease);}catch(Exception e){logger.LogWarning("Word focus delivery unavailable: {Type}",e.GetType().Name);}} + if(result.Changed){try{await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync("ManuscriptFocusChanged",result);diagnostics?.Write(user,result.BookID,"signalr-send",request.WindowID,request.Sequence,chapter:result.ChapterID,scene:result.SceneID,paragraph:result.ParagraphID,version:result.Version,outcome:"user-group-dispatched");}catch(Exception e){logger.LogWarning("Focus notification unavailable: {Type}",e.GetType().Name);}foreach(var lease in native.Read(user,result.BookID).Where(l=>l.Position.CanSharedFocus))try{await FollowWord(user,result,lease);}catch(Exception e){logger.LogWarning("Word focus delivery unavailable: {Type}",e.GetType().Name);}} return result; } public async Task WordPosition(int user,NativeLease lease,string action,SharedFocusPosition? focus=null) diff --git a/PlotLine/Views/Shared/_FocusFollowControl.cshtml b/PlotLine/Views/Shared/_FocusFollowControl.cshtml index bcbac13b..d7526723 100644 --- a/PlotLine/Views/Shared/_FocusFollowControl.cshtml +++ b/PlotLine/Views/Shared/_FocusFollowControl.cshtml @@ -1,2 +1,2 @@ @{var embedded=ViewContext.RouteData.Values["controller"]?.ToString()=="Writing";} - + diff --git a/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml b/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml index 6ad9de0b..d3c786c1 100644 --- a/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml +++ b/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml @@ -1,5 +1,6 @@

Word connection

+

Checking the Companion’s authenticated document heartbeat…

diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index 6ab7efda..1b84daaf 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -25,7 +25,7 @@ -

@(Model.Display?.FollowStatus ?? "Waiting for a saved scene")

+