Add same-user book-scoped My Windows interactions to Context

This commit is contained in:
Nick Beckley 2026-11-22 15:06:21 +00:00
parent bd3ebd0deb
commit 16c05055fa
14 changed files with 287 additions and 14 deletions

View File

@ -0,0 +1,27 @@
# Unified Context enhancement programme
22 November 2026. Development only. Production is outside scope. Existing untracked investigation/audit documents are preserved.
## Existing-system audit and reuse decisions
- `WritingController`, `Context.cshtml`, `context-workspace.js`: established two-pane shell, declared endpoints/scopes/lifecycle, shared native notification connection, HTTP partials, generation guards, dirty/busy deferral and independent local state. Extend these; do not add a second workspace or connection.
- `StoryPointContextService.GetAsync/Compose` and `StoryStateService.OrderScenes`: canonical narrative ordering and bounded established knowledge/relationship state. `ICharacterRepository.GetTimelineAsync` already batches character appearances. A focused Context read projection can combine these for previous/next appearances without changing canonical story state. Future location records must remain explicitly author reference, never current viewpoint knowledge.
- `ICharacterService`: canonical identity, alias, scene appearance and relationship-event reads/saves. Existing character editor supports name, aliases, importance, description and many unrelated fields. Focused modals must hydrate the canonical edit model, change only the chosen field, and reuse these saves rather than posting replacement editor models.
- Classifications: manual create currently leaves importance null (timeline fallback). `CharacterLanePriority` can use role/count as display ranking; that must not be presented as explicit author classification. The core structural-import character INSERT in migration 162 sets new characters to 8 (Major); a forward-only correction for new records is needed. Existing classifications must not be bulk-updated.
- `NamesController` / `INameIntelligenceService`: canonical Unicode normalization, reference recognition, related forms, locale/era/gender/used-name searches and full Names workspace already exist. Use them for suggestions. Canonical aliases have individual-character repository reads; a bounded batched project read is the only missing read shape needed for a responsive alias catalogue. No existing general project-name near-match engine has been established; do not substitute a new generator.
- `IRelationshipMapService.GetAsync` / `BuildAtScene`: existing narrative-point projection, category, direction, reciprocal state, intensity and recorded event history. `CharacterRelationship` and `RelationshipType` retain family categories; family/narrative tracks must remain distinct. First meeting is displayed only when explicitly recorded, not inferred from co-occurrence.
- `RelationshipMapController.Save` and `ICharacterService.SaveInitialRelationshipAsync/AddRelationshipEventAsync/UpdateRelationshipEventAsync`: focused existing relationship persistence. Context must validate scope, permitted edit access, entity IDs, lookups and existing relationship ownership before invoking them.
- `ProjectAccessService`, `ProjectAccessFilter`, project collaboration: existing access checks and Owner/Collaborator membership. The new interaction registry is strictly per authenticated user/book, separate from project membership/collaboration. No cross-user command path is enabled. Focused writes will conservatively require owner permission where the existing model exposes no finer write permission, rather than inventing a read/write role.
- Shared notifications: `_WritingCompanionLayout` owns `_ToastHost`, `notifications.js` and `word-notifications.js` outside replaceable content. Explicit save outcomes toast in the initiating window only; incoming invalidations remain quiet. Inline validation and recovery remain in the modal.
## Phase 1: My Windows
The existing `/hubs/native-companion` connection additionally supports version-1 Context registration, discovery, targeted interaction and acknowledgements. `ContextWindows` is ephemeral presence/capability state, not another character/name/relationship service. It expires stale leases after 60 seconds, removes disconnects, and bounds registrations/pending commands. Registration and command methods independently authorize the book; canonical IDs are checked against its project and story point.
Only visible, loaded, clean panes advertise supported action names. Routing prefers an eligible pane in the originating connection, then another same-user/book connection. Explicit window/session/pane targets stay within that scope. No unrelated tool is switched. Missing, busy, expired or unavailable handlers return explicit outcomes. Receiver re-reads its authorized HTTP partial before tool-specific focus handling; it never sets the manuscript scene or calls Word navigation. Receipt acknowledgements are accepted only from the selected recipient.
Contract: version, book ID, originating pane, action, canonical character/location/relationship ID as applicable, chapter/scene story point, optional target window/session/pane. Reserved target-user routing is rejected in version 1. Commands contain no manuscript text or display-name matching. Saved-data `ContextInvalidated` events remain separate from interaction commands.
My Windows shows current capabilities and offers a scene-focus demonstration. Overview and Characters are minimal non-destructive handlers; later phases extend them. Pinned snapshots retain their existing no-live-connection semantics and explicitly explain that My Windows requires a live Context window. Reconnect re-registers current visible capability state and recovers manuscript authority through the existing foundation mechanisms; missed commands are not replayed.
Qualification and deployment evidence will be appended as each phase completes. Physical cross-device/Word/installed-PWA acceptance is not implied by browser-session automation.

View File

