From 16c05055fa1069b3a413b95e8f6f038528a5dc11 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sun, 22 Nov 2026 15:06:21 +0000 Subject: [PATCH] Add same-user book-scoped My Windows interactions to Context --- .../Unified-Context-Enhancements-20261122.md | 27 +++++++++ PlotLine.Tests/Browser/context-my-windows.cjs | 30 ++++++++++ PlotLine.Tests/ContextWindowsTests.cs | 27 +++++++++ PlotLine.Tests/Program.cs | 3 + PlotLine.Tests/ToolbarBrowserHost.cs | 6 ++ PlotLine/Hubs/NativeCompanionPresenceHub.cs | 55 ++++++++++++++++- PlotLine/Program.cs | 2 + PlotLine/Services/Context/ContextWindows.cs | 59 +++++++++++++++++++ PlotLine/Views/Writing/Context.cshtml | 15 ++++- .../Writing/_WritingContextPeople.cshtml | 2 +- PlotLine/wwwroot/css/context-workspace.css | 3 + PlotLine/wwwroot/js/context-tools.js | 9 +++ PlotLine/wwwroot/js/context-windows.js | 45 ++++++++++++++ PlotLine/wwwroot/js/context-workspace.js | 18 +++--- 14 files changed, 287 insertions(+), 14 deletions(-) create mode 100644 Docs/Writer/Unified-Context-Enhancements-20261122.md create mode 100644 PlotLine.Tests/Browser/context-my-windows.cjs create mode 100644 PlotLine.Tests/ContextWindowsTests.cs create mode 100644 PlotLine/Services/Context/ContextWindows.cs create mode 100644 PlotLine/wwwroot/js/context-tools.js create mode 100644 PlotLine/wwwroot/js/context-windows.js diff --git a/Docs/Writer/Unified-Context-Enhancements-20261122.md b/Docs/Writer/Unified-Context-Enhancements-20261122.md new file mode 100644 index 00000000..9a9948c5 --- /dev/null +++ b/Docs/Writer/Unified-Context-Enhancements-20261122.md @@ -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. diff --git a/PlotLine.Tests/Browser/context-my-windows.cjs b/PlotLine.Tests/Browser/context-my-windows.cjs new file mode 100644 index 00000000..ea2d01e6 --- /dev/null +++ b/PlotLine.Tests/Browser/context-my-windows.cjs @@ -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();}})(); diff --git a/PlotLine.Tests/ContextWindowsTests.cs b/PlotLine.Tests/ContextWindowsTests.cs new file mode 100644 index 00000000..ef5a5df0 --- /dev/null +++ b/PlotLine.Tests/ContextWindowsTests.cs @@ -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");} + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index daa9bd20..6653c4c2 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -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()), diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 53205b13..83f5ca6b 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -141,6 +141,11 @@ internal static class ToolbarBrowserHost builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(TimeProvider.System); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(FixtureProxy((name,args)=>Task.FromResult((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((name,args)=>name=="GetCharacterAsync"?Task.FromResult((int)args![0]! ==5?new(){CharacterID=5,ProjectID=7,CharacterName="Fixture participant"}:null):throw new NotSupportedException(name))); + builder.Services.AddSingleton(FixtureProxy((name,args)=>name=="GetAsync"?Task.FromResult((int)args![0]! ==77?new(){LocationID=77,ProjectID=7,LocationName="Saved room"}:null):throw new NotSupportedException(name))); + builder.Services.AddSingleton(); builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((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("
" + menu + toolbar + "
" + surface + "
" + appearanceScript + "" + writerScripts + ""); }); + app.MapHub("/hubs/native-companion"); app.MapHub("/hubs/word-companion-follow"); await app.RunAsync(); } diff --git a/PlotLine/Hubs/NativeCompanionPresenceHub.cs b/PlotLine/Hubs/NativeCompanionPresenceHub.cs index 01796024..f4332f7e 100644 --- a/PlotLine/Hubs/NativeCompanionPresenceHub.cs +++ b/PlotLine/Hubs/NativeCompanionPresenceHub.cs @@ -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 Book(int book) + => await access.GetBookStructureAsync(book,Author)??throw new HubException("Book unavailable."); + public async Task 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 MyContextWindows(int bookId){await Book(bookId);return windows.List(Author,bookId);} + 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."); + 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); + } } diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index f9482b58..06a619a5 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -288,7 +288,9 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); + builder.Services.Configure>(options => options.MaximumReceiveMessageSize = 16384); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); diff --git a/PlotLine/Services/Context/ContextWindows.cs b/PlotLine/Services/Context/ContextWindows.cs new file mode 100644 index 00000000..c6589a78 --- /dev/null +++ b/PlotLine/Services/Context/ContextWindows.cs @@ -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 leases = []; + private readonly Dictionary 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;} + } +} diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index 96c54757..dc538f54 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -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" } } }; } @@ -21,6 +21,7 @@ +

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