Announce fallback presence connection for live character updates

This commit is contained in:
Nick Beckley 2026-11-26 12:07:04 +00:00
parent 59298af9a7
commit a043e9f902
5 changed files with 59 additions and 4 deletions

View File

@ -46,12 +46,12 @@ The server returns a protected, author-bound, ten-minute Undo receipt containing
- Filters combine across attributes. Counts respect other active attribute filters. Select displayed includes only visible cards; hidden selections are removed when filtering. Checkboxes, Ctrl/Cmd-click and Shift-click ranges support bulk assignment. Dragging uses a separate handle, leaving biography selection, details links and existing form buttons intact.
- The existing `PlotDirectorContextMenus` provider handles individual and selected scopes, nested submenus, viewport positioning, dismissal and keyboard navigation. This feature adds optional `checked` and `tone` command properties, and exposes `openAt`/`close` for component invocation. It does not add another menu framework or suppress context menus outside the existing shell policy. Ctrl-right-click and text selection retain existing shell/browser behavior. Open/Edit/Archive appear only for an individual; Archive submits its original confirmation-protected form.
- The shared toast service accepts an optional `{action:{label,run}}`; content remains plain text, with existing roles, bounds, timing and dismissal. There is no separate notification host.
- Successful writes emit one lightweight existing `ContextInvalidated` hint (`projectId`, `kind: characters`) through `ContextWorkspaceNotifications`. The directory reuses `PlotDirectorPresenceConnection`, with authenticated snapshot retrieval and no per-card connections. Existing Character Details and Context listeners continue their existing refresh behavior, including Held Context; no position/focus command is emitted.
- Successful writes emit one lightweight existing `ContextInvalidated` hint (`projectId`, `kind: characters`) through `ContextWorkspaceNotifications`. The directory reuses `PlotDirectorPresenceConnection`, with authenticated snapshot retrieval and no per-card connections. The main-window fallback announces that same connection and its readiness even when the optional Word status control is hidden; `context-presence-fallback.cjs` checks one connection/event/subscription/registration. Existing Character Details and Context listeners continue their existing refresh behavior, including Held Context; no position/focus command is emitted.
## Verification
Build and executable harness must run serially. `CharacterQuickAttributesTests` checks catalogue/custom/unknown semantics, biography-free snapshots, protected Undo author/expiry/tamper rejection and endpoint boundaries. `PlotLine.Tests/Sql/CharacterQuickAttributes.sql` refuses non-qualification databases and exercises atomic persistence on disposable characters in a disposable database copy.
With `--toolbar-browser-host` running, `node PlotLine.Tests/Browser/character-attributes.cjs` renders the actual compiled Characters Razor view and production scripts with isolated HTTP state. It covers 10/100/500 cards and records performance/screenshot artifacts in `/tmp`. `xvfb-run -a node PlotLine.Tests/Browser/character-attributes.cjs --installed` installs and launches a real Chromium app, asserting standalone display mode; it is not a matchMedia simulation. Neither browser fixture mutates an author's manuscript.
With `--toolbar-browser-host` running, `node PlotLine.Tests/Browser/character-attributes.cjs` renders the actual compiled Characters Razor view and production scripts with isolated HTTP state. It covers 10/100/500 cards and records performance/screenshot artifacts in `/tmp`. `xvfb-run -a node PlotLine.Tests/Browser/character-attributes.cjs --installed` installs and launches a real Chromium app, asserting standalone display mode; it is not a matchMedia simulation. Neither browser fixture mutates an author's manuscript. `character-attributes-held-context.cjs` verifies the real Context Razor/scripts refresh character data at Held scene 22 while shared focus moves to scene 23, without another connection or a held-position change.
Fixture HTTP responses do not substitute for authenticated Development persistence smoke checks or manifest-based schema deployment qualification. Delivery evidence must distinguish these checks explicitly.

View File

