diff --git a/PlotDirector.NativeCompanion/Agent/SessionManager.cs b/PlotDirector.NativeCompanion/Agent/SessionManager.cs index 590015b5..56a6b715 100644 --- a/PlotDirector.NativeCompanion/Agent/SessionManager.cs +++ b/PlotDirector.NativeCompanion/Agent/SessionManager.cs @@ -109,7 +109,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai if(message.Kind.StartsWith("ai-",StringComparison.Ordinal))return ai?.Handle(document.Descriptor,message,answer)??Reject(answer,"ai-unavailable"); switch (message.Kind) { - case "tray-context":case "tray-intent":case "tray-workspace": break; + case "tray-context":case "tray-workspace": break; case "tray-audio": if(message.Action is not ("play" or "pause" or "back15" or "forward15"))return Reject(answer,"invalid-audio-operation"); break; diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index ee0e5bf0..c5ab9c54 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -49,8 +49,8 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway if(request.Kind=="tray-audio"&&answer.Status=="ok"&&doc.Active&&doc.Book>0) AudioRequested?.Invoke(doc.Session,request.Action); if(request.Kind is "tray-sync" or "tray-repair")ReceiveChapterRibbonRequest(doc,request.Kind); - if ((request.Kind is "tray-context" or "tray-intent") && answer.Status == "ok") - _ = OpenRibbonWorkspace(doc.Session, request.Revision, request.Kind == "tray-context" ? "context" : "intent"); + if (request.Kind == "tray-context" && answer.Status == "ok") + _ = OpenRibbonWorkspace(doc.Session, request.Revision, "context"); if (request.Kind == "tray-workspace" && answer.Status == "ok") _ = OpenRibbonWorkspace(doc.Session, request.Revision, "book"); CaptureFrame(doc,request,answer); diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index b8023a12..9d40ad43 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.44 +1.0.0.45 diff --git a/PlotDirector.NativeCompanion/Tests/TrayTests.cs b/PlotDirector.NativeCompanion/Tests/TrayTests.cs index e4209904..fcbee9fd 100644 --- a/PlotDirector.NativeCompanion/Tests/TrayTests.cs +++ b/PlotDirector.NativeCompanion/Tests/TrayTests.cs @@ -39,6 +39,10 @@ internal static class TrayTests bool staleLaunch=false; try{control.OpenPage(Guid.NewGuid(),"writer");}catch(InvalidOperationException){staleLaunch=true;} check(staleLaunch&&launched.Count==1,"Return to Writer rejects a stale document without launching a page"); + var retired=Apply(new(){Kind="tray-intent",SessionId=first.SessionId,Revision=1}); + check(retired.Status!="ok"&&launched.Count==1,"retired Intent ribbon IPC cannot launch a separate workspace"); + control.OpenPage(first.SessionId,"context"); + check(launched.Last().EndsWith("&view=context",StringComparison.Ordinal)&&launched.Last().Contains("sessionId="+first.SessionId),"Context launch retains authorised exact-session routing for browser window reuse"); bool refused=false;try{control.SelectBook(second.SessionId,999,false);}catch(InvalidOperationException){refused=true;}check(refused,"tray refuses unauthorised books before Word metadata command"); using(var heartbeatStop=new CancellationTokenSource()){ var heartbeat=control.Heartbeat(heartbeatStop.Token);await Until(()=>handler.Heartbeats==1);await Task.Delay(600); diff --git a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs index e2e108c7..7e9f93dc 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",GetFocusHeld(null).ToString());Refresh("PlotDirectorFocusState",GetFocusState(null)); + Refresh("PlotDirectorHold",adapter()?.FocusWindowKey+GetFocusHeld(null));Refresh("PlotDirectorFocusState",adapter()?.FocusWindowKey+GetFocusState(null)); Refresh("PlotDirectorBook", GetBookTip(null)); Refresh("PlotDirectorChapter", GetChapterTip(null)); Refresh("PlotDirectorScene", GetSceneTip(null)); @@ -45,7 +45,6 @@ namespace PlotDirector.WordAddIn Refresh("PlotDirectorSyncProgress", GetSyncProgress(null)); var enabled = CanOpenBook(null).ToString(); Refresh("PlotDirectorContext", enabled); - Refresh("PlotDirectorIntent", enabled); Refresh("PlotDirectorWeb", enabled); Refresh("PlotDirectorSynchronise", enabled); Refresh("PlotDirectorRepair", enabled); @@ -69,8 +68,9 @@ namespace PlotDirector.WordAddIn ui?.InvalidateControl(control.Id); } - public bool GetFocusHeld(Office.IRibbonControl control)=>adapter()?.FocusHeld==true; - public string GetFocusState(Office.IRibbonControl control)=>adapter()?.FocusStateLabel??"Following"; + 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 void ToggleFocusHold(Office.IRibbonControl control,bool pressed){adapter()?.SetFocusHeld(pressed);Invalidate();} public bool CanOpenBook(Office.IRibbonControl control) => adapter()?.HasRibbonBook == true; @@ -82,7 +82,6 @@ namespace PlotDirector.WordAddIn public string GetSyncTip(Office.IRibbonControl control) => adapter()?.ChapterStatusTip ?? "Open Companion to connect."; public string GetStatus(Office.IRibbonControl control) => adapter()?.ConnectionState == "connected" ? "Companion connected" : "Companion offline"; public void OpenContext(Office.IRibbonControl control) => adapter()?.OpenWritingWorkspace("tray-context"); - public void OpenIntent(Office.IRibbonControl control) => adapter()?.OpenWritingWorkspace("tray-intent"); public void OpenPlotDirector(Office.IRibbonControl control) => adapter()?.OpenWritingWorkspace("tray-workspace"); public void Synchronise(Office.IRibbonControl control) => adapter()?.RequestChapterSynchronisation(false); public void Repair(Office.IRibbonControl control) => adapter()?.RequestChapterSynchronisation(true); diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index 4ff87eda..9a097b4b 100644 --- a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -3,6 +3,6 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("PlotDirector Word Companion — Native development")] [assembly: AssemblyCompany("Nick Beckley")] [assembly: AssemblyProduct("PlotDirector")] -[assembly: AssemblyVersion("1.0.0.44")] -[assembly: AssemblyFileVersion("1.0.0.44")] +[assembly: AssemblyVersion("1.0.0.45")] +[assembly: AssemblyFileVersion("1.0.0.45")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml index 1a95637c..df09b6f7 100644 --- a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml +++ b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml @@ -7,10 +7,9 @@ - + - '); + await page.evaluate(outcome=>{ + window.calls=[];window.closedByLaunch=false;window.close=()=>{window.closedByLaunch=true;}; + window.PlotDirectorContextEnvironment=outcome==='no-storage'?null:'browser-profile'; + window.PlotDirectorPresenceConnection={state:'Connected',invoke:async(name,...args)=>{ + window.calls.push([name,...args]);if(name==='OpenContextWindow'){if(outcome==='failure')throw new Error('offline');return outcome;} + }}; + },outcome); + await page.addScriptTag({content:script}); + if(outcome==='open'){ + await page.waitForURL('**/Writing/Context?**');const url=new URL(page.url()); + assert.equal(url.searchParams.get('bookId'),'12');assert.equal(url.searchParams.get('sessionId'),'session'); + assert.equal(url.searchParams.has('sceneId'),false,'opening cannot force a scene selection'); + }else{ + await page.waitForFunction(()=>window.closedByLaunch||document.querySelector('[data-context-launch-status]').textContent.length>0); + const state=await page.evaluate(()=>({calls:window.calls,closed:window.closedByLaunch,retry:!document.querySelector('button').hidden,text:document.querySelector('p').textContent})); + assert.equal(state.closed,['reused','pending'].includes(outcome)); + assert.equal(state.calls.some(c=>/Publish|Resolve|Navigate/.test(c[0])),false,'opening never publishes or redirects manuscript focus'); + assert.equal(state.retry,outcome==='failure'); + if(outcome==='no-storage')assert.equal(state.calls.length,0,'missing environment cannot target another device'); + if(outcome==='reused')assert.match(state.text,/layout, tools, Hold and position were retained/); + } + console.log('PASS isolated native Context launch: '+outcome);await context.close(); + } + }finally{await browser.close();} +})().catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/PlotLine.Tests/ContextWindowsTests.cs b/PlotLine.Tests/ContextWindowsTests.cs index 7fc9cd3b..15fdaf7c 100644 --- a/PlotLine.Tests/ContextWindowsTests.cs +++ b/PlotLine.Tests/ContextWindowsTests.cs @@ -30,5 +30,17 @@ internal static class ContextWindowsTests Check(store.Route(7,"reconnected",open with{TargetSessionID="main-remote"})==null,"explicit target cannot bypass same-environment restriction"); store.Remove("main-local");store.Remove("main-remote");Check(store.TryLaunch(7,"reconnected",12,environment),"one browser environment can reserve a missing main-window launch");Check(!store.TryLaunch(7,"reconnected",12,environment),"concurrent fallback launches are suppressed");clock.Now+=TimeSpan.FromSeconds(11);Check(store.TryLaunch(7,"reconnected",12,environment),"failed or blocked main launches can be retried after the short lease"); try{store.Register(7,"bad",new(1,12,Guid.NewGuid(),[new("0","fake",["word.navigate"])]));throw new Exception("Word action accepted");}catch(ArgumentException){Check(true,"interaction contract cannot invoke Word navigation");} + var launchStore=new ContextWindows(clock);var browser=Guid.NewGuid(); + launchStore.Register(7,"launcher",new(1,12,Guid.NewGuid(),[],browser)); + launchStore.Register(8,"foreign-user",Registration(Guid.NewGuid(),12,"scene.focus") with{EnvironmentID=browser}); + launchStore.Register(7,"foreign-book",Registration(Guid.NewGuid(),13,"scene.focus") with{EnvironmentID=browser}); + launchStore.Register(7,"foreign-browser",Registration(Guid.NewGuid(),12,"scene.focus") with{EnvironmentID=Guid.NewGuid()}); + Check(launchStore.OpenContext(7,"launcher",12).Status=="open","ribbon launch cannot reuse a foreign account, book or browser window"); + Check(launchStore.OpenContext(7,"launcher",12).Status=="pending","repeated ribbon launches reserve only one new Context window"); + launchStore.Register(7,"held-context",Registration(Guid.NewGuid(),12,"scene.focus",false) with{EnvironmentID=browser}); + Check(launchStore.OpenContext(7,"launcher",12)==("reused","held-context"),"existing Context is reused without replacing busy tools or its independent held position"); + try{launchStore.OpenContext(8,"launcher",12);throw new Exception("Cross-user launch accepted");}catch(ArgumentException){Check(true,"Context launch validates its authenticated origin registration");} + launchStore.Remove("held-context");clock.Now+=TimeSpan.FromSeconds(11); + Check(launchStore.OpenContext(7,"launcher",12).Status=="open","failed launch reservations expire for an explicit retry"); } } diff --git a/PlotLine/Controllers/NativeWorkspaceController.cs b/PlotLine/Controllers/NativeWorkspaceController.cs index 7786705e..ac9edcf8 100644 --- a/PlotLine/Controllers/NativeWorkspaceController.cs +++ b/PlotLine/Controllers/NativeWorkspaceController.cs @@ -15,7 +15,8 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB public async Task Workspace(int bookId,Guid? instanceId,Guid? sessionId,string view="book") { var structure=await access.GetBookStructureAsync(bookId,Author);if(structure==null)return Forbid();var book=await books.GetAsync(bookId);if(book==null)return NotFound(); - if(view is "context" or "intent") return RedirectToAction("Context","Writing",new{projectId=book.ProjectID,bookId,instanceId,sessionId,embedded=true}); + if(view=="context") return View("ContextLaunch",new NativeWorkspaceModel(bookId,book.ProjectID,book.BookDisplayTitle,instanceId,sessionId,"context",[],structure.Chapters)); + if(view=="intent") return RedirectToAction("Context","Writing",new{projectId=book.ProjectID,bookId,instanceId,sessionId,embedded=true}); return View(new NativeWorkspaceModel(bookId,book.ProjectID,book.BookDisplayTitle,instanceId,sessionId,view is "context" or "intent"?view:"book",await reviews.List(Author,bookId),structure.Chapters)); } [HttpGet("presence")] diff --git a/PlotLine/Hubs/NativeCompanionPresenceHub.cs b/PlotLine/Hubs/NativeCompanionPresenceHub.cs index b7facaa0..b71aa895 100644 --- a/PlotLine/Hubs/NativeCompanionPresenceHub.cs +++ b/PlotLine/Hubs/NativeCompanionPresenceHub.cs @@ -32,6 +32,13 @@ public sealed class NativeCompanionPresenceHub(ContextWindows windows,IWordCompa public async Task ClaimContextMainWindow(int bookId,Guid environmentID) {await Book(bookId);try{return windows.TryLaunch(Author,Context.ConnectionId,bookId,environmentID);}catch(ArgumentException){throw new HubException("Invalid navigation scope.");}} public async Task MyContextWindows(int bookId){await Book(bookId);return windows.List(Author,bookId);} + public async Task OpenContextWindow(int bookId) + { + await Book(bookId);(string Status,string? Connection) result; + try{result=windows.OpenContext(Author,Context.ConnectionId,bookId);}catch(Exception e)when(e is ArgumentException or InvalidOperationException){throw new HubException(e.Message);} + if(result.Connection!=null)await Clients.Client(result.Connection).SendAsync("ContextWindowRequested"); + return result.Status; + } public async Task SendContextInteraction(ContextInteraction command) { if(command==null||command.Version!=1||command.TargetUserID.HasValue||!ContextWindows.Actions.Contains(command.Action))throw new HubException("Unsupported interaction."); diff --git a/PlotLine/Services/Context/ContextWindows.cs b/PlotLine/Services/Context/ContextWindows.cs index a1329ea8..ed4b11d2 100644 --- a/PlotLine/Services/Context/ContextWindows.cs +++ b/PlotLine/Services/Context/ContextWindows.cs @@ -22,6 +22,19 @@ public sealed class ContextWindows(TimeProvider clock) public static readonly string[] Actions = ["character.focus", "location.focus", "location.focusAtStoryPoint", "relationship.focus", "scene.focus", "workspace.open"]; public static string Group(int user,int book) => $"context-windows:{user}:{book}"; private readonly Dictionary<(int,Guid),DateTimeOffset> launches=[]; + private readonly Dictionary<(int,Guid,int),DateTimeOffset> contextLaunches=[]; + public (string Status,string? Connection) OpenContext(int user,string origin,int book) + { + lock(gate){Prune();var source=leases.GetValueOrDefault(origin); + if(source?.User!=user||source.Registration.BookID!=book||source.Registration.EnvironmentID is not Guid environment||environment==Guid.Empty) + throw new ArgumentException("Invalid Context launch scope."); + var target=leases.Values.Where(x=>x.User==user&&x.Connection!=origin&&x.Registration.Kind=="context"&&x.Registration.BookID==book&&x.Registration.EnvironmentID==environment&&x.Registration.Panes.Length>0).OrderByDescending(x=>x.Seen).FirstOrDefault(); + if(target!=null)return("reused",target.Connection); + var key=(user,environment,book);if(contextLaunches.ContainsKey(key))return("pending",null); + if(contextLaunches.Count>=4096)throw new InvalidOperationException("Wait for pending Context windows."); + contextLaunches[key]=clock.GetUtcNow().AddSeconds(10);return("open",null); + } + } public bool TryLaunch(int user,string connection,int book,Guid environment) {lock(gate){Prune();var source=leases.GetValueOrDefault(connection);if(source?.User!=user||source.Registration.BookID!=book||source.Registration.EnvironmentID!=environment||environment==Guid.Empty)throw new ArgumentException("Invalid navigation scope."); if(leases.Values.Any(x=>x.User==user&&x.Registration.Kind=="main"&&x.Registration.EnvironmentID==environment)||launches.ContainsKey((user,environment))||launches.Count>=4096)return false; @@ -30,6 +43,7 @@ public sealed class ContextWindows(TimeProvider clock) { var now=clock.GetUtcNow(); foreach(var key in launches.Where(x=>x.Value<=now).Select(x=>x.Key).ToArray())launches.Remove(key); + foreach(var key in contextLaunches.Where(x=>x.Value<=now).Select(x=>x.Key).ToArray())contextLaunches.Remove(key); foreach(var key in leases.Where(x=>now-x.Value.Seen>TimeSpan.FromSeconds(60)).Select(x=>x.Key).ToArray())leases.Remove(key); foreach(var key in pending.Where(x=>x.Value.Expires<=now).Select(x=>x.Key).ToArray())pending.Remove(key); } diff --git a/PlotLine/Views/NativeWorkspace/ContextLaunch.cshtml b/PlotLine/Views/NativeWorkspace/ContextLaunch.cshtml new file mode 100644 index 00000000..c96e38e9 --- /dev/null +++ b/PlotLine/Views/NativeWorkspace/ContextLaunch.cshtml @@ -0,0 +1,10 @@ +@model PlotLine.Controllers.NativeWorkspaceModel +@{ ViewData["Title"]="Open Context"; } +
+

Context

+

Checking your Context windows for this book…

+ +
+@section Scripts { + +} diff --git a/PlotLine/wwwroot/js/context-windows.js b/PlotLine/wwwroot/js/context-windows.js index ee28662f..5d10c55f 100644 --- a/PlotLine/wwwroot/js/context-windows.js +++ b/PlotLine/wwwroot/js/context-windows.js @@ -31,6 +31,7 @@ }catch{fallback(node,command,'unavailable');}} function complete(node,command,status){if(!node?.isConnected)return;if(status==='focused')node.textContent='Reference focused in the selected tool. Word position is unchanged.';else fallback(node,command,status);} connection?.on('ContextWindowsChanged',()=>void discover()); + connection?.on('ContextWindowRequested',()=>{window.focus();}); connection?.on('ContextInteraction',async delivery=>{let status='unavailable';try{if(delivery.command.bookID===controller.announcement.bookID)status=await controller.receiveInteraction(delivery);}catch{status='unavailable';}void connection.invoke('CompleteContextInteraction',delivery.commandID,status).catch(()=>{});}); connection?.on('ContextInteractionResult',result=>{const item=pending.get(result.commandID);if(item?.node){complete(item.node,item.command,result.status);pending.delete(result.commandID);}else pending.set(result.commandID,{status:result.status,expires:Date.now()+20000});}); root.addEventListener('context-connection-ready',()=>{pending.clear();void register();}); diff --git a/PlotLine/wwwroot/js/native-context-launch.js b/PlotLine/wwwroot/js/native-context-launch.js new file mode 100644 index 00000000..3d2419a7 --- /dev/null +++ b/PlotLine/wwwroot/js/native-context-launch.js @@ -0,0 +1,28 @@ +// Reuse My Windows in this authenticated browser environment. Opening never publishes focus. +(() => { + 'use strict'; + const root=document.querySelector('[data-native-context-launch]');if(!root)return; + const message=root.querySelector('[data-context-launch-status]'),retry=root.querySelector('[data-context-launch-retry]'); + const windowID=crypto.randomUUID(),bookID=Number(root.dataset.book);let running=false,finished=false; + async function open(){ + const connection=window.PlotDirectorPresenceConnection,environmentID=window.PlotDirectorContextEnvironment; + if(running||finished||connection?.state!=='Connected')return; + if(!environmentID){message.textContent='Context window discovery requires browser storage. No additional window was opened.';return;} + running=true;retry.hidden=true; + try{ + await connection.invoke('RegisterContextWindow',{version:1,bookID,windowID,environmentID,panes:[]}); + const result=await connection.invoke('OpenContextWindow',bookID); + if(result==='open'){ + const url=new URL('/Writing/Context',location.origin); + for(const key of ['book','project','instance','session'])if(root.dataset[key])url.searchParams.set(key+'Id',root.dataset[key]); + finished=true;location.replace(url.href); + }else if(result==='reused'||result==='pending'){ + finished=true;message.textContent=result==='reused'?'Context is already open. Its layout, tools, Hold and position were retained.':'A Context window is already opening for this book.'; + window.close(); + } + }catch{message.textContent='Context window discovery is unavailable. Reconnect and retry; no other window was changed.';retry.hidden=false;} + finally{running=false;} + } + document.addEventListener('pd-presence-ready',()=>void open()); + retry.addEventListener('click',()=>void open());void open(); +})();