@ -0,0 +1,30 @@
// Real SignalR transport. Isolated loopback data by default; opt-in real Development uses disposable identity/scope.
const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
const live=!!process.env.PD_CONTEXT_IDENTITY,base=live?'https://dev.plotdirector.com':(process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238');
(async()=>{const browser=await chromium.launch();let step='setup';try{
const scope=live?JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE)):{project:7,book:12,chapter:10,scene:22};
const who=live?JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)):null;
if(live){assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,scope.user);assert(who.Email.startsWith('pwa-browser-'));}
const contexts=[];const pages=[];const counts=[];
for(let i=0;i<2;i++){
const context=await browser.newContext({viewport:{width:1366,height:768}});contexts.push(context);
if(!live){await context.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await context.route('**/native-companion/status',r=>r.fulfill({json:[]}));await context.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected'}}));await context.route('**/Writing/Context/Position?*',r=>r.fulfill({json:{connected:false,position:null}}));await context.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});}
const page=await context.newPage();pages.push(page);const count={hub:0,word:0,reads:0};counts.push(count);page.on('request',r=>{if(r.url().includes('/hubs/')&&r.url().includes('/negotiate'))count.hub++;if(r.url().includes('/Writing/Context/Navigate')||r.url().includes('/WriterWord/Navigate'))count.word++;if(r.url().includes('/Writing/Context/Tabs/'))count.reads++;});
if(live){await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(who.Email);await page.locator('[name=Password]').fill(who.Password);await Promise.all([page.waitForURL(u=>u.pathname!=='/Account/Login'),page.locator('button[type=submit]').click()]);}
await page.goto(`${base}/Writing/Context?projectId=${scope.project}&bookId=${scope.book}&sceneId=${scope.scene}`);await page.waitForSelector('[data-context-tab-fragment]');await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected');
}
const [source,destination]=pages;
step='two independently authenticated browser sessions';await source.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(w=>w.length===2&&w.every(x=>x.panes[0].available)),scope.book);
const target=await destination.evaluate(()=>({windowID:document.querySelector('[data-context-workspace]').contextController.windowId,connection:document.querySelector('[data-context-workspace]').contextController.connection.connectionId}));
const command={version:1,bookID:scope.book,originPaneID:'0',action:'scene.focus',storyPoint:{chapterID:scope.chapter,sceneID:scope.scene},targetWindowID:target.windowID,targetSessionID:target.connection,targetPaneID:'0'};
await source.evaluate(()=>{window.receipts=[];document.querySelector('[data-context-workspace]').contextController.connection.on('ContextInteractionResult',r=>receipts.push(r));});
const before=counts.map(x=>x.reads),position=await source.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position);
step='targeted command and authoritative recipient read';const result=await source.evaluate(c=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c),command);assert.equal(result.status,'delivered');await destination.waitForSelector('.context-reference-focus');await source.waitForFunction(()=>receipts.some(r=>r.status==='focused'));
assert.equal(counts[0].reads,before[0]);assert.equal(counts[1].reads,before[1]+1);assert.equal(await source.locator('.context-reference-focus').count(),0);assert.deepEqual(await source.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position),position);assert(counts.every(x=>x.word===0&&x.hub===1));
step='no-handler does not replace a tool';await destination.selectOption('[data-context-pane="0"] [data-context-tab]','characters');await destination.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',Number(document.querySelector('[data-context-workspace]').dataset.scopeBookId)).then(rows=>rows.find(r=>r.windowID===document.querySelector('[data-context-workspace]').contextController.windowId)?.panes[0].toolID==='characters'));
const absent=await source.evaluate(c=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c),command);assert.equal(absent.status,'no-handler');assert.equal(await destination.locator('[data-context-tab]').first().inputValue(),'characters');
step='cross-user and cross-book rejection';for(const change of [{targetUserID:999},{bookID:2147483647},{storyPoint:{chapterID:scope.chapter,sceneID:2147483647}}])assert(await source.evaluate(async c=>{try{await document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c);return false}catch{return true}},{...command,...change}));
step='disconnect and reconnect registration';await destination.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.connection.stop());await source.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(w=>w.length===1),scope.book);await destination.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await source.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(w=>w.length===2),scope.book);
assert.equal(await destination.locator('[data-context-tab]').first().inputValue(),'characters');assert.equal(counts[1].word,0);
for(const context of contexts)await context.close();console.log('PASS My Windows real SignalR: two independent sessions, exact recipient and pane read, no unrelated mutation/Word navigation, no-handler, cross-user/book/story-point rejection and reconnect capability recovery'+(live?' on Development':' in isolated host'));
} catch(error){console.error('FAILED '+step+': '+error.message);process.exitCode=1;}finally{await browser.close();}})();

View File

@ -0,0 +1,27 @@
using PlotLine.Services.Context;
internal static class ContextWindowsTests
{
private sealed class Clock:TimeProvider {public DateTimeOffset Now=DateTimeOffset.UtcNow;public override DateTimeOffset GetUtcNow()=>Now;}
private static void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS My Windows: "+message);}
public static void Run()
{
var clock=new Clock();var store=new ContextWindows(clock);var first=Guid.NewGuid();var second=Guid.NewGuid();
ContextWindowRegistration Registration(Guid id,int book,string action,bool available=true)=>new(1,book,id,[new("0","reference",[action],available)]);
store.Register(7,"origin",Registration(first,12,"scene.focus"));store.Register(7,"remote-device",Registration(second,12,"scene.focus"));
store.Register(8,"other-user",Registration(Guid.NewGuid(),12,"scene.focus"));store.Register(7,"other-book",Registration(Guid.NewGuid(),13,"scene.focus"));
var command=new ContextInteraction(1,12,"0","scene.focus",StoryPoint:new(10,22));
Check(store.List(7,12).Length==2,"discovery is isolated by account and book");
var local=store.Route(7,"origin",command)!.Value;Check(local.Window.Connection=="origin","suitable local pane is preferred");
var remote=store.Route(7,"origin",command with{TargetWindowID=second})!.Value;Check(remote.Window.Connection=="remote-device","explicit recipient is targeted without broadcasting");
Check(store.Complete(7,"origin",remote.CommandID)==null,"another connection cannot acknowledge a recipient's command");
Check(store.Complete(7,"remote-device",remote.CommandID)=="origin","only the selected recipient acknowledges delivery");
Check(store.Route(7,"origin",command with{Action="location.focus",LocationID=20})==null,"no-handler is explicit and does not replace a tool");
try{store.Route(7,"origin",command with{TargetUserID=8});throw new Exception("Cross-user request accepted");}catch(ArgumentException){Check(true,"cross-user commands are disabled");}
try{store.Route(7,"origin",command with{BookID=13});throw new Exception("Cross-book request accepted");}catch(ArgumentException){Check(true,"origin registration cannot cross books");}
store.Register(7,"origin",Registration(first,12,"scene.focus",false));Check(store.Route(7,"origin",command)!.Value.Window.Connection=="remote-device","busy local pane is bypassed without mutation");
store.Remove("remote-device");Check(store.Route(7,"origin",command)==null,"disconnect removes eligible destinations");
clock.Now+=TimeSpan.FromSeconds(61);Check(store.List(7,12).Length==0,"missed disconnects expire on authoritative discovery");
store.Register(7,"reconnected",Registration(first,12,"scene.focus"));Check(store.List(7,12).Length==1,"reconnection registers current capability state");
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");}
}
}

