Keep Context windows isolated when browser channel or storage is unavailable
This commit is contained in:
parent
28b074ca53
commit
cf8a969196
@ -68,7 +68,7 @@ Equivalent concurrent requests from both panes share one HTTP response promise f
|
||||
|
||||
Versioned localStorage keys are `plotdirector.context.v1.<account>.<window UUID>`. sessionStorage records the current window identity; managed launches pass a fresh `contextWindow` UUID. Ordinary refresh/navigation restores that window's layout, ratio, both pane selections, selected document and per-tool scroll. No manuscript prose or unsaved form drafts are persisted.
|
||||
|
||||
New Context, Writer, native launcher and Office launches open independent windows with a fresh UUID/default single-pane arrangement. Role-wide popup names, role focus selection and global active-tab keys are gone. An opener check plus account-scoped BroadcastChannel identity claims detects cloned/duplicated live tabs; the newcomer receives a new identity/default layout. Explicit native document parameters are retained during clone repair. Optional storage/channel failures do not prevent the reference workspace from operating; without BroadcastChannel, unmanaged browser tab duplication cannot be guaranteed collision-free, although managed launches and opener clones remain isolated.
|
||||
New Context, Writer, native launcher and Office launches open independent windows with a fresh UUID/default single-pane arrangement. Role-wide popup names, role focus selection and global active-tab keys are gone. An opener check plus account-scoped BroadcastChannel identity claims (with a storage-event fallback) detects cloned/duplicated live tabs; the newcomer receives a new identity/default layout. Explicit native document parameters are retained during clone repair. Storage access, including a denied storage getter, is guarded. When persistent storage is unavailable, each document operates with fresh in-memory identity/state; otherwise storage events provide clone recovery when BroadcastChannel is unavailable.
|
||||
|
||||
Single mode retains pane two's tool and state. Layouts are Single, Side by side and Stacked. Pointer drag and arrow/Home/End keyboard controls resize the separator; orientation, value and controlled pane IDs are exposed for assistive technology. Ratios are bounded; pane-size constraints are clamped to the available viewport. On very small/zoomed displays users can select stacked or single layout rather than relying on operating-system snapping.
|
||||
|
||||
@ -96,7 +96,7 @@ The Scene editor, Writer Chapter workflows, full Maps/Floor Plans/Relationships/
|
||||
- Normal `dotnet build PlotLine.slnx`: clean build, zero warnings/errors at the recorded gate.
|
||||
- Full executable regression harness: 673 PASS lines, exit 0; includes updated native session/access/ownership/reference-data checks and existing native command/authentication suites. Additional notification-boundary assertions are included in focused Writing integration qualification.
|
||||
- `--writing-integration`: authoritative reference hydration, scope/access, exact native session, unsaved/stale mappings, during-load changes, chronology/provenance and request reuse.
|
||||
- `Browser/context-workspace-foundation.cjs`: real compiled Razor shell and both partials in the isolated loopback host, with synthetic reference data and controllable HTTP/SignalR inputs. Covers layouts, pointer/keyboard divider, same/different tabs, shared reads, hidden staleness, same-scene invalidation, rapid chapter/scene races, dirty/busy deferral, access/session failures, reconnect, native ambiguity/document selection, Office fallback/native precedence, independent windows, cloned storage, persistence, pinned snapshots and Office/Intent launch compatibility.
|
||||
- `Browser/context-workspace-foundation.cjs`: real compiled Razor shell and both partials in the isolated loopback host, with synthetic reference data and controllable HTTP/SignalR inputs. Covers layouts, pointer/keyboard divider, same/different tabs, shared reads, hidden staleness, same-scene invalidation, rapid chapter/scene races, dirty/busy deferral, access/session failures, reconnect, native ambiguity/document selection, Office fallback/native precedence, independent windows, cloned storage (BroadcastChannel and storage-event fallback), denied storage, persistence, pinned snapshots and Office/Intent launch compatibility.
|
||||
- Browser sizes include 1366×768, 760×768, 683×384 and 480×700 at 125% CSS zoom; shell/card reflow and no document-wide horizontal overflow are checked. The 683×384 viewport approximates the CSS space at 200% on a 1366×768 display.
|
||||
- Shared notifications browser checks pass in browser and simulated standalone presentation. Existing Evidence request/cancel/isolation checks remain applicable.
|
||||
- Standalone presentation is simulated Chromium qualification. Physical installed-PWA, Windows Word/VSTO and OS-level zoom/assistive-technology acceptance remain manual; these are not claimed as automated physical tests.
|
||||
@ -134,7 +134,7 @@ The new opt-in live smoke requires private disposable identity/scope files via `
|
||||
- Context shows authoritative saved reference data. Accepted prose synchronization does not imply completed canonical Story Intelligence analysis, and no analysis is started by refresh.
|
||||
- Paragraph scope is supported by the generic registry, but the current common position integration supplies no durable paragraph identity and no paragraph tool is shipped.
|
||||
- Browser layout/zoom and standalone presentation were qualified in Chromium; physical Windows Word/VSTO, a genuinely installed PWA and OS/browser zoom plus assistive technology need the manual acceptance below. No physical Word performance claim is made.
|
||||
- Managed new-window identities and BroadcastChannel clone recovery are tested. Unmanaged duplicated tabs on browsers without BroadcastChannel have the fallback limitation described in the state section.
|
||||
- Managed new-window identities, BroadcastChannel and storage-event clone recovery, and denied-storage in-memory operation are tested. Settings cannot persist when storage is denied.
|
||||
- Window/pane settings are local to the account/browser/window identity, not server-roaming preferences. Storage refusal falls back to usable in-memory operation.
|
||||
|
||||
## Adding a future tab
|
||||
|
||||
@ -71,6 +71,11 @@ const lease=(extra={})=>({instanceId:'11111111-1111-4111-8111-111111111111',sess
|
||||
}
|
||||
await page.evaluate(()=>{document.documentElement.style.zoom='1';Object.defineProperty(navigator,'standalone',{value:true});});
|
||||
step='pinned snapshot';leases=[lease({sceneId:23,chapterId:11})];const pinned=await context.newPage();await pinned.goto(base+'/Writing/Context?pinned=true&sceneId=22');await pinned.waitForSelector('[data-context-tab-fragment]');assert.equal(await pinned.evaluate(()=>contextConnections.length),0);assert.equal(await pinned.locator('[data-context-tab-fragment]').getAttribute('data-scene-id'),'22');await pinned.selectOption('[data-context-scene]','23');await pinned.waitForSelector('[data-context-tab-fragment][data-scene-id="23"]');await pinned.close();
|
||||
step='storage-event clone fallback';
|
||||
const fallback=await context.newPage();await fallback.addInitScript(()=>Object.defineProperty(window,'BroadcastChannel',{value:undefined}));await fallback.goto(base+'/Writing/Context');await fallback.waitForSelector('[data-context-tab-fragment]');await fallback.selectOption('[data-context-layout]','rows');const fallbackId=await fallback.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId);
|
||||
const fallbackClone=await context.newPage();await fallbackClone.addInitScript(id=>{Object.defineProperty(window,'BroadcastChannel',{value:undefined});sessionStorage.setItem('plotdirector.context.window.v1',id);},fallbackId);await fallbackClone.goto(base+'/Writing/Context');await fallbackClone.waitForFunction(id=>document.querySelector('[data-context-workspace]')?.contextController?.windowId!==id,fallbackId);assert.equal(await fallbackClone.locator('[data-context-layout]').inputValue(),'single');await fallback.close();await fallbackClone.close();
|
||||
step='denied storage in-memory fallback';
|
||||
const noStorage=await context.newPage();await noStorage.addInitScript(()=>{Object.defineProperty(window,'BroadcastChannel',{value:undefined});for(const name of ['localStorage','sessionStorage'])Object.defineProperty(window,name,{get(){throw new DOMException('Storage unavailable','SecurityError');}});});await noStorage.goto(base+'/Writing/Context');await noStorage.waitForSelector('[data-context-tab-fragment]');await noStorage.selectOption('[data-context-layout]','rows');assert.equal(await noStorage.locator('[data-context-layout]').inputValue(),'rows');await noStorage.close();
|
||||
step='Office launch URL contract';
|
||||
const host=fs.readFileSync(require('node:path').join(__dirname,'../../PlotLine/wwwroot/js/word-companion-host.js'),'utf8');
|
||||
const launch=host.slice(host.indexOf(' const writingWorkspaceUrl ='),host.indexOf(' const openWritingWindow ='));
|
||||
|
||||
@ -19,22 +19,22 @@
|
||||
let navigationRequest, manualGeneration = 0, recoveryPending = false, recoveryAgain = false;
|
||||
const requests = new Map();
|
||||
const lifecycles = { reference: { mount() {}, dispose() {} }, ...(window.PlotDirectorContextLifecycles || {}) };
|
||||
const read = (storage,key) => { try { return storage.getItem(key); } catch { return null; } };
|
||||
const write = (storage,key,value) => { try { storage.setItem(key,value); } catch { /* UI storage is optional. */ } };
|
||||
let windowId = new URL(location.href).searchParams.get('contextWindow') || read(sessionStorage,'plotdirector.context.window.v1');
|
||||
const read = (name,key) => { try { return window[name].getItem(key); } catch { return null; } };
|
||||
const write = (name,key,value) => { try { window[name].setItem(key,value); return true; } catch { return false; } };
|
||||
let windowId = new URL(location.href).searchParams.get('contextWindow') || read('sessionStorage','plotdirector.context.window.v1');
|
||||
if (!/^[a-f0-9-]{36}$/i.test(windowId || '')) windowId = uuid();
|
||||
try { if (window.opener?.document.querySelector('[data-context-workspace]')?.contextController?.windowId === windowId) windowId = uuid(); } catch { }
|
||||
const defaults = () => ({ version:1, layout:'single', ratio:.5, selectedDocument:'', panes:[{tab:'overview',views:{}},{tab:'characters',views:{}}] });
|
||||
const stateKey = () => `plotdirector.context.v1.${root.dataset.user}.${windowId}`;
|
||||
let state;
|
||||
try { state=JSON.parse(read(localStorage,stateKey())); } catch { }
|
||||
try { state=JSON.parse(read('localStorage',stateKey())); } catch { }
|
||||
if (state?.version !== 1 || !Array.isArray(state.panes) || state.panes.length !== 2) state=defaults();
|
||||
if (!['single','columns','rows'].includes(state.layout)) state.layout='single';
|
||||
state.ratio = Number.isFinite(state.ratio) ? Math.max(.2,Math.min(.8,state.ratio)) : .5;
|
||||
state.panes=state.panes.map((pane,i)=>({tab:registry.has(pane?.tab)?pane.tab:defaults().panes[i].tab,views:pane?.views && typeof pane.views==='object'?pane.views:{}}));
|
||||
let selectedDocument = root.dataset.wordInstance && root.dataset.wordSession ? `${root.dataset.wordInstance}/${root.dataset.wordSession}` : state.selectedDocument || '';
|
||||
let nativeKey = '', unavailable = false;
|
||||
const save = () => { state.selectedDocument=selectedDocument; write(sessionStorage,'plotdirector.context.window.v1',windowId); write(localStorage,stateKey(),JSON.stringify(state)); };
|
||||
const save = () => { state.selectedDocument=selectedDocument; write('sessionStorage','plotdirector.context.window.v1',windowId); write('localStorage',stateKey(),JSON.stringify(state)); };
|
||||
const panes = [...root.querySelectorAll('[data-context-pane]')].map((element,index)=>({ element,index,select:element.querySelector('[data-context-tab]'),host:element.querySelector('[data-context-pane-content]'),status:element.querySelector('[data-context-pane-status]'),records:new Map(),revision:0 }));
|
||||
const current = pane => pane.records.get(state.panes[pane.index].tab);
|
||||
const visible = pane => pane.index===0 || state.layout!=='single';
|
||||
@ -242,7 +242,18 @@
|
||||
window.addEventListener('pageshow',event=>{if(event.persisted)location.reload();});
|
||||
// Duplicated browser tabs clone both URL and session storage. The live owner answers claims.
|
||||
const pageToken=uuid();let channel;
|
||||
if(window.BroadcastChannel){channel=new BroadcastChannel(`plotdirector.context.identity.${root.dataset.user}`);channel.onmessage=event=>{
|
||||
const identityChannel=`plotdirector.context.identity.${root.dataset.user}`;
|
||||
try { if(window.BroadcastChannel)channel=new BroadcastChannel(identityChannel); } catch { }
|
||||
if(!channel){
|
||||
// Storage events also reach cloned tabs when BroadcastChannel is unavailable.
|
||||
const key=identityChannel+'.claim';
|
||||
if(write('localStorage',key,JSON.stringify({kind:'probe',token:pageToken}))){
|
||||
const receive=event=>{if(event.key===key&&event.newValue){try{channel?.onmessage?.({data:JSON.parse(event.newValue)});}catch{}}};
|
||||
channel={postMessage:message=>write('localStorage',key,JSON.stringify({...message,nonce:uuid()})),close:()=>window.removeEventListener('storage',receive)};
|
||||
window.addEventListener('storage',receive);
|
||||
}
|
||||
}
|
||||
if(channel){channel.onmessage=event=>{
|
||||
const message=event.data;if(message.id!==windowId||message.token===pageToken)return;
|
||||
if(message.kind==='claim')channel.postMessage({kind:'occupied',id:windowId,token:pageToken,target:message.token});
|
||||
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();}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user