@ -0,0 +1,49 @@
// Focused saved-character invalidation with the real Context Razor/scripts; disposable HTTP fixtures.
// Actual compiled Razor shell and partials; isolated loopback fixture, no database or Word writes.
const {chromium}=require('playwright');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
const fakeSignalR=`window.contextConnections=[];window.signalR={HubConnectionBuilder:class{withUrl(url){this.url=url;return this}withAutomaticReconnect(){return this}build(){const c={url:this.url,state:'Disconnected',handlers:{},on(n,f){const prior=this.handlers[n];this.handlers[n]=(...args)=>{prior?.(...args);f(...args)}},onreconnecting(f){const prior=this.reconnecting;this.reconnecting=(...args)=>{prior?.(...args);f(...args)}},onreconnected(f){const prior=this.reconnected;this.reconnected=(...args)=>{prior?.(...args);f(...args)}},onclose(f){const prior=this.closed;this.closed=(...args)=>{prior?.(...args);f(...args)}},async start(){this.state='Connected'},async stop(){this.state='Disconnected'}};contextConnections.push(c);return c}}};`;
const lease=(extra={})=>({instanceId:'11111111-1111-4111-8111-111111111111',sessionId:'22222222-2222-4222-8222-222222222222',manuscriptId:'33333333-3333-4333-8333-333333333333',bookId:12,chapterId:10,sceneId:22,wordAvailable:true,wordSaved:true,active:true,positionVerified:true,mappingCurrent:true,snapshotRevision:1,revision:1,documentTitle:'Synthetic manuscript',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString(),...extra});
(async()=>{
const browser=await chromium.launch();let step='setup';
try{
const context=await browser.newContext({viewport:{width:1366,height:768}});
let leases=[lease()],office={connected:false,position:null},revision=1,mode='ok',delayScene=null,requests=[];
await context.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fakeSignalR}));
await context.route('**/native-companion/status',r=>r.fulfill({json:leases}));
await context.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected'}}));
await context.route('**/NarrativeFocus/Shared?*',r=>r.fulfill({json:{projectID:7,bookID:12,chapterID:10,sceneID:22,version:1,isValid:true}}));
await context.route('**/Writing/Context/Position?*',r=>r.fulfill({json:office}));
await context.route('**/Writing/Context/Navigate',r=>r.fulfill({status:409,json:{message:'No current Word mapping. Saved scene selected.'}}));
await context.route('**/Writing/Context/Tabs/*',async route=>{
const url=new URL(route.request().url());const tool=url.pathname.split('/').at(-1),scene=url.searchParams.get('sceneId');
requests.push({tool,scene,revision});const captured=revision;
if(mode==='expired')return route.fulfill({status:401,body:'Sign in'});
if(mode==='mapping')return route.fulfill({status:409,body:'Mapping pending'});
const response=await route.fetch({url:`${base}/context-tab-fixture/${tool}?sceneId=${scene}`});
const html=(await response.text()).replaceAll('Fixture participant',`Fixture participant · revision ${captured}`);
if(delayScene===scene)await new Promise(resolve=>setTimeout(resolve,350));
try{await route.fulfill({contentType:'text/html',body:html});}catch{/* Navigation may abort an obsolete shared read. */}
});
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
step='Held Context actual Razor';await page.goto(base+'/Writing/Context?pinned=true');
await page.waitForFunction(()=>window.PlotDirectorSharedFocus?.held&&window.PlotDirectorSharedFocus?.shared?.isValid);
await page.selectOption('[data-context-pane="0"] [data-context-tab]','characters');
await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 1'));
assert.equal(await page.evaluate(()=>contextConnections.length),1);
const before=await page.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position}));
step='Held character data refresh does not follow newer shared position';
await page.evaluate(()=>contextConnections[0].handlers.ManuscriptFocusChanged({projectID:7,bookID:12,chapterID:11,sceneID:23,version:2,isValid:true}));
revision=2;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({projectId:7,kind:'characters'}));
await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 2'));
assert.deepEqual(await page.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position})),before);
assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.held),true);
assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.shared.sceneID),23);
assert(requests.filter(r=>r.revision===2).every(r=>r.scene==='22'));
const reads=requests.length;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({projectId:999,kind:'characters'}));await page.waitForTimeout(100);assert.equal(requests.length,reads);
assert.equal(await page.evaluate(()=>contextConnections.length),1);assert.deepEqual(errors,[]);
console.log('PASS character invalidation in actual Held Context: character data refreshes at held scene 22 while shared focus moves to 23; unrelated-project hints ignored; one connection; no held position changes');
}catch(e){console.error('FAILED at '+step+'\n'+e.stack);process.exitCode=1;}finally{await browser.close();}
})();

View File