View File

@ -182,8 +182,11 @@ if(args.Contains("--sql-architecture-inventory")){Console.WriteLine(System.Text.
if(args.Contains("--native-review-navigation")){await NativeReviewNavigationTests.Run();Console.WriteLine("PASS historical review navigation session/content guards and acknowledgements");return;}
if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;}
var tests = new (string Name, Action Test)[]
{
("Context My Windows routing and lifecycle",ContextWindowsTests.Run),
("Settlement boundaries preserve anchors, routes and backup/import contracts",MapSettlementTests.Run),
("Shared boundary topology preserves map and project contracts",MapTopologyTests.Run),
("Geographical roots, providers, queue outcomes and access", () => GeographyTests.Run().GetAwaiter().GetResult()),

View File

@ -141,6 +141,11 @@ internal static class ToolbarBrowserHost
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationGuidanceService>();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationService>();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<PlotLine.Services.Context.ContextWindows>();
builder.Services.AddSingleton(FixtureProxy<IWordCompanionRepository>((name,args)=>Task.FromResult<WordCompanionBookStructureResponse?>((int)args![0]! is 12 or 13?new(){BookId=(int)args[0]!,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]},new(){ChapterId=11,Scenes=[new(){SceneId=23}]}]}:null)));
builder.Services.AddSingleton(FixtureProxy<ICharacterRepository>((name,args)=>name=="GetCharacterAsync"?Task.FromResult<Character?>((int)args![0]! ==5?new(){CharacterID=5,ProjectID=7,CharacterName="Fixture participant"}:null):throw new NotSupportedException(name)));
builder.Services.AddSingleton(FixtureProxy<ILocationRepository>((name,args)=>name=="GetAsync"?Task.FromResult<LocationItem?>((int)args![0]! ==77?new(){LocationID=77,ProjectID=7,LocationName="Saved room"}:null):throw new NotSupportedException(name)));
builder.Services.AddSingleton<IWordCompanionPresenceService, WordCompanionPresenceService>();
builder.Services.AddSingleton(FixtureProxy<IOnboardingRepository>((name, args) => throw new NotSupportedException(name)));
builder.Services.AddSingleton(FixtureProxy<IOnboardingBuildRepository>((name, args) => throw new NotSupportedException(name)));
@ -701,6 +706,7 @@ internal static class ToolbarBrowserHost
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync("<!doctype html><html lang='en' data-app-theme='" + initialTheme + "' data-theme='" + (initialTheme.EndsWith("dark") ? "dark" : "light") + "'><head><script src='/js/application-display-mode.js'></script><link rel='manifest' href='/site.webmanifest'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'><link rel='stylesheet' href='/css/onboarding.css'></head><body data-pd-user-id='" + context.User.FindFirstValue(ClaimTypes.NameIdentifier) + "' data-pd-project-id='7' class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><template data-pwa-initial-contributions>" + contributions + "</template><link rel='stylesheet' href='/css/scene-explorer.css'><script src='/js/scene-explorer.js'></script><script src='/js/narrative-focus.js' defer></script><script src='/js/narrative-focus-workspaces.js' defer></script><script src='/js/application-page-context.js'></script><div class='plotline-help-main'><div class='container-fluid plotline-shell " + (recordLayout is null ? "pd-dashboard-shell" : $"pd-record-canvas pd-record-canvas--{recordLayout}") + "'><main data-pwa-page-content class='pb-3'>" + surface + "</main><script>window.PlotDirectorPageContext?.activate();</script></div></div><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script>" + appearanceScript + "<script src='/js/application-shell.js'></script><script src='/js/application-theme-sync.js'></script><script src='/js/site.js'></script><script src='/js/application-pwa.js'></script><script src='/js/application-context-menu.js'></script>" + writerScripts + "</body></html>");
});
app.MapHub<PlotLine.Hubs.NativeCompanionPresenceHub>("/hubs/native-companion");
app.MapHub<PlotLine.Hubs.WordCompanionFollowHub>("/hubs/word-companion-follow");
await app.RunAsync();
}

View File

