Complete native shared-focus ribbon and reuse scoped Context windows

This commit is contained in:
nick 2026-11-23 14:45:36 +00:00
parent 2d60e2a90a
commit 898a97f730
17 changed files with 135 additions and 19 deletions

View File

@ -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;

View File

@ -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);

View File

@ -1 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.44</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.45</ApplicationVersion></PropertyGroup></Project>

View File

@ -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);

View File

@ -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);

View File

@ -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)]

View File

@ -7,10 +7,9 @@
<editBox id="PlotDirectorChapter" label="Chapter" getText="GetChapterTip" getSupertip="GetChapterTip" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" />
<editBox id="PlotDirectorScene" label="Scene" getText="GetSceneTip" getSupertip="GetSceneTip" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" />
</group>
<group id="PlotDirectorSharedFocus" label="Manuscript focus"><toggleButton id="PlotDirectorHold" label="Hold / Follow" imageMso="Lock" getPressed="GetFocusHeld" onAction="ToggleFocusHold" getSupertip="GetFocusTip"/><editBox id="PlotDirectorFocusState" label="State" getText="GetFocusState" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMM"/></group>
<group id="PlotDirectorSharedFocus" label="Manuscript focus"><toggleButton id="PlotDirectorHold" getLabel="GetFocusAction" imageMso="Lock" getPressed="GetFocusHeld" onAction="ToggleFocusHold" getSupertip="GetFocusTip"/><editBox id="PlotDirectorFocusState" label="State" getText="GetFocusState" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMM"/></group>
<group id="PlotDirectorWriting" label="Writing">
<button id="PlotDirectorContext" label="Writing Context" size="large" imageMso="ReadingMode" onAction="OpenContext" getEnabled="CanOpenBook" />
<button id="PlotDirectorIntent" label="Writing Intent" size="large" imageMso="ReviewNewComment" onAction="OpenIntent" getEnabled="CanOpenBook" />
<button id="PlotDirectorContext" label="Context" size="large" imageMso="ReadingMode" onAction="OpenContext" getEnabled="CanOpenBook" />
<button id="PlotDirectorWeb" label="PlotDirector" size="large" imageMso="HyperlinkInsert" onAction="OpenPlotDirector" getEnabled="CanOpenBook" />
</group>
<group id="PlotDirectorCompanion" label="Companion">

View File

@ -17,7 +17,11 @@ namespace PlotDirector.WordAddIn
private FocusWindowState FocusWindow(Word.Window window){var handle=Com(()=>window.Hwnd);FocusWindowState state;if(!focusWindows.TryGetValue(handle,out state))focusWindows[handle]=state=new FocusWindowState();return state;}
private FocusWindowState ActiveFocusWindow(){Word.Window window=null;try{window=Com(()=>application.ActiveWindow);return window==null?null:FocusWindow(window);}catch(COMException){return null;}finally{Release(window);}}
public bool FocusHeld=>ActiveFocusWindow()?.Held==true;
public string FocusStateLabel=>FocusHeld?"Held · Release Hold":sharedFocusStatus=="word-unmapped"?"Following · mapping unavailable":sharedFocusStatus=="save-required"?"Following · save Word first":sharedFocusStatus=="word-busy"?"Following · Word busy":"Following · Hold available";
public bool WindowFocusHeld(object context){var window=context as Word.Window;try{return window!=null?FocusWindow(window).Held:FocusHeld;}finally{Release(window);}}
public string FocusWindowKey=>ActiveFocusWindow()?.Id.ToString()??"";
private string FollowingFocusLabel=>sharedFocusStatus=="word-unmapped"?"Following · mapping unavailable":sharedFocusStatus=="save-required"?"Following · save Word first":sharedFocusStatus=="word-busy"?"Following · Word busy":"Following · Hold available";
public string FocusStateLabel=>FocusHeld?"Held · Release Hold":FollowingFocusLabel;
public string WindowFocusState(object context)=>WindowFocusHeld(context)?"Held · Release Hold":FollowingFocusLabel;
public void SetFocusHeld(bool held){var state=ActiveFocusWindow();if(state==null)return;state.Hold(held);deliberateFocusPending=false;scheduler.Post("selection",CaptureSelection);invalidateRibbon?.Invoke();}
private void MarkDeliberateFocus(){uint process;GetWindowThreadProcessId(GetForegroundWindow(),out process);if(applyingFocus||process!=focusProcessId)return;foreach(var key in new[]{1,37,38,39,40,33,34,35,36,9})if((GetAsyncKeyState(key)&0x8000)!=0){deliberateFocusPending=true;deliberateFocusWindow=ActiveFocusWindow()?.Id??Guid.Empty;break;}}
private Message FocusObservation(Word.Document document,int start,int end){var state=ActiveFocusWindow();var pending=deliberateFocusPending&&state?.Id==deliberateFocusWindow;deliberateFocusPending=false;bool any=false;Word.Windows windows=null;var alive=new HashSet<int>();try{windows=Com(()=>application.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);alive.Add(Com(()=>window.Hwnd));}finally{Release(window);}}foreach(var handle in focusWindows.Keys.Where(k=>!alive.Contains(k)).ToArray())focusWindows.Remove(handle);Release(windows);windows=Com(()=>document.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);if(!FocusWindow(window).Held)any=true;}finally{Release(window);}}}finally{Release(windows);}return new Message{CanSharedFocus=true,FocusWindowID=state?.Id??Guid.Empty,FocusHeld=state?.Held==true,AnyFollowingWindows=any,FocusModeRequest=state?.ModeRequest??Guid.Empty,DeliberateFocusSequence=state?.Observe(start,end,pending&&!applyingFocus)??0};}

