Qualify Context integration and scope cross-book refreshes to projects
This commit is contained in:
parent
37845993c8
commit
504eccacd6
@ -57,3 +57,25 @@ Relationships reuses the Story Point snapshot / existing `RelationshipMapService
|
||||
One relationship modal supports adding an initial connection or a scene development, correcting existing initial state or the selected scene event. It reuses initial/event services and lookups, validates role/book/scene/character/relationship ownership and duplicates, protects stale drafts and preserves existing direction/type/pair. Ambiguous multiple or unverified same-scene events redirect the author to full-editor review. Existing initial save now hydrates the prior structural flags/start/end before saving, preserving those fields during a focused correction.
|
||||
|
||||
Qualification: clean build; 10 focused assertions cover canonical future exclusion, Family/direction, loaded values, exact event save, stale and invalid pair/direction guards, initial save, foreign relationship/scene and read-only denial. Compiled Razor browser covers category separation, directional display, evidence limitations, saved modal values/cancel, independent same-tool filters and full/half/stacked/mobile layouts. No schema migration needed.
|
||||
|
||||
Phase 4 deployed commit `3784599`; release `context-enhancement-phase4-3784599-20261122T153623Z`; assembly/asset hashes and informational commit verified; local/public GET200 and all three authenticated tool reads passed. Actual Development persistence acceptance created two characters in the pre-existing disposable qualification project through the normal Character editor (Supporting default verified), attached them through the normal scene-participant save, and exercised Context description, alias and relationship saves. No author manuscript fixtures were modified.
|
||||
|
||||
### Phase 5 integration qualification
|
||||
|
||||
- Clean `dotnet build PlotLine.slnx` (zero warnings/errors), full executable regression harness via `dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj` passed, exit0; stored-procedure architecture guard passed. The first full run exposed an older native HTTP fixture missing the new presence-hub constructor dependencies; its isolated service registration was corrected and the full harness passed afterwards.
|
||||
- Focused coverage: 13 routing/lifecycle assertions, 17 character/name projection/edit assertions, 10 relationship state/edit assertions, plus existing narrative/permissions/native suites in the full harness.
|
||||
- Actual compiled Razor browser suites: Characters (12 long-name entries, Previous/Now/Next, canonical location command/no-handler link, saved-value modal, cancel/draft protection, inline failure and one success toast); Names (canonical/alias lookup, Unicode shared-spelling domain test, structured character focus, alias form, full-editor access); Relationships (Family/narrative separation, direction/evidence limits, focused modal, independent search). Full/half/stacked/390px widths, 125% zoom, two same-tool panes and touch-emulated Chromium passed. Screenshots inspected for narrow Characters. This is browser/emulation acceptance; physical touch hardware and installed PWA are not claimed.
|
||||
- Foundation suite passed including stale/race responses, dirty/busy deferral, reconnect, native/Office selection, cloned-window identity, denied-storage fallback, pinned snapshots, no inactive reload and unrelated-project invalidation isolation.
|
||||
- Real SignalR tests cover two independent authenticated sessions, exact scene and character recipient/pane, authoritative HTTP read only in recipient, explicit no-handler without tab replacement, cross-user/book/story-point rejection, disconnect/reconnect, one connection per Context and no Word navigation.
|
||||
- Actual Development editing on disposable records passed persisted description and alias, cancel without persistence, invalid blank-name inline draft retention, single local success toast and quiet second authenticated session, existing-service relationship create/correct and quiet remote refresh. Test is opt-in `Browser/context-live-editing.cjs`; it refuses identities not marked Development/disposable and requires an explicit synthetic scope.
|
||||
- Integration correction: identity/relationship changes notify the same authenticated account with a project ID so other books in that project can recover authoritative state; scene-appearance corrections stay book-scoped. Other projects ignore the hint. Inactive tabs remain stale until selected, rather than reloading. Current location now distinguishes explicitly Unknown and Off-screen from an unrecorded location.
|
||||
|
||||
### Remaining limitations and acceptance
|
||||
|
||||
No Production changes. No physical Word Companion, genuine cross-device hardware, separate browser engine or installed-PWA acceptance has been performed. Two authenticated browser contexts using the actual Development transport have been qualified. Those physical-client checks remain manual acceptance items, not claimed passes.
|
||||
|
||||
Underlying gaps: no structured first-meeting marker; no established general near-name detector (existing related forms are used); initial-reader versus event-other-character knowledge flags have different semantics; canonical saves have no atomic cross-process row version. Focused fingerprints and process locks prevent common stale Context saves but cannot guarantee atomicity against simultaneous saves from every legacy editor. Presence/capability leases are in-memory on the current single application instance; multi-instance hosting would require shared discovery/backplane coordination.
|
||||
|
||||
Map/Location/Floor Plan capability handlers are not added by this programme: location commands return an explicit non-disruptive full-location-editor fallback until a suitable tool advertises the contract. Previous/next appearances are scoped to the selected book. Existing ambiguous/unverified relationship events and structural pair/type/direction changes require the full editor.
|
||||
|
||||
No known Development build/regression blockers remain. Physical-client acceptance and the above underlying-system gaps should be considered explicitly before broader launch claims.
|
||||
|
||||
@ -8,6 +8,7 @@ const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
|
||||
await context.route('**/Writing/Context/EditCharacter*',async r=>{const post=r.request().method()==='POST';if(post)posts++;if(post&&!fail)return r.fulfill({json:{saved:true,bookId:12}});const response=await r.fetch({url:base+'/context-edit-fixture?field=description'+(post?'&invalid=true':''),method:'GET'});await r.fulfill({status:post?422:200,contentType:'text/html',body:await response.text()});});
|
||||
const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/Writing/Context');await page.selectOption('[data-context-tab]','characters');await page.waitForSelector('[data-character-explorer]');
|
||||
step='scene-first compact long catalogue';assert.equal(await page.locator('[data-context-character]').count(),12);assert.match(await page.locator('[data-context-character="5"]').innerText(),/POV/);assert.match(await page.locator('[data-context-character="6"] summary').innerText(),/Mentioned only/);assert.match(await page.locator('[data-context-character="5"]').innerText(),/Earlier hall[\s\S]*Saved room[\s\S]*Following garden/);
|
||||
step='location canonical command and no-handler fallback';await page.evaluate(()=>{window.locationCommands=[];document.querySelector('[data-context-workspace]').addEventListener('context-command',e=>locationCommands.push(e.detail));});await page.locator('[data-context-character="5"] [data-context-location="77"]').click();await page.waitForSelector('[data-context-interaction-status] a');assert.deepEqual(await page.evaluate(()=>locationCommands[0]),{action:'location.focusAtStoryPoint',locationID:77,storyPoint:{chapterID:10,sceneID:22}});assert.equal(await page.locator('[data-context-tab]').first().inputValue(),'characters');
|
||||
step='independent same-tool panes';await page.selectOption('[data-context-layout]','columns');await page.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await page.locator('[data-context-pane="1"] [data-character-filter]').fill('name 10');assert.equal(await page.locator('[data-context-pane="1"] [data-context-character]:visible').count(),1);assert.equal(await page.locator('[data-context-pane="0"] [data-context-character]:visible').count(),12);
|
||||
step='container widths, stacked, mobile, zoom';for(const width of [1366,760,390]){await page.setViewportSize({width,height:800});for(const layout of ['single','columns','rows']){await page.selectOption('[data-context-layout]',layout);await page.waitForTimeout(60);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+layout);}}
|
||||
await page.evaluate(()=>document.documentElement.style.zoom='1.25');assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await page.evaluate(()=>document.documentElement.style.zoom='1');
|
||||
|
||||
19
PlotLine.Tests/Browser/context-live-editing.cjs
Normal file
19
PlotLine.Tests/Browser/context-live-editing.cjs
Normal file
@ -0,0 +1,19 @@
|
||||
// Opt-in Development-only canonical persistence acceptance. Requires an explicitly disposable identity and scope.
|
||||
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
|
||||
(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE,'Disposable Development inputs required');const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));assert(s.characters?.length===2);const browser=await chromium.launch();let step='login';try{
|
||||
const pages=[],counts=[];
|
||||
for(let i=0;i<2;i++){const c=await browser.newContext({viewport:{width:1280,height:900}}),p=await c.newPage();pages.push(p);await p.goto('https://dev.plotdirector.com/Account/Login');await p.locator('[name=Email]').fill(who.Email);await p.locator('[name=Password]').fill(who.Password);await Promise.all([p.waitForURL(u=>u.pathname!='/Account/Login'),p.locator('button[type=submit]').click()]);const count={hub:0,word:0,reads:0};counts.push(count);p.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++;});await p.goto(`https://dev.plotdirector.com/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene}`);await p.waitForSelector('[data-context-tab-fragment]');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]');await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected');await p.evaluate(()=>{window.successes=0;const prior=window.PlotDirector.toast.success;window.PlotDirector.toast.success=(...a)=>{successes++;prior(...a);};});}
|
||||
const [p,remote]=pages,id=s.characters[0],row=`[data-context-character="${id}"]`,stamp='Synthetic Context correction '+Date.now();
|
||||
async function open(field){if(!await p.locator(row).evaluate(n=>n.open))await p.locator(row+' summary').click();await p.locator(row+` [data-context-edit="${field}"]`).click();await p.waitForSelector('[data-context-edit-form]');}
|
||||
async function save(){await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);}
|
||||
step='live canonical description and quiet remote refresh';await open('description');await p.locator('[name=Value]').fill(stamp);await save();await remote.waitForFunction(stamp=>document.querySelector('[data-character-explorer]').textContent.includes(stamp),stamp);assert.equal(await p.evaluate(()=>successes),1);assert.equal(await remote.evaluate(()=>successes),0);
|
||||
step='cancel persists nothing';await open('description');assert.equal(await p.locator('[name=Value]').inputValue(),stamp);await p.locator('[name=Value]').fill('Discarded synthetic draft');p.once('dialog',d=>d.accept());await p.click('[data-context-edit-cancel]');await open('description');assert.equal(await p.locator('[name=Value]').inputValue(),stamp);await p.click('[data-context-edit-cancel]');
|
||||
step='names alias add and persisted spelling';await p.selectOption('[data-context-tab]','names');await p.waitForSelector('[data-context-names]');await p.locator('[data-name-filter]').fill('Synthetic Context person one');await p.locator('[data-name-row]:visible summary').click();await p.locator(`[data-context-edit="alias-add"][data-character-id="${id}"]`).click();await p.waitForSelector('[data-context-edit-form]');const alias='Synthetic alias '+Date.now();await p.locator('[name=Value]').fill(alias);await save();await p.waitForFunction(alias=>document.querySelector('[data-context-names]').textContent.includes(alias),alias);
|
||||
step='live inline validation retains failed draft';await p.locator('[data-name-filter]').fill('Synthetic Context person one');if(!await p.locator(`[data-context-edit="name"][data-character-id="${id}"]`).isVisible())await p.locator('[data-name-row]:visible summary').click();await p.locator(`[data-context-edit="name"][data-character-id="${id}"]`).click();await p.waitForSelector('[data-context-edit-form]');await p.locator('[name=Value]').fill('');await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForSelector('.validation-summary-errors');assert(await p.locator('[data-context-edit-dialog]').isVisible());assert.equal(await p.locator('[name=Value]').inputValue(),'');p.once('dialog',d=>d.accept());await p.click('[data-context-edit-cancel]');
|
||||
if(process.env.PD_CONTEXT_RELATIONSHIPS==='1'){
|
||||
step='live one-relationship create and correction';await p.selectOption('[data-context-tab]','relationships');await remote.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-context-relationships]');await remote.waitForSelector('[data-context-relationships]');
|
||||
const existing=p.locator('[data-context-relationship]');if(await existing.count()===0){await p.locator('[data-context-relationship-edit="scene"]').last().click();await p.waitForSelector('[data-context-edit-form]');await p.selectOption('[name=SourceID]',String(s.characters[0]));await p.selectOption('[name=TargetID]',String(s.characters[1]));const type=await p.locator('[name=TypeID] option').evaluateAll(ns=>ns.find(n=>n.value&&!n.textContent.includes('Family'))?.value);await p.selectOption('[name=TypeID]',type);const state=await p.locator('[name=StateID] option').evaluateAll(ns=>ns.find(n=>n.value)?.value);await p.selectOption('[name=StateID]',state);await p.locator('[name=Notes]').fill('Synthetic relationship evidence');await save();}
|
||||
await p.waitForSelector('[data-context-relationship]');const rr=p.locator('[data-context-relationship]').first();if(!await rr.evaluate(n=>n.open))await rr.locator('summary').first().click();await rr.locator('[data-context-relationship-edit="scene"]').click();await p.waitForSelector('[data-context-edit-form]');const note='Synthetic relationship correction '+Date.now();await p.locator('[name=Notes]').fill(note);await save();await remote.waitForFunction(note=>document.querySelector('[data-context-relationships]').textContent.includes(note),note);assert.equal(await remote.evaluate(()=>successes),0);
|
||||
}
|
||||
assert(counts.every(c=>c.word===0&&c.hub===1));console.log('PASS Development canonical editing: focused persisted values, cancel/unsaved protection, alias add, failed inline name draft retained, one local success/quiet second authenticated session, one connection each, no Word navigation'+(process.env.PD_CONTEXT_RELATIONSHIPS==='1'?', relationship create/correct persisted through existing services':''));
|
||||
} catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await browser.close();}})();
|
||||
@ -24,6 +24,7 @@ const live=!!process.env.PD_CONTEXT_IDENTITY,base=live?'https://dev.plotdirector
|
||||
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='character handler focuses only intended recipient';await destination.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.announcement.panes[0].available);await destination.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('RegisterContextWindow',document.querySelector('[data-context-workspace]').contextController.announcement));const charBefore=counts.map(x=>x.reads);const characterCommand={...command,action:'character.focus',characterID:live?scope.characters?.[0]:5};if(characterCommand.characterID){const focused=await source.evaluate(c=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c),characterCommand);assert.equal(focused.status,'delivered');await destination.waitForSelector(`[data-context-character="${characterCommand.characterID}"].context-reference-focus`);await source.waitForFunction(id=>receipts.some(r=>r.commandID===id&&r.status==='focused'),focused.commandID);assert.equal(counts[0].reads,charBefore[0]);assert.equal(counts[1].reads,charBefore[1]+1);assert.deepEqual(await destination.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position),position);}
|
||||
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);
|
||||
|
||||
2
PlotLine.Tests/Browser/context-touch.cjs
Normal file
2
PlotLine.Tests/Browser/context-touch.cjs
Normal file
@ -0,0 +1,2 @@
|
||||
const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
|
||||
(async()=>{const b=await chromium.launch();try{const c=await b.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,deviceScaleFactor:2});await c.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 c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));await c.route('**/Writing/Context/Position?*',r=>r.fulfill({json:{connected:false}}));await c.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 p=await c.newPage();await p.goto(base+'/Writing/Context');for(const tool of ['characters','names','relationships']){await p.selectOption('[data-context-tab]',tool);await p.waitForSelector('[data-context-tab-fragment]');const first=p.locator('.context-character-row').first();await first.locator('summary').first().tap();await first.locator('summary').first().tap();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.screenshot({path:'/tmp/context-enhancement-'+tool+'-touch.png'});}console.log('PASS touch-emulated Chromium: all three tools, long names, summary tap and no horizontal overflow at 390px. Physical touch/PWA installation not exercised.');}finally{await b.close();}})().catch(e=>{console.error(e.message);process.exitCode=1;});
|
||||
@ -50,6 +50,7 @@ const lease=(extra={})=>({instanceId:'11111111-1111-4111-8111-111111111111',sess
|
||||
step='stacked layout';await page.selectOption('[data-context-layout]','rows');assert.equal(await divider.getAttribute('aria-orientation'),'horizontal');await divider.focus();await page.keyboard.press('ArrowUp');
|
||||
const a=await page.locator('[data-context-pane="0"]').boundingBox(),b=await page.locator('[data-context-pane="1"]').boundingBox();assert(b.y>a.y+a.height);
|
||||
step='single retains second pane selection';await page.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await page.selectOption('[data-context-layout]','single');await page.selectOption('[data-context-layout]','columns');assert.equal(await page.locator('[data-context-pane="1"] [data-context-tab]').inputValue(),'characters');
|
||||
step='unrelated-project notifications do not reload panes';const scopedReads=requests.length;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({projectId:999}));await page.waitForTimeout(80);assert.equal(requests.length,scopedReads);
|
||||
step='same scene accepted content and inactive stale selection';revision=2;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({bookId:12}));await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 2'));
|
||||
await page.selectOption('[data-context-pane="0"] [data-context-tab]','characters');await page.selectOption('[data-context-pane="0"] [data-context-tab]','overview');await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 2'));
|
||||
step='rapid scene/chapter navigation and out of order responses';delayScene='23';await page.evaluate(()=>{const c=document.querySelector('[data-context-workspace]').contextController;c.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23});setTimeout(()=>c.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22}),30);});await page.waitForTimeout(550);assert.equal(await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').getAttribute('data-scene-id'),'22');delayScene=null;
|
||||
|
||||
@ -56,7 +56,9 @@ internal static class NativeCompanionHttpTests
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IStoryContextService>((n,a)=>Task.FromResult<StoryContextViewModel?>(null)));
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IWriterWorkspaceService>((n,a)=>Task.FromResult<PlotLine.ViewModels.ChapterWorkflowViewModel?>(null)));
|
||||
builder.Services.AddSingleton<INativeInstallationRepository>(new MemoryNativeInstallations(user));builder.Services.AddScoped<NativeInstallationService>();builder.Services.AddSingleton(users);builder.Services.AddSingleton(repo);builder.Services.AddSingleton(subscriptions);
|
||||
builder.Services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton<DesktopPairing>();builder.Services.AddSingleton<NativeAnalysisCache>();builder.Services.AddSingleton(NativeWorkflowTests.Proxy<INativeImportRepository>((n,a)=>n=="List"?Task.FromResult<IReadOnlyList<NativeImportedChapter>>([]):throw new Exception("Unexpected import write "+n)));builder.Services.AddScoped<NativeImportService>();builder.Services.AddSingleton<NativeCommandWakeQueue>();builder.Services.AddSingleton<NativeAgentConnections>();builder.Services.AddHostedService<NativeCommandNotificationDispatcher>();builder.Services.AddSingleton<NativePresenceStore>();builder.Services.AddSingleton<INativeReviewRepository>(new MemoryNativeReviews());
|
||||
builder.Services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton<PlotLine.Services.Context.ContextWindows>();
|
||||
builder.Services.AddSingleton(Proxy<ICharacterRepository>((n,a)=>throw new Exception("Unexpected character read "+n)));
|
||||
builder.Services.AddSingleton(Proxy<ILocationRepository>((n,a)=>throw new Exception("Unexpected location read "+n)));builder.Services.AddSingleton<DesktopPairing>();builder.Services.AddSingleton<NativeAnalysisCache>();builder.Services.AddSingleton(NativeWorkflowTests.Proxy<INativeImportRepository>((n,a)=>n=="List"?Task.FromResult<IReadOnlyList<NativeImportedChapter>>([]):throw new Exception("Unexpected import write "+n)));builder.Services.AddScoped<NativeImportService>();builder.Services.AddSingleton<NativeCommandWakeQueue>();builder.Services.AddSingleton<NativeAgentConnections>();builder.Services.AddHostedService<NativeCommandNotificationDispatcher>();builder.Services.AddSingleton<NativePresenceStore>();builder.Services.AddSingleton<INativeReviewRepository>(new MemoryNativeReviews());
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options=>{options.LoginPath="/fixture-login";options.Cookie.SecurePolicy=Microsoft.AspNetCore.Http.CookieSecurePolicy.None;})
|
||||
.AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});
|
||||
builder.Services.AddRateLimiter(o=>o.AddPolicy("native-pair",_=>System.Threading.RateLimiting.RateLimitPartition.GetNoLimiter("fixture")));
|
||||
|
||||
@ -47,6 +47,8 @@ internal static class WritingIntegrationTests
|
||||
var notifications=new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.Instance);
|
||||
await notifications.Invalidate(7,2,3,20);
|
||||
Check(group==NativeCompanionPresenceHub.UserGroup(7)&&eventName=="ContextInvalidated"&&payload!.Contains("bookId"),"Accepted-data invalidations use the authenticated account's existing hub group and lightweight scope");
|
||||
await notifications.Invalidate(7,projectId:1);
|
||||
Check(payload!.Contains("\"projectId\":1")&&payload.Contains("\"bookId\":null"),"Project identity changes invalidate relevant windows across books using only IDs");
|
||||
await notifications.Position(7);
|
||||
Check(eventName=="ContextPositionChanged"&&!payload!.Contains("sceneId"),"Office notifications are hints, not invented authoritative cursor payloads");
|
||||
fail=true;await notifications.Invalidate(7,2);
|
||||
|
||||
@ -24,6 +24,7 @@ public sealed class ContextCharacterEditing(ICharacterService characters,IStoryC
|
||||
public async Task<ContextCharacterEditForm> Read(int bookId,int sceneId,int characterId,string field)=>(await Load(bookId,sceneId,characterId,field)).Form;
|
||||
private async Task<Frame> Load(int bookId,int sceneId,int characterId,string field)
|
||||
{
|
||||
if(string.IsNullOrWhiteSpace(field))throw new ArgumentException("Choose a correction field.");
|
||||
var author=user.UserId??throw new UnauthorizedAccessException();
|
||||
var structure=await access.GetBookStructureAsync(bookId,author)??throw new UnauthorizedAccessException();
|
||||
var book=await books.GetAsync(bookId)??throw new UnauthorizedAccessException();
|
||||
@ -98,7 +99,7 @@ public sealed class ContextCharacterEditing(ICharacterService characters,IStoryC
|
||||
}
|
||||
await characters.UpdateSceneCharacterAsync(edit);
|
||||
}
|
||||
await notifications.Invalidate(user.UserId!.Value,input.BookID);
|
||||
await notifications.Invalidate(user.UserId!.Value,frame.Appearance==null?null:input.BookID,projectId:frame.Character.ProjectID);
|
||||
}finally{mutex.Release();}
|
||||
}
|
||||
}
|
||||
|
||||
@ -60,7 +60,7 @@ public sealed class ContextRelationshipEditing(ICharacterRepository repository,I
|
||||
var edit=new RelationshipEventCreateViewModel{RelationshipEventID=frame.Event?.RelationshipEventID??0,CharacterRelationshipID=r?.CharacterRelationshipID,SceneID=input.SceneID,CharacterAID=input.SourceID,CharacterBID=input.TargetID,RelationshipTypeID=input.TypeID,RelationshipStateID=input.StateID,Intensity=input.Intensity,IsReciprocal=input.Mutual,IsKnownToOtherCharacter=input.Known,Description=input.Notes,ReturnProjectID=frame.ProjectID,ReturnBookID=input.BookID};
|
||||
if(frame.Event==null)await characters.AddRelationshipEventAsync(edit);else await characters.UpdateRelationshipEventAsync(edit);
|
||||
}
|
||||
await notifications.Invalidate(user.UserId!.Value,input.BookID);
|
||||
await notifications.Invalidate(user.UserId!.Value,projectId:frame.ProjectID);
|
||||
}finally{mutex.Release();}
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,8 +6,8 @@ namespace PlotLine.Services;
|
||||
public sealed class ContextWorkspaceNotifications(IHubContext<NativeCompanionPresenceHub> hub, ILogger<ContextWorkspaceNotifications> logger)
|
||||
{
|
||||
public Task Position(int user) => Send(user, "ContextPositionChanged", new { });
|
||||
public Task Invalidate(int user, int? bookId = null, int? chapterId = null, int? sceneId = null)
|
||||
=> Send(user, "ContextInvalidated", new { bookId, chapterId, sceneId });
|
||||
public Task Invalidate(int user, int? bookId = null, int? chapterId = null, int? sceneId = null, int? projectId = null)
|
||||
=> Send(user, "ContextInvalidated", new { bookId, chapterId, sceneId, projectId });
|
||||
private async Task Send(int user, string name, object hint)
|
||||
{
|
||||
try { await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync(name, hint); }
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
<div class="context-location-rail" aria-label="Recorded character locations">
|
||||
@foreach(var item in new[]{("Previous",row.Previous),("Now",row.Now),("Next · future record",row.Next)}){
|
||||
<div><strong>@item.Item1</strong>@if(item.Item2 is {} place){<button type="button" class="btn btn-link btn-sm" data-context-location="@place.LocationID" data-location-scene="@place.SceneID" data-location-chapter="@place.ChapterID">@place.Name</button><a href="/Scenes/Edit/@place.SceneID" target="_blank" rel="noopener" class="small">Source scene</a>}
|
||||
else{<span>@(item.Item1=="Now"?(row.Participation=="Mentioned only"?"Mentioned only · no physical presence implied":"No recorded location here"):"No recorded location")</span>}</div>
|
||||
else{<span>@(item.Item1=="Now"?(row.Participation=="Mentioned only"?"Mentioned only · no physical presence implied":row.Participation=="Unknown"?"Location unknown (recorded presence state)":row.Participation=="Off-screen"?"Off-screen · location not recorded":"No recorded location here"):"No recorded location")</span>}</div>
|
||||
}
|
||||
</div>
|
||||
<dl class="writing-context-facts"><dt>Emotional state</dt><dd>@(string.IsNullOrWhiteSpace(row.Emotion)?"Not recorded in this scene":row.Emotion)</dd><dt>Physical condition</dt><dd>@(string.IsNullOrWhiteSpace(row.Condition)?"Not recorded in this scene":row.Condition)</dd><dt>Reference</dt><dd>@(string.IsNullOrWhiteSpace(row.Character.DefaultDescription)?"No character description recorded":row.Character.DefaultDescription)</dd></dl>
|
||||
|
||||
@ -123,6 +123,7 @@
|
||||
return fields.slice(0,count).some(field=>before[field]!==after[field]);
|
||||
};
|
||||
function invalidate(hint={}) {
|
||||
if(hint.projectId&&scope.projectId&&Number(hint.projectId)!==scope.projectId)return;
|
||||
if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId)return;
|
||||
generation++;cancelRequests();
|
||||
for(const pane of panes){for(const record of pane.records.values()){
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user