@ -1,11 +1,60 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using PlotLine.Data;
using PlotLine.Services.Context;
namespace PlotLine.Hubs;
// Cookie-authenticated native and Context notifications. No Word commands or client-chosen groups.
// The existing browser connection carries presence, saved-data invalidation and targeted Context interactions.
[Authorize]
public sealed class NativeCompanionPresenceHub:Hub
public sealed class NativeCompanionPresenceHub(ContextWindows windows,IWordCompanionRepository access,IBookRepository books,
ICharacterRepository characters,ILocationRepository locations):Hub
{
public static string UserGroup(int user)=>"native-presence:user:"+user;
public override async Task OnConnectedAsync(){if(!int.TryParse(Context.User?.FindFirstValue(ClaimTypes.NameIdentifier),out var user)){Context.Abort();return;}await Groups.AddToGroupAsync(Context.ConnectionId,UserGroup(user));await base.OnConnectedAsync();}
private int Author=>int.TryParse(Context.User?.FindFirstValue(ClaimTypes.NameIdentifier),out var user)?user:throw new HubException("Sign in again.");
public override async Task OnConnectedAsync(){await Groups.AddToGroupAsync(Context.ConnectionId,UserGroup(Author));await base.OnConnectedAsync();}
private async Task<PlotLine.Models.WordCompanionBookStructureResponse> Book(int book)
=> await access.GetBookStructureAsync(book,Author)??throw new HubException("Book unavailable.");
public async Task<ContextConnectedWindow[]> RegisterContextWindow(ContextWindowRegistration registration)
{
if(registration==null)throw new HubException("Invalid registration.");await Book(registration.BookID);
var prior=windows.Read(Context.ConnectionId);
try{windows.Register(Author,Context.ConnectionId,registration);}catch(Exception e)when(e is ArgumentException or InvalidOperationException){throw new HubException(e.Message);}
if(prior!=null&&prior.Registration.BookID!=registration.BookID){await Groups.RemoveFromGroupAsync(Context.ConnectionId,ContextWindows.Group(Author,prior.Registration.BookID));await Clients.Group(ContextWindows.Group(Author,prior.Registration.BookID)).SendAsync("ContextWindowsChanged");}
await Groups.AddToGroupAsync(Context.ConnectionId,ContextWindows.Group(Author,registration.BookID));
// Registration is also a heartbeat; only discovery changes need a broadcast.
if(prior==null||prior.Registration.BookID!=registration.BookID||prior.Registration.WindowID!=registration.WindowID||!System.Text.Json.JsonSerializer.Serialize(prior.Registration.Panes).Equals(System.Text.Json.JsonSerializer.Serialize(registration.Panes)))
await Clients.Group(ContextWindows.Group(Author,registration.BookID)).SendAsync("ContextWindowsChanged");
return windows.List(Author,registration.BookID);
}
public async Task<ContextConnectedWindow[]> MyContextWindows(int bookId){await Book(bookId);return windows.List(Author,bookId);}
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.");
var structure=await Book(command.BookID);var book=await books.GetAsync(command.BookID)??throw new HubException("Book unavailable.");
if(command.StoryPoint is {} point&&((point.ChapterID.HasValue&&!structure.Chapters.Any(c=>c.ChapterId==point.ChapterID))||
(point.SceneID.HasValue&&!structure.Chapters.Any(c=>(!point.ChapterID.HasValue||c.ChapterId==point.ChapterID)&&c.Scenes.Any(s=>s.SceneId==point.SceneID)))))throw new HubException("Invalid story point.");
var allowed=command.Action switch {
"character.focus"=>command.CharacterID is >0&&(await characters.GetCharacterAsync(command.CharacterID.Value))?.ProjectID==book.ProjectID,
"location.focus" or "location.focusAtStoryPoint"=>command.LocationID is >0&&(await locations.GetAsync(command.LocationID.Value))?.ProjectID==book.ProjectID,
"relationship.focus"=>command.RelationshipID is >0&&(await characters.GetRelationshipAsync(command.RelationshipID.Value))?.ProjectID==book.ProjectID,
"scene.focus"=>command.StoryPoint?.SceneID is >0,
_=>false};
if(!allowed)throw new HubException("Reference unavailable in this book's project.");
(ContextWindowLease Window,ContextPaneCapability Pane,Guid CommandID)? target;
try{target=windows.Route(Author,Context.ConnectionId,command);}catch(Exception e)when(e is ArgumentException or InvalidOperationException){throw new HubException(e.Message);}
if(target==null)return new("no-handler");
await Clients.Client(target.Value.Window.Connection).SendAsync("ContextInteraction",new ContextInteractionDelivery(target.Value.CommandID,command,target.Value.Pane.PaneID));
return new("delivered",target.Value.CommandID);
}
public async Task CompleteContextInteraction(Guid commandId,string status)
{
if(status is not ("focused" or "not-visible" or "busy" or "unavailable"))throw new HubException("Invalid result.");
var origin=windows.Complete(Author,Context.ConnectionId,commandId);if(origin!=null)await Clients.Client(origin).SendAsync("ContextInteractionResult",new ContextInteractionResult(status,commandId));
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
var prior=windows.Remove(Context.ConnectionId);if(prior!=null)await Clients.Group(ContextWindows.Group(prior.User,prior.Registration.BookID)).SendAsync("ContextWindowsChanged");
await base.OnDisconnectedAsync(exception);
}
}

View File

@ -288,7 +288,9 @@ public class Program
builder.Services.AddScoped<IImportService, ImportService>();
builder.Services.AddScoped<IWordCompanionService, WordCompanionService>();
builder.Services.AddSingleton<IWordCompanionPresenceService, WordCompanionPresenceService>();
builder.Services.Configure<Microsoft.AspNetCore.SignalR.HubOptions<PlotLine.Hubs.NativeCompanionPresenceHub>>(options => options.MaximumReceiveMessageSize = 16384);
builder.Services.AddSingleton<ContextWorkspaceNotifications>();
builder.Services.AddSingleton<PlotLine.Services.Context.ContextWindows>();
builder.Services.AddSingleton<IManuscriptScanPreviewStore, ManuscriptScanPreviewStore>();
builder.Services.AddSingleton<IOnboardingStoryIntelligenceBatchStore, OnboardingStoryIntelligenceBatchStore>();
builder.Services.AddHostedService<WordCompanionPresenceMonitor>();

View File