@ -36,7 +36,7 @@ const {chromium}=require('playwright');const os=require('node:os'),path=require(
const width=await page.locator('.character-card-grid').evaluate(n=>n.getBoundingClientRect().width);await page.locator('[data-attributes-toggle]').click();assert(await page.locator('[data-attribute-sidebar]').isHidden());assert(await page.locator('.character-card-grid').evaluate(n=>n.getBoundingClientRect().width)>width);await page.locator('[data-attributes-toggle]').click();
if(count>=100){await page.evaluate(()=>{let n=document.querySelector('[data-character-attributes]');for(;n;n=n.parentElement){if(/auto|scroll/.test(getComputedStyle(n).overflowY)&&n.scrollHeight>n.clientHeight){n.scrollTo({top:1200,behavior:'instant'});return;}}window.scrollTo({top:1200,behavior:'instant'});});const box=await page.locator('[data-attribute-sidebar]').boundingBox();assert(box.y>=0&&box.y<1000&&box.y+box.height<=1001);await page.evaluate(()=>{let n=document.querySelector('[data-character-attributes]');for(;n;n=n.parentElement)n.scrollTo({top:0,left:0,behavior:'instant'});window.scrollTo({top:0,behavior:'instant'});});}
await page.evaluate(()=>document.querySelectorAll('.pd-toast button[aria-label^="Dismiss"]').forEach(b=>b.click()));
for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';},theme);if(count===100)await page.screenshot({path:`/tmp/character-attributes-${installed?'installed-':''}${theme}.png`});}
for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';},theme);if(count===100)await page.screenshot({path:`/tmp/character-attributes-${installed?'installed-':''}${theme}.png`});}
for(const width of [1920,1366,1024,768,390]){await page.setViewportSize({width,height:1000});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}
assert.equal(await card(1).locator('.visual-card-heading p.muted').textContent(),biography);assert.deepEqual(errors,[]);results.push({count,loadMs:load,assignments:requests.length});await page.close();
}

View File

@ -0,0 +1,6 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path');
(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage();await page.route('https://fixture.test/',route=>route.fulfill({contentType:'text/html',body:'<body class="app-layout" data-pd-user-id="1"></body>'}));await page.goto('https://fixture.test/');await page.evaluate(()=>{
window.PlotDirectorContextEnvironment=crypto.randomUUID();window.metrics={builds:0,announced:0,ready:0,invalidations:0,registrations:0};const methods=new Map();window.fixtureConnection={state:'Disconnected',on:(name,fn)=>{if(!methods.has(name))methods.set(name,[]);methods.get(name).push(fn);},onreconnected:()=>{},invoke:async name=>{if(name==='RegisterContextWindow')metrics.registrations++;return [];},start:async()=>{fixtureConnection.state='Connected';},deliver:()=>{for(const fn of methods.get('ContextInvalidated')||[])fn({kind:'characters'});}};
window.signalR={HubConnectionBuilder:class{withUrl(){return this;}withAutomaticReconnect(){return this;}build(){metrics.builds++;return fixtureConnection;}}};
document.addEventListener('pd-presence-connection',e=>{metrics.announced++;e.detail.on('ContextInvalidated',()=>metrics.invalidations++);});document.addEventListener('pd-presence-ready',()=>metrics.ready++);
});await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/context-main-window.js')});await page.evaluate(()=>document.dispatchEvent(new Event('DOMContentLoaded')));await page.waitForFunction(()=>metrics.ready===1);await page.evaluate(()=>fixtureConnection.deliver());assert.deepEqual(await page.evaluate(()=>metrics),{builds:1,announced:1,ready:1,invalidations:1,registrations:1});await page.close();console.log('PASS shared presence fallback: hidden Word control still announces one shared connection, one ready event and one invalidation subscription without duplicate registration');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -35,6 +35,6 @@
function attach(c){if(connection)return;connection=c;connection.on('ContextInteraction',receive);connection.onreconnected(register);void register();timer=setInterval(()=>{if(connection.state==='Disconnected'&&!starting){starting=true;connection.start().then(register).catch(()=>{}).finally(()=>starting=false);}else void register();},15000);}
document.addEventListener('pd-presence-ready',register);
document.addEventListener('pd-presence-connection',e=>attach(e.detail));
document.addEventListener('DOMContentLoaded',()=>{if(window.PlotDirectorPresenceConnection)attach(window.PlotDirectorPresenceConnection);else if(window.signalR){const c=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();window.PlotDirectorPresenceConnection=c;attach(c);starting=true;c.start().then(register).catch(()=>{}).finally(()=>starting=false);}});
document.addEventListener('DOMContentLoaded',()=>{if(window.PlotDirectorPresenceConnection)attach(window.PlotDirectorPresenceConnection);else if(window.signalR){const c=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();window.PlotDirectorPresenceConnection=c;document.dispatchEvent(new CustomEvent('pd-presence-connection',{detail:c}));attach(c);starting=true;c.start().then(()=>document.dispatchEvent(new Event('pd-presence-ready'))).catch(()=>{}).finally(()=>starting=false);}});
window.addEventListener('pagehide',()=>clearInterval(timer));
})();