View File

@ -1,7 +1,7 @@
{
"version": "1.0.0.44",
"msiVersion": "1.0.44",
"productCode": "{8245E12F-39A8-4FC3-B1A0-9FB6AEB62F1A}",
"version": "1.0.0.45",
"msiVersion": "1.0.45",
"productCode": "{C9797E15-A318-48BF-95B8-1769AEBCA565}",
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
"atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d",
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",

View File

@ -0,0 +1,37 @@
// Isolated production launch asset: no account, database, native process or manuscript.
const {chromium}=require('playwright');
const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
const script=fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-context-launch.js'),'utf8');
(async()=>{
const browser=await chromium.launch();
try{
for(const outcome of ['open','reused','pending','failure','no-storage']){
const context=await browser.newContext(),page=await context.newPage();
await page.route('https://fixture.invalid/**',route=>route.fulfill({contentType:'text/html',body:'<p>Context destination</p>'}));
await page.goto('https://fixture.invalid/launch');
await page.setContent('<main data-native-context-launch data-book="12" data-project="3" data-instance="instance" data-session="session"><p data-context-launch-status></p><button data-context-launch-retry hidden>Retry</button></main>');
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;});

View File

@ -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");
}
}

View File

@ -15,7 +15,8 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
public async Task<IActionResult> 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")]

View File

@ -32,6 +32,13 @@ public sealed class NativeCompanionPresenceHub(ContextWindows windows,IWordCompa
public async Task<bool> 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<ContextConnectedWindow[]> MyContextWindows(int bookId){await Book(bookId);return windows.List(Author,bookId);}
public async Task<string> 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<ContextInteractionResult> SendContextInteraction(ContextInteraction command)
{
if(command==null||command.Version!=1||command.TargetUserID.HasValue||!ContextWindows.Actions.Contains(command.Action))throw new HubException("Unsupported interaction.");

View File

@ -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);
}

View File

@ -0,0 +1,10 @@
@model PlotLine.Controllers.NativeWorkspaceModel
@{ ViewData["Title"]="Open Context"; }
<main class="container py-4" data-native-context-launch data-book="@Model.Book" data-project="@Model.Project" data-instance="@Model.Instance" data-session="@Model.Session">
<h1>Context</h1>
<p role="status" data-context-launch-status>Checking your Context windows for this book…</p>
<button type="button" class="btn btn-primary" data-context-launch-retry hidden>Retry</button>
</main>
@section Scripts {
<script src="~/js/native-context-launch.js" asp-append-version="true" defer></script>
}

View File

@ -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();});

View File

@ -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();
})();