@ -0,0 +1,59 @@
namespace PlotLine.Services.Context;
public sealed record ContextPaneCapability(string PaneID, string ToolID, string[] Actions, bool Available = true);
public sealed record ContextWindowRegistration(int Version, int BookID, Guid WindowID, ContextPaneCapability[] Panes);
public sealed record ContextConnectedWindow(Guid WindowID, string SessionID, int BookID, ContextPaneCapability[] Panes, DateTimeOffset LastSeen);
public sealed record ContextStoryPoint(int? ChapterID, int? SceneID);
public sealed record ContextInteraction(int Version, int BookID, string OriginPaneID, string Action,
int? CharacterID = null, int? LocationID = null, int? RelationshipID = null, ContextStoryPoint? StoryPoint = null,
Guid? TargetWindowID = null, string? TargetPaneID = null, int? TargetUserID = null, string? TargetSessionID = null);
public sealed record ContextInteractionDelivery(Guid CommandID, ContextInteraction Command, string PaneID);
public sealed record ContextInteractionResult(string Status, Guid? CommandID = null);
public sealed record ContextWindowLease(int User, string Connection, ContextWindowRegistration Registration, DateTimeOffset Seen);
public sealed record ContextPendingCommand(int User, int Book, string Origin, string Target, DateTimeOffset Expires);
// Ephemeral interaction discovery, not durable manuscript or collaboration state.
public sealed class ContextWindows(TimeProvider clock)
{
private readonly object gate = new();
private readonly Dictionary<string,ContextWindowLease> leases = [];
private readonly Dictionary<Guid,ContextPendingCommand> pending = [];
public static readonly string[] Actions = ["character.focus", "location.focus", "location.focusAtStoryPoint", "relationship.focus", "scene.focus"];
public static string Group(int user,int book) => $"context-windows:{user}:{book}";
private void Prune()
{
var now=clock.GetUtcNow();
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);
}
public ContextWindowLease? Read(string connection) { lock(gate){Prune();return leases.GetValueOrDefault(connection);} }
public void Register(int user,string connection,ContextWindowRegistration registration)
{
if(registration.Version!=1||registration.BookID<=0||registration.WindowID==Guid.Empty||registration.Panes==null||registration.Panes.Length>2||
registration.Panes.Any(p=>p==null||p.PaneID is not ("0" or "1")||string.IsNullOrWhiteSpace(p.ToolID)||p.ToolID.Length>48||p.Actions==null||p.Actions.Length>Actions.Length||p.Actions.Any(a=>!Actions.Contains(a)))||
registration.Panes.Select(p=>p.PaneID).Distinct().Count()!=registration.Panes.Length)throw new ArgumentException("Invalid Context registration.");
lock(gate){Prune();if(!leases.ContainsKey(connection)&&(leases.Count>=4096||leases.Values.Count(x=>x.User==user)>=32))throw new InvalidOperationException("Too many Context windows.");
leases[connection]=new(user,connection,registration,clock.GetUtcNow());}
}
public ContextWindowLease? Remove(string connection) {lock(gate){var prior=leases.GetValueOrDefault(connection);leases.Remove(connection);foreach(var id in pending.Where(x=>x.Value.Target==connection||x.Value.Origin==connection).Select(x=>x.Key).ToArray())pending.Remove(id);return prior;}}
public ContextConnectedWindow[] List(int user,int book)
{
lock(gate){Prune();return leases.Values.Where(x=>x.User==user&&x.Registration.BookID==book).OrderByDescending(x=>x.Seen)
.Select(x=>new ContextConnectedWindow(x.Registration.WindowID,x.Connection,x.Registration.BookID,x.Registration.Panes,x.Seen)).ToArray();}
}
public (ContextWindowLease Window,ContextPaneCapability Pane,Guid CommandID)? Route(int user,string origin,ContextInteraction command)
{
lock(gate){Prune();var source=leases.GetValueOrDefault(origin);
if(source?.User!=user||source.Registration.BookID!=command.BookID||command.Version!=1||command.TargetUserID.HasValue||!Actions.Contains(command.Action)||!source.Registration.Panes.Any(p=>p.PaneID==command.OriginPaneID))throw new ArgumentException("Invalid interaction scope.");
var targets=leases.Values.Where(x=>x.User==user&&x.Registration.BookID==command.BookID&&(!command.TargetWindowID.HasValue||x.Registration.WindowID==command.TargetWindowID)&&(string.IsNullOrWhiteSpace(command.TargetSessionID)||x.Connection==command.TargetSessionID))
.OrderByDescending(x=>x.Connection==origin).ThenByDescending(x=>x.Seen);
foreach(var target in targets){var pane=target.Registration.Panes.FirstOrDefault(p=>p.Available&&p.Actions.Contains(command.Action)&&(string.IsNullOrWhiteSpace(command.TargetPaneID)||p.PaneID==command.TargetPaneID));
if(pane==null)continue;if(pending.Values.Count(x=>x.Origin==origin)>=16)throw new InvalidOperationException("Wait for pending Context commands.");
var id=Guid.NewGuid();pending[id]=new(user,command.BookID,origin,target.Connection,clock.GetUtcNow().AddSeconds(20));return(target,pane,id);}
return null;}
}
public string? Complete(int user,string connection,Guid id)
{
lock(gate){Prune();if(!pending.TryGetValue(id,out var command)||command.User!=user||command.Target!=connection)return null;pending.Remove(id);return command.Origin;}
}
}

View File

@ -5,8 +5,8 @@
ViewData["Title"] = "Context";
var position = Model.Display?.Context?.Position;
var tabs = new[] {
new { id = "overview", displayName = "Overview", endpoint = Url.Action("ContextScene", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "reference", refreshGuard = "defer-while-dirty-or-busy" },
new { id = "characters", displayName = "Characters in Scene", endpoint = Url.Action("ContextCharacters", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "reference", refreshGuard = "defer-while-dirty-or-busy" }
new { id = "overview", displayName = "Overview", endpoint = Url.Action("ContextScene", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "reference", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "scene.focus" } },
new { id = "characters", displayName = "Characters in Scene", endpoint = Url.Action("ContextCharacters", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "reference", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "character.focus" } }
};
}
<link rel="stylesheet" href="~/css/context-workspace.css" asp-append-version="true" />
@ -21,6 +21,7 @@
<label>Layout <select data-context-layout class="form-select form-select-sm"><option value="single">Single pane</option><option value="columns">Side by side</option><option value="rows">Stacked</option></select></label>
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-new>New Context window</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-refresh>Refresh saved data</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-windows>My Windows</button>
<p data-context-status role="status">@(Model.Display?.FollowStatus ?? "Waiting for a saved scene")</p>
</header>
<nav class="context-navigation" aria-label="Saved manuscript scenes">
@ -39,8 +40,18 @@
</section>
}
</div>
<dialog data-context-windows-dialog class="context-windows-dialog">
<h2 class="h5">My Context windows</h2><p>Only your connected windows for this book appear. Commands focus a reference tool; they do not navigate Word.</p>
<div data-context-window-list></div>
<label>Destination <select data-context-window-target class="form-select"><option value="">Choose automatically</option></select></label>
<button type="button" data-context-demonstrate class="btn btn-outline-primary mt-2">Focus this scene in an Overview pane</button>
<p data-context-window-status role="status"></p>
<button type="button" data-context-windows-close class="btn btn-outline-secondary">Close</button>
</dialog>
</main>
@section Scripts {
<script src="~/js/writing-workspace.js" asp-append-version="true"></script>
<script src="~/js/context-tools.js" asp-append-version="true"></script>
<script src="~/js/context-workspace.js" asp-append-version="true"></script>
<script src="~/js/context-windows.js" asp-append-version="true"></script>
}

View File

@ -20,7 +20,7 @@ else
var known = Model.AtPoint?.Characters.FirstOrDefault(x=>x.Appearance.CharacterID==character.CharacterID);
var knowledge = Model.AtPoint?.Characters.FirstOrDefault(x=>x.Appearance.CharacterID==character.CharacterID)?.Knowledge.ToList() ?? [];
var attributes = scene.CharacterAttributeEvents.Where(x => x.CharacterID == character.CharacterID).ToList();
<article class="writing-context-card writing-context-person-card">
<article class="writing-context-card writing-context-person-card" data-context-character="@character.CharacterID" tabindex="-1">
<div class="writing-context-person-heading">
<partial name="~/Views/Shared/_Avatar.cshtml" model="@(new AvatarViewModel { DisplayName = character.CharacterName, ImagePath = character.CharacterImagePath, ThumbnailPath = character.CharacterThumbnailPath, Size = "md" })" />
<div>

View File

@ -32,3 +32,6 @@ body:has([data-context-workspace])>.writing-window-bar { flex:none; }
@container (min-width:700px) { .context-pane-content .writing-context-grid,.context-pane-content .writing-context-people-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } .context-pane-content .writing-context-card--hero,.context-pane-content .writing-context-card--wide { grid-column:span 2; } }
@container (max-width:320px) { .context-pane-content .writing-context-facts { grid-template-columns:minmax(0,1fr); gap:.2rem; } .context-pane-content .writing-context-facts dd { margin-bottom:.5rem; } }
@media(max-height:500px) { .context-toolbar,.context-navigation { gap:.25rem; } .context-toolbar p { font-size:.75rem; } }
.context-windows-dialog { width:min(38rem,calc(100vw - 2rem));max-height:85dvh;overflow:auto;background:var(--plotline-panel);color:var(--plotline-ink);border:1px solid var(--plotline-line);border-radius:.7rem;padding:1rem; }
.context-windows-dialog::backdrop { background:#0006; }
.context-reference-focus { outline:3px solid var(--plotline-accent);outline-offset:-3px; }

View File

@ -0,0 +1,9 @@
// Tool interactions own presentation. They never change the manuscript/Word position.
(() => {
const focus=node=>{node.classList.add('context-reference-focus');node.scrollIntoView({block:'nearest'});node.focus({preventScroll:true});};
window.PlotDirectorContextLifecycles={...(window.PlotDirectorContextLifecycles||{}),reference:{mount(){},dispose(){},onInteraction(node,command){
if(command.action==='scene.focus'&&Number(node.dataset.sceneId)===command.storyPoint?.sceneID){node.tabIndex=-1;focus(node);return 'focused';}
if(command.action==='character.focus'){const target=node.querySelector(`[data-context-character="${Number(command.characterID)}"]`);if(target){focus(target);return 'focused';}}
return 'not-visible';
}}};
})();

View File

@ -0,0 +1,45 @@
(() => {
'use strict';
const root=document.querySelector('[data-context-workspace]'),controller=root?.contextController,connection=controller?.connection;
if(!controller)return;
const dialog=root.querySelector('[data-context-windows-dialog]'),message=dialog.querySelector('[data-context-window-status]'),list=dialog.querySelector('[data-context-window-list]'),target=dialog.querySelector('[data-context-window-target]');
let windows=[],registering=false,again=false,lastBook=null,closed=false;
const pending=new Map();
function render(rows){windows=rows;const previous=target.value;target.replaceChildren(new Option('Choose automatically',''));list.replaceChildren();
rows.forEach((item,index)=>{const text=document.createElement('p');text.textContent=`${item.windowID===controller.windowId?'This window':'Window '+(index+1)} · ${item.panes.map(p=>p.toolID+(p.available?'':' (busy)')).join(', ')}`;list.append(text);
item.panes.forEach(p=>{const option=new Option(`Window ${index+1} · ${p.toolID} · pane ${Number(p.paneID)+1}`,item.sessionID+'/'+p.paneID);option.dataset.window=item.windowID;target.add(option);});});
if([...target.options].some(option=>option.value===previous))target.value=previous;
}
async function register(){if(!connection||connection.state!=='Connected'||closed||!controller.announcement.bookID)return;if(registering){again=true;return;}registering=true;
try{const announcement=controller.announcement;render(await connection.invoke('RegisterContextWindow',announcement));lastBook=announcement.bookID;}
catch{message.textContent='Window discovery unavailable. Reconnect or retry My Windows.';}
finally{registering=false;if(again){again=false;void register();}}
}
async function discover(){if(!connection){message.textContent='Pinned snapshots do not join live window discovery. Open a live Context window to communicate.';return;}
if(connection.state!=='Connected'){message.textContent='Context connection is reconnecting. Try again shortly.';return;}
try{render(await connection.invoke('MyContextWindows',controller.announcement.bookID));}catch{message.textContent='Window discovery unavailable for this book.';}}
function fallback(node,command,status){node.textContent=status==='no-handler'?'No visible tool supports this reference. Choose the tool in a pane or open the full workspace.':status==='not-visible'?'The destination cannot show this reference at its current point. Open the full workspace if needed.':status==='busy'?'The destination is editing or busy. Try again after it finishes.':'Reference unavailable. Retry after reconnecting.';
const path=command.characterID?'/Characters/Details/'+Number(command.characterID):command.locationID?'/Locations/Details/'+Number(command.locationID):null;
if(path){const link=document.createElement('a');link.href=path;link.target='_blank';link.rel='noopener';link.textContent=' Open full workspace';node.append(link);}}
async function send(command,node){if(!connection||connection.state!=='Connected'){fallback(node,command,'unavailable');return;}
const pane=root.querySelector('[data-context-pane]:not([hidden])');command={...command,version:1,bookID:controller.announcement.bookID,originPaneID:command.originPaneID||pane?.dataset.contextPane||'0'};
if(target.value&&dialog.open){const option=target.selectedOptions[0];command.targetWindowID=option.dataset.window;const at=target.value.lastIndexOf('/');command.targetSessionID=target.value.slice(0,at);command.targetPaneID=target.value.slice(at+1);}
try{await register();const result=await connection.invoke('SendContextInteraction',command);
if(result.status!=='delivered'){fallback(node,command,result.status);return;}
// Ack can arrive before invoke completion; retain the record so either ordering is safe.
const receipt=pending.get(result.commandID);if(receipt?.status){complete(node,command,receipt.status);pending.delete(result.commandID);}else{pending.set(result.commandID,{node,command,expires:Date.now()+20000});node.textContent='Reference request delivered; waiting for the selected tool.';}
}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('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();});
root.addEventListener('context-capabilities-changed',()=>{for(const [id,item]of pending)if(item.expires<Date.now()){if(item.node)fallback(item.node,item.command,'unavailable');pending.delete(id);}void register();});
root.addEventListener('context-command',event=>{const pane=event.target.closest('[data-context-pane]');let node=event.target.closest('[data-context-tab-fragment]')?.querySelector('[data-context-interaction-status]');
if(!node){node=document.createElement('p');node.dataset.contextInteractionStatus='';node.setAttribute('role','status');(event.target.closest('[data-context-tab-fragment]')||root).append(node);}void send({...event.detail,originPaneID:pane?.dataset.contextPane||'0'},node);});
root.querySelector('[data-context-windows]').addEventListener('click',()=>{dialog.showModal();void discover();});
root.querySelector('[data-context-windows-close]').addEventListener('click',()=>dialog.close());
root.querySelector('[data-context-demonstrate]').addEventListener('click',()=>{const position=controller.position;void send({action:'scene.focus',storyPoint:{chapterID:position.chapterId,sceneID:position.sceneId}},message);});
window.addEventListener('pagehide',()=>{closed=true;pending.clear();});
void register();
})();

View File

@ -7,6 +7,7 @@
const fields = ['projectId', 'bookId', 'chapterId', 'sceneId', 'paragraphId'];
const number = value => Number.isSafeInteger(Number(value)) && Number(value) > 0 ? Number(value) : null;
const uuid = () => crypto.randomUUID();
const announce=()=>root.dispatchEvent(new Event("context-capabilities-changed"));
const status = root.querySelector('[data-context-status]');
const grid = root.querySelector('[data-context-panes]');
const divider = root.querySelector('[data-context-divider]');
@ -106,7 +107,7 @@
remember(pane);dispose(record);record.node=node;record.stale=false;record.position={...position};
mount(pane,record);
if(focusHref&&document.hasFocus())[...pane.host.querySelectorAll('a')].find(link=>link.getAttribute('href')===focusHref)?.focus({preventScroll:true});
pane.status.textContent=unavailable?'Saved reference · live Word position unavailable.':'';
pane.status.textContent=unavailable?'Saved reference · live Word position unavailable.':'';announce();
} catch(error) {
if(epoch!==generation||request!==pane.revision||stopped)return;
pane.status.textContent=error.name==='AbortError'?'Reference request interrupted. Use Refresh saved data to retry.':error.message;
@ -137,6 +138,7 @@
sceneSelect.value=position.sceneId||'';
root.querySelector('[data-context-editor]').href=position.sceneId?`/Scenes/Edit/${position.sceneId}`:'/Writer';
for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');for(const record of pane.records.values())if(force||scopeChanged(record.tab,before,position))record.stale=true;void refreshPane(pane);}
announce();
}
async function recoverOffice(force=false) {
if(pinned||selectedDocument||nativeLeases.some(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)))return;
@ -189,7 +191,7 @@
divider.setAttribute('aria-valuenow',String(Math.round(ratio*100)));
divider.setAttribute('aria-valuemin',String(Math.round(edge*100)));divider.setAttribute('aria-valuemax',String(Math.round((1-edge)*100)));
for(const pane of panes){pane.select.value=state.panes[pane.index].tab;if(visible(pane))void refreshPane(pane);else{pane.revision++;dispose(current(pane));}}
save();
save();announce();
}
function resize(ratio) { state.ratio=Math.max(.2,Math.min(.8,ratio));applyLayout(); }
let dragging=false;
@ -202,11 +204,11 @@
pane.select.value=state.panes[pane.index].tab;
pane.select.addEventListener('change',()=>{
if(guarded(current(pane))){pane.select.value=state.panes[pane.index].tab;pane.status.textContent='Finish or cancel editing before changing tools.';return;}
remember(pane);dispose(current(pane));pane.revision++;state.panes[pane.index].tab=pane.select.value;save();void refreshPane(pane);
remember(pane);dispose(current(pane));pane.revision++;state.panes[pane.index].tab=pane.select.value;save();void refreshPane(pane);announce();
});
pane.host.addEventListener('scroll',()=>{remember(pane);save();},{passive:true});
pane.element.addEventListener('context-panel-state',event=>{
const record=current(pane);if(!record)return;record.dirty=!!event.detail?.dirty;record.busy=!!event.detail?.busy;if(!guarded(record)&&record.stale)void refreshPane(pane);
const record=current(pane);if(!record)return;record.dirty=!!event.detail?.dirty;record.busy=!!event.detail?.busy;if(!guarded(record)&&record.stale)void refreshPane(pane);announce();
});
}
async function navigate(sceneId,sendWord=false) {
@ -231,7 +233,7 @@
async function startConnection(){
if(stopped||connectionStarting||!connection||connection.state&&connection.state!=='Disconnected')return;
connectionStarting=true;
try{await connection.start();wakeStatus(true);void recoverOffice(true);}catch{status.textContent='Context notifications disconnected · retrying; saved browsing remains available';}finally{connectionStarting=false;}
try{await connection.start();wakeStatus(true);void recoverOffice(true);root.dispatchEvent(new Event('context-connection-ready'));}catch{status.textContent='Context notifications disconnected · retrying; saved browsing remains available';}finally{connectionStarting=false;}
}
if(!pinned&&window.signalR){
connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();
@ -239,11 +241,11 @@
connection.on('ContextPositionChanged',()=>void recoverOffice());
connection.on('ContextInvalidated',hint=>{invalidate(hint);wakeStatus();});
connection.onreconnecting(()=>status.textContent='Context notifications reconnecting · saved reference may be stale');
connection.onreconnected(()=>{wakeStatus(true);void recoverOffice(true);invalidate();});
connection.onreconnected(()=>{wakeStatus(true);void recoverOffice(true);invalidate();root.dispatchEvent(new Event('context-connection-ready'));});
connection.onclose(()=>status.textContent='Context notifications disconnected · saved browsing remains available');
void startConnection();
}
const timer=pinned?null:setInterval(()=>{void startConnection();void recoverOffice();},15000);
const timer=pinned?null:setInterval(()=>{void startConnection();void recoverOffice();announce();},15000);
document.addEventListener('visibilitychange',()=>{if(!document.hidden&&!pinned){void startConnection();wakeStatus(true);void recoverOffice(true);}});
window.addEventListener('pageshow',event=>{if(event.persisted)location.reload();});
// Duplicated browser tabs clone both URL and session storage. The live owner answers claims.
@ -265,7 +267,7 @@
if(message.kind==='occupied'&&message.target===pageToken){windowId=uuid();panes.forEach(pane=>{dispose(current(pane));pane.revision++;pane.records.clear();pane.host.replaceChildren();});state=defaults();selectedDocument=root.dataset.wordInstance&&root.dataset.wordSession?`${root.dataset.wordInstance}/${root.dataset.wordSession}`:'';save();const url=new URL(location.href);url.searchParams.set('contextWindow',windowId);history.replaceState(null,'',url);applyLayout();}
};channel.postMessage({kind:'claim',id:windowId,token:pageToken});}
const observer=new ResizeObserver(()=>applyLayout());observer.observe(grid);
root.contextController={ get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,registerLifecycle:(name,hooks)=>lifecycles[name]=hooks };
root.contextController={ get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,get connection(){return connection;},get announcement(){return {version:1,bookID:position.bookId,windowID:windowId,panes:panes.filter(visible).map(pane=>({paneID:String(pane.index),toolID:state.panes[pane.index].tab,actions:registry.get(state.panes[pane.index].tab).actions||[],available:!!current(pane)?.node&&!current(pane).stale&&!guarded(current(pane))}))};},receiveInteraction:async delivery=>{const pane=panes.find(p=>String(p.index)===delivery.paneID);if(!pane||!visible(pane))return 'not-visible';const record=current(pane);if(guarded(record))return 'busy';if(!record?.node||record.stale)return 'unavailable';record.stale=true;await refreshPane(pane);if(record.stale||guarded(record))return 'unavailable';return await lifecycles[record.tab.lifecycle]?.onInteraction?.(record.node,delivery.command,{position:{...position},pane})||'not-visible';},registerLifecycle:(name,hooks)=>lifecycles[name]=hooks };
window.addEventListener('pagehide',()=>{stopped=true;panes.forEach(pane=>{remember(pane);dispose(current(pane));});save();cancelRequests();navigationRequest?.abort();clearInterval(timer);observer.disconnect();channel?.close();void connection?.stop();});
save();applyLayout();
if(pinned)status.textContent='Saved PlotDirector snapshot · manual selection · live follow disabled';