From 7ce96acd94cb5a9b09b0b7604a5a67239bf66b55 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Mon, 9 Nov 2026 09:16:37 +0000 Subject: [PATCH] Restore authoritative native cursor following and isolate explicit Word navigation --- .../2026-11-09-cursor-follow-regression.md | 53 +++++++++++++++++++ .../DeveloperVersion.props | 2 +- .../Vsto/NativeRibbon.cs | 6 +-- .../Vsto/WordAdapter.cs | 11 ++-- .../WindowsValidation/Setup/Release.json | 8 +-- .../Browser/writing-context-development.cjs | 11 ++-- .../writing-context-follow-recovery.cjs | 50 +++++++++++++++++ .../Browser/writing-context-navigation.cjs | 4 +- .../WritingContextNavigationTests.cs | 11 ++++ .../Controllers/NativePresenceController.cs | 10 ++-- .../Controllers/NativeWorkspaceController.cs | 9 +++- PlotLine/Controllers/WritingController.cs | 8 +-- .../NativeCompanion/NativePresenceStore.cs | 7 +-- .../wwwroot/js/native-companion-status.js | 12 ++--- .../wwwroot/js/writing-context-components.js | 2 +- PlotLine/wwwroot/js/writing-follow.js | 26 +++++---- 16 files changed, 183 insertions(+), 47 deletions(-) create mode 100644 Docs/WordCompanion/2026-11-09-cursor-follow-regression.md create mode 100644 PlotLine.Tests/Browser/writing-context-follow-recovery.cjs diff --git a/Docs/WordCompanion/2026-11-09-cursor-follow-regression.md b/Docs/WordCompanion/2026-11-09-cursor-follow-regression.md new file mode 100644 index 00000000..92cb07cb --- /dev/null +++ b/Docs/WordCompanion/2026-11-09-cursor-follow-regression.md @@ -0,0 +1,53 @@ +# Word cursor following regression — 9 November 2026 + +## Evidence and limits + +Baseline: `e0525f4` deployed application, `c6cdfbc` shared branch head. Clean worktree, configured `origin` fetched, shared branch already current; no branch/worktree/merge created. + +The user's live report separates two symptoms: Context says **No trustworthy current Word scene**, while the insertion-cursor flashing continues after Context closes and stops when the tray process exits. Atlas cannot reproduce or certify the actual Windows caret visually. + +Development's nginx access log for 08:00–08:59 UTC contains one `/Writing/Context/Navigate` POST, at 08:47:04, returning **409**. There is no repeated successful browser navigation submission in that interval. Source confirms that `NativePresenceController.Update` only consumes an already queued command; it does not create `navigate` commands. VSTO calls `Range.Select()` only in its explicit `command.Kind == "navigate"` branch. Thus repeated navigation commands are **not established as the cause** of the reported flashing. + +Read-only inspection of book 10152's position metadata shows snapshot revision 1, Word revision 0, 8,457 paragraph-position rows (8,366 verified scene rows), and a saved live-session ID different from all three heartbeat identities seen that morning. No manuscript text was read or changed. A position from that previous session must not be treated as trustworthy against a reopened document without a successful existing paragraph synchronisation. This explains why an old snapshot cannot independently prove the new cursor's scene; it does not prove why the native refresh attempts were unsuccessful. The access log contains three failed-capture cleanup DELETEs and no accepted capture upload in that interval. No import, original paragraph IDs, full-book analysis or author snapshot was reset/rebound. + +### Reproduced web defects + +The new `writing-context-follow-recovery.cjs` loads the scripts actually served by Development when `PD_SCRIPT_BASE=https://dev.plotdirector.com` is set. Against `e0525f4`, it fails: a delayed legacy `plotdirector:story-position-changed` event replaces native scene 23 with scene 22. Removing the pinned iframe exposed the direct live workspace to both native and legacy subscriptions. Native heartbeats previously remembered the newer key, so later identical notifications could leave the wrong view displayed. + +Additional controlled interleavings reproduce the status handler's out-of-scope `leases` reference on failure, dropped native invalidations while a status request is in flight, and suppression of retries for a failed fragment at an unchanged native scene. These are browser/protocol simulations, not a replay of the user's Windows machine. + +### Native interference candidate + +`WordAdapter.CaptureSelection` invalidated the entire Word ribbon on **every** positional observation, including the idle one-second probe. The ribbon exposes a local connection label, not cursor-position data. This is a confirmed unnecessary recurring native UI operation, consistent with (but not proof of) the reported tray-dependent flashing. No native code changed in the overnight web deployment, so its temporal association alone does not establish a new Windows defect. + +## Corrections + +- An available selected/active native session is authoritative over legacy broadcasts, even if its current mapping is unresolved. Legacy following still works when native authority is absent. No guessed scene or unsafe cross-session fallback. +- The existing native status updater drains invalidations received during HTTP reads, safely publishes disconnects on failures, retries initial SignalR negotiation through its existing periodic check, and retains the latest observation for late workspace initialization. No second presence service or parallel polling system. +- Same-scene fragment failures can recover on the next authoritative observation. Saved-state changes participate in the observation key. Existing generation/abort protection, tab state and fragment-only HTML validation remain. +- Passive updates never restore focus to browser controls. Explicit keyboard/mouse navigation may preserve its own focus. +- Only trusted user events can request Word navigation. Programmatic scene-control changes may browse saved content but cannot queue a selection. Plot/Metric **Go to scene** uses the genuine click through the existing navigation handler rather than synthesising a select-change event. +- Explicit navigation carries a correlation GUID through browser POST, server queue and existing IPC command. Retried identical requests cannot execute again; changed-target reuse is refused. Receipts are bounded and expire. Capture/cancel commands retain priority. +- Server logs record scene/saved/revision transitions and queued/delivered navigation IDs, instance/session, position and revision. No prose, tokens, passwords or document titles are added to those logs. Normal observations never create commands. +- Connection status explains unsaved documents, reopened/changed session mappings, different manuscript identity and unresolved paragraphs rather than claiming an established live scene. The existing authorised repository/procedure supplies metadata; no SQL or identity changes. +- Native source: positional polling no longer invalidates the ribbon. Connection changes invalidate only the actual status control when its displayed label changes. Executed navigation command IDs are bounded/deduplicated, and their count/latest ID appear in existing Troubleshooting diagnostics. + +Native source is prepared as **1.0.0.22**. Existing unified installer metadata has the matching application/MSI version and a fresh product code, preserving its upgrade family and previous qualified baseline. No Windows package was built, signed, installed or launched on Atlas. The running 1.0.0.21 installation is unchanged. + +## Verification and deployment + +Final build, browser/protocol results, deployed revision and cleanup are recorded below after rollout. No database migration is required. Deployment uses the existing idle-work guard and preserves configuration, uploads, keys and the previous application release. Production is untouched. + +## Windows qualification / handover + +Use the same shared branch `codex/word-companion-native-phase1-20261104`; inspect/preserve the worktree, discover its tracking remote, fetch and fast-forward safely. Do not use desktop automation, launch Word or install unattended while the user is working. + +1. Check the final Atlas code commit recorded below is an ancestor of HEAD. Build through the existing `PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1`; it prepares the managed/VSTO package and does not install. Use the existing signing certificate. No IDE/installer repair, private profile or alternate installation mechanism. +2. Build the existing unified installer with `PlotDirector.NativeCompanion/WindowsValidation/Setup/Build-Setup.ps1 -PackagePath -CertificateThumbprint -ExpectedSourceCommit `. Do not guess an output path or install switch. Verify application **1.0.0.22**, MSI **1.0.22**, payload/signatures and upgrade from the user's actual installed 1.0.0.21 in the normal Windows user environment. Preserve pairing, server settings and associations. Installation remains a separately scheduled user action using that unified installer. +3. In an author-owned disposable Word/test book, save and use the existing **Synchronise from Word** if the UI reports a reopened/changed position map. This verifies current positions through the established workflow; do not manually rewrite IDs, adopt an arbitrary session or rerun a real manuscript import. +4. With Context closed, leave Word idle for 60 seconds, scroll, select text and type continuously. Record whether flashing remains. Troubleshooting's navigation execution count must remain unchanged, and the server must show observations with **no** queued/delivered `navigate`. This tests the ribbon-invalidation candidate; do not declare the cause proven before this comparison. +5. Open Context, select People or another tab, move across scenes and chapters in Word, and type. Context should follow verified scenes, retain its tab and never take focus. Its updates must not increment Word's navigation execution count. Repeated same-scene movement must not select/reposition text. +6. Explicitly Jump/Previous/Next once. Correlate the browser/server `navigationId`, delivered IPC command and native last executed ID: one intended selection, no further commands from acknowledgement. Compare Word's saved/dirty state and prose before/after. Test both directions, rapid movement, multiple document selection, disconnect, tray restart and reconnect. If a map is unresolved, require a useful explanation and preserve saved browsing rather than guessing. +7. If flashing persists, capture native diagnostics/operation timings and Windows/Word version with the navigation counter at zero. Distinguish read-only polling, repeated extraction, other add-ins and connection churn from actual selection commands. Do not add delays, disable author typing or weaken snapshot validation to hide the symptom. + +Actual Word responsiveness, COM execution, native compilation and caret behaviour remain Windows-only checks. The browser and server test client do not establish them. diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index 2d9e0d3b..2ff5caa4 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.21 +1.0.0.22 diff --git a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs index a8caaead..7c609266 100644 --- a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs +++ b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs @@ -8,11 +8,11 @@ namespace PlotDirector.WordAddIn [ComVisible(true)] public sealed class NativeRibbon:Office.IRibbonExtensibility { - private readonly Func adapter;private Office.IRibbonUI ui; + private readonly Func adapter;private Office.IRibbonUI ui;private string lastStatus; public NativeRibbon(Func adapter){this.adapter=adapter;} public string GetCustomUI(string ribbonID){using(var reader=new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PlotDirector.WordAddIn.Ribbon.xml")))return reader.ReadToEnd();} - public void OnLoad(Office.IRibbonUI ribbonUI){ui=ribbonUI;} - public void Invalidate(){try{ui?.Invalidate();}catch(COMException){}} + public void OnLoad(Office.IRibbonUI ribbonUI){ui=ribbonUI;lastStatus=GetStatus(null);} + public void Invalidate(){try{var status=GetStatus(null);if(status==lastStatus)return;lastStatus=status;ui?.InvalidateControl("PlotDirectorStatus");}catch(COMException){}} public string GetStatus(Office.IRibbonControl control)=>"Local Companion: "+(adapter()?.ConnectionState??"unavailable"); public void RemoveLegacyMarkers(Office.IRibbonControl control)=>adapter()?.RemoveLegacyMarkers(); public void OpenCompanion(Office.IRibbonControl control)=>adapter()?.OpenCompanion(); diff --git a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs index dc7debdb..f27cdbfb 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs @@ -47,6 +47,7 @@ namespace PlotDirector.WordAddIn private bool disposed;private bool activationPending,traySupported; public string WordCountSummary=>active?.WordCount?.ToString("N0")??"not read / stale"; private long busyFailures; + private long navigationExecutions;private Guid lastNavigationId;private readonly Queue completedNavigationIds=new Queue(); private string lastWordError; private int documentCollectionGeneration; private double lastBatchMs; @@ -54,6 +55,7 @@ namespace PlotDirector.WordAddIn public string ConnectionState { get; private set; } = "Connecting"; public bool HasActiveDocument => active != null; public string Diagnostics => "PlotDirector " + typeof(WordAdapter).Assembly.GetName().Version + "\nAgent: " + ConnectionState + + "\nWord navigation executions: " + navigationExecutions + " · last command: " + lastNavigationId + "\nOpen sessions: " + documents.Count + "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth + "\nAgent startup: " + AgentProcess.LaunchStatus @@ -177,9 +179,9 @@ namespace PlotDirector.WordAddIn try { selection = Com(() => application.Selection); - if(selection==null){active=null;invalidateRibbon();return;} + if(selection==null){active=null;return;} var document = Com(() => selection.Document); - if(document==null){active=null;invalidateRibbon();return;} + if(document==null){active=null;return;} if (!documents.TryGetValue(document,out var state)) { Open(document); return; } range = Com(() => selection.Range); if(range==null)return; @@ -199,7 +201,7 @@ namespace PlotDirector.WordAddIn active = state; link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,WordSaved=saved&&Com(()=>application.BackgroundSavingStatus)==0,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth}); // Prose is read only on an explicit Companion request; cursor observations never rescan it. - invalidateRibbon(); + } finally { Release(range); Release(selection); } } @@ -245,8 +247,9 @@ namespace PlotDirector.WordAddIn } else if(command.Kind=="cancel"){CancelExtraction(doc);doc.AiJob=Guid.Empty;} else if(command.Kind=="navigate"&&command.Chapter!=null){ + if(completedNavigationIds.Contains(command.Id)){Reply(command,"ok");return;} var position=command.Chapter.Start;if(position<0||position>DocumentEnd(doc.Document))throw new InvalidOperationException("Position no longer exists."); - Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));Com(()=>{range.Select();return true;});}finally{Release(range);} + Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));Com(()=>{range.Select();return true;});navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}finally{Release(range);} } else if(command.Kind=="associate"){ if(command.Remember){ diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json index 6b5f4b46..8a1bb16f 100644 --- a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json @@ -1,9 +1,9 @@ { - "version": "1.0.0.21", - "msiVersion": "1.0.21", - "productCode": "{0BF0FC05-40A0-4B6E-B7BC-1FEA9A7C8530}", + "version": "1.0.0.22", + "msiVersion": "1.0.22", + "productCode": "{79A10C5C-D417-4F93-A854-C6E114B4532D}", "upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}", - "atlasBaseline": "9395e094f87a8718ee430255746f0b841d3f37ba", + "atlasBaseline": "c6cdfbc3b17107a8d269561c319d946c8e337835", "baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}", "baselineSetupSha256": "9526E3781EB2EF9936132786E1E2242633349933A553E93E7A7D0B038160A7FF" } diff --git a/PlotLine.Tests/Browser/writing-context-development.cjs b/PlotLine.Tests/Browser/writing-context-development.cjs index 921f9dbb..1b9fa3ef 100644 --- a/PlotLine.Tests/Browser/writing-context-development.cjs +++ b/PlotLine.Tests/Browser/writing-context-development.cjs @@ -12,7 +12,7 @@ const base='https://dev.plotdirector.com';let step='validate fixture files'; const browser=await chromium.launch();let keepalive; try{ const context=await browser.newContext();await context.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')})); - const page=await context.newPage();step='normal login';await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);await Promise.all([page.waitForURL(u=>u.pathname!='/Account/Login'),page.locator('form:has(input[name=Password]) button[type=submit]').click()]); + const page=await context.newPage();let navigationForm;page.on('request',request=>{if(request.url().endsWith('/Writing/Context/Navigate')&&request.method()==='POST')navigationForm=request.postData();});step='normal login';await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);await Promise.all([page.waitForURL(u=>u.pathname!='/Account/Login'),page.locator('form:has(input[name=Password]) button[type=submit]').click()]); step='browser-approved persistent pairing';const verifier=crypto.randomBytes(32).toString('base64url'),connectionId=crypto.randomUUID(); let response=await page.request.post(base+'/api/native-companion/pair',{data:{challenge:crypto.createHash('sha256').update(verifier).digest('hex').toUpperCase(),persistent:true,connectionId,deviceName:'Atlas Context protocol verification'}});assert.equal(response.status(),200);const {code}=await response.json(); await page.goto(base+'/native-companion/authorize?code='+code);const csrf=await page.locator('[name=__RequestVerificationToken]').inputValue();response=await page.request.post(base+'/native-companion/authorize',{form:{code,retainImport:'true',__RequestVerificationToken:csrf}});assert.equal(response.status(),200); @@ -23,17 +23,20 @@ const base='https://dev.plotdirector.com';let step='validate fixture files'; step='live paragraph cursor resolution';let presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[0]);assert.equal(presence.chapterId,scope.Chapters[0]); keepalive=setInterval(()=>void heartbeat().catch(()=>{}),10000); step='direct Context and compiled fragments';await page.goto(base+`/native-companion/workspace?bookId=${scope.Book}&instanceId=${scope.Instance}&sessionId=${scope.Session}&view=context`);await page.waitForURL(u=>u.pathname==='/Writing/Context');await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[0]}"]`);assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('.pd-ribbon,.pd-titlebar').count(),0);await page.evaluate(()=>window.originalContextShell=document.querySelector('[data-writing-context]')); - await page.click('[data-writing-context-tab=people]');await page.selectOption('[data-writing-context-scene-select]',String(scope.Scenes[1])); + await page.click('[data-writing-context-tab=people]'); + step='passive cursor following across chapters';for(const next of [scope.SceneStarts[1],scope.SceneStarts[0]]){cursor=next;await heartbeat();await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${next===scope.SceneStarts[0]?scope.Scenes[0]:scope.Scenes[1]}"]`);}for(let i=0;i<5;i++)await heartbeat();assert.equal(commands.length,0,'Passive presence and scene changes cannot queue Word selection');await page.locator('[data-writing-context-scene-select]').press('End'); await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[1]}"]`);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested')); step='existing native navigation command';await heartbeat();assert.equal(commands.length,1);assert.equal(commands[0].kind,'navigate');assert.equal(commands[0].sessionId.toLowerCase(),scope.Session.toLowerCase());assert.equal(commands[0].revision,1);assert.equal(commands[0].chapter.start,scope.SceneStarts[1]); + assert.equal(commands[0].id,new URLSearchParams(navigationForm).get('navigationId'));const acceptedNavigationForm=navigationForm; cursor=commands[0].chapter.start;presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[1]);assert.equal(presence.chapterId,scope.Chapters[1]);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Following Word');assert.equal(commands.length,1,'Following a cursor must not command Word back');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible()); + step='duplicate explicit request after acknowledgement';response=await page.request.post(base+'/Writing/Context/Navigate',{form:Object.fromEntries(new URLSearchParams(acceptedNavigationForm))});assert.equal(response.status(),200);assert.ok(!(await heartbeat()).navigation);assert.equal(commands.length,1,'Retried explicit navigation is not reexecuted'); step='stale Word revision refusal';revision=2;await heartbeat();const body={bookId:String(scope.Book),sceneId:String(scope.Scenes[0]),instanceId:scope.Instance,sessionId:scope.Session,__RequestVerificationToken:await page.locator('[data-writing-context] [name=__RequestVerificationToken]').inputValue()};response=await page.request.post(base+'/Writing/Context/Navigate',{form:body});assert.equal(response.status(),409);assert.match((await response.json()).message,/mapping|synchronise/i);assert.ok(!(await heartbeat()).navigation); revision=1;await page.request.delete(presencePath(),{headers});sequence=0;await heartbeat(); step='actual saved metrics and empty plot data';await page.click('[data-writing-context-tab=metrics]');await page.waitForSelector('[data-writing-component=metrics][data-loaded=true]');assert.ok(await page.locator('[data-context-metric-select] option').count()>0);await page.click('[data-writing-context-tab=plots]');await page.waitForSelector('[data-writing-component=plots][data-loaded=true]');assert.ok(await page.getByText('No saved plot-line developments are available for this book.').isVisible()); - step='disconnect and saved navigation';clearInterval(keepalive);keepalive=null;await page.request.delete(presencePath(),{headers});await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected'),null,{timeout:25000});await page.click('[data-writing-context-tab=people]');await page.selectOption('[data-writing-context-scene-select]',String(scope.Scenes[0]));await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[0]}"]`); + step='disconnect and saved navigation';clearInterval(keepalive);keepalive=null;await page.request.delete(presencePath(),{headers});await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected'),null,{timeout:25000});await page.click('[data-writing-context-tab=people]');await page.locator('[data-writing-context-scene-select]').press('Home');await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[0]}"]`); step='reconnect actual cursor wins';cursor=scope.SceneStarts[1];sequence=0;presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[1]);await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[1]}"]`);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.ok(await page.evaluate(()=>originalContextShell===document.querySelector('[data-writing-context]')));assert.equal(commands.length,1,'Reconnect cannot manufacture navigation commands'); step='anonymous and antiforgery refusal';const bare=await browser.newContext();const unauthorised=await bare.request.get(base+`/Writing/Context/Metrics?projectId=${scope.Project}&bookId=${scope.Book}`,{maxRedirects:0});assert.ok([302,401].includes(unauthorised.status()));await bare.close();response=await page.request.post(base+'/Writing/Context/Navigate',{form:{bookId:String(scope.Book),sceneId:String(scope.Scenes[0])}});assert.equal(response.status(),400); step='sign out test installation';await page.request.post(base+'/api/native-companion/revoke',{data:{installationId:tokens.installationId,credential:tokens.deviceSecret,connectionId,nextCredential:'',rotationId:crypto.randomUUID()}});response=await page.request.get(base+'/api/native-companion/books',{headers});assert.equal(response.status(),401); - console.log('PASS live Development: normal browser approval, real native presence and persisted paragraph mapping, direct iframe-free Context, cross-chapter explicit command at exact saved position, cursor acknowledgement without loops, stable People tab/shell, stale revision refusal, read-only metrics/plots, disconnected browsing, reconnect precedence, authentication/antiforgery and revocation. Protocol client only; actual Word execution remains unverified.'); + console.log('PASS live Development: normal browser approval, real native presence and persisted paragraph mapping, direct iframe-free Context, cross-chapter explicit command at exact saved position, cursor acknowledgement without loops, stable People tab/shell, stale revision refusal, read-only metrics/plots, disconnected browsing, reconnect precedence, authentication/antiforgery and revocation. Includes repeated passive cursor observations and duplicate explicit-request refusal after acknowledgement. Protocol client only; actual Word execution remains unverified.'); }finally{if(keepalive)clearInterval(keepalive);await browser.close();} })().catch(error=>{fs.writeFileSync('/tmp/pd-context-development-error.log',String(error.stack),{mode:0o600});console.error('FAIL Development Context verification at '+step+'; private diagnostic saved.');process.exit(1);}); diff --git a/PlotLine.Tests/Browser/writing-context-follow-recovery.cjs b/PlotLine.Tests/Browser/writing-context-follow-recovery.cjs new file mode 100644 index 00000000..a024a7e0 --- /dev/null +++ b/PlotLine.Tests/Browser/writing-context-follow-recovery.cjs @@ -0,0 +1,50 @@ +// Real scripts in Chromium with controlled native/legacy event interleavings. No Word automation. +const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict'); +(async()=>{const browser=await chromium.launch();try{ + const page=await browser.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message)); + const html=`
`; + const fragment=(scene)=>`
Overview saved data
People saved data
`; + let current=22,failStatus=false,holdStatus=false,release,reads=0,commands=0,fragmentFailure=false,holdFragment=false,releaseFragment; + await page.route('https://context.test/**',async r=>{const u=new URL(r.request().url()); + if(u.pathname==='/')return r.fulfill({contentType:'text/html',body:html}); + if(u.pathname==='/native-companion/status'){ + reads++;const snapshot=current;if(holdStatus){holdStatus=false;await new Promise(resolve=>release=resolve);} + return r.fulfill(failStatus?{status:503}:{json:[{instanceId:'instance',sessionId:'session',bookId:12,chapterId:snapshot===22?10:11,sceneId:snapshot,wordAvailable:true,wordSaved:true,active:true,documentTitle:'Synthetic',expires:new Date(Date.now()+45000).toISOString()}]});} + if(u.pathname==='/Writing/Context/Scene'){ + if(holdFragment){holdFragment=false;await new Promise(resolve=>releaseFragment=resolve);} + return r.fulfill(fragmentFailure?{status:503}:{contentType:'text/html',body:fragment(Number(u.searchParams.get('sceneId')))});} + if(u.pathname==='/Writing/Context/Navigate'){commands++;assert.ok(new URLSearchParams(r.request().postData()).get('navigationId'));return r.fulfill({json:{message:'Navigation requested in Word.'}});} + return r.fulfill({json:{known:false}}); + }); + await page.goto('https://context.test/');await page.evaluate(fragment=>document.querySelector('[data-writing-context-content]').innerHTML=fragment,fragment(22)); + await page.evaluate(()=>{window.hubHandlers={};window.focusCalls=0;window.focus=()=>focusCalls++;window.intervals=[];window.setInterval=f=>(intervals.push(f),intervals.length);window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return{state:'Disconnected',on:(name,fn)=>hubHandlers[name]=fn,onreconnected:()=>{},start:async()=>{},stop:async()=>{}}}}};window.PlotDirectorWritingWorkspace={watchWorkspace:async()=>null};}); + for(const name of ['story-position','writing-follow','writing-context','native-companion-status']){ + let script=fs.readFileSync(path.resolve(__dirname,'../../PlotLine/wwwroot/js/'+name+'.js'),'utf8'); + if(process.env.PD_SCRIPT_BASE)script=await(await page.request.get(process.env.PD_SCRIPT_BASE+'/js/'+name+'.js')).text(); + await page.addScriptTag({content:script}); + } + const scene=async id=>page.waitForFunction(id=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId===String(id),id); + const pulse=()=>page.evaluate(()=>intervals[0]());await page.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='true'); + await page.click('[data-writing-context-tab=people]');await page.evaluate(()=>{window.elementFocusCalls=0;const original=HTMLElement.prototype.focus;HTMLElement.prototype.focus=function(...args){elementFocusCalls++;return original.apply(this,args);};}); + current=23;await pulse();await scene(23);assert.equal(commands,0);assert.equal(await page.evaluate(()=>elementFocusCalls),0,'passive following must not refocus any browser control');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible()); + // A delayed legacy broadcast must not override a live native cursor scene. + await page.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,bookId:12,chapterId:10,sceneId:22,source:'WordCompanion'}}))); + await page.waitForTimeout(120);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'23','stale legacy position cannot replace live native scene'); + for(let i=0;i<8;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,0);assert.equal(await page.evaluate(()=>focusCalls),0); + // Status failure must dispatch disconnection, not throw ReferenceError for an out-of-scope leases variable. + failStatus=true;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected')); + failStatus=false;current=22;await pulse();await scene(22);assert.deepEqual(errors,[]); + // SignalR invalidation during an HTTP read must be drained, not discarded until a 15-second poll. + holdStatus=true;await pulse();await page.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='true');while(!release)await page.waitForTimeout(10); + const before=reads;current=23;await page.evaluate(()=>hubHandlers.NativePresenceChanged());await page.waitForTimeout(300);release();await scene(23);assert.ok(reads>before,'pending invalidation triggers a trailing authoritative read'); + // Failed fragment read can recover on an unchanged authoritative scene, without navigating Word. + fragmentFailure=true;current=22;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Context unavailable');fragmentFailure=false;await pulse();await scene(22);assert.equal(commands,0); + // Programmatic scene changes can browse saved information but may not command Word. + await page.selectOption('[data-writing-context-scene-select]','23');await scene(23);assert.equal(commands,0); + // Genuine keyboard action requests exactly one command; its acknowledgement is passive. + await page.locator('[data-writing-context-scene-select]').press('Home');await scene(22);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested'));assert.equal(commands,1); + current=22;for(let i=0;i<4;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,1);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.deepEqual(errors,[]); + console.log('PASS native/legacy race, cross-chapter cursor following, repeated presence without commands/focus, status failure recovery, in-flight invalidation, unchanged-scene fragment retry, trusted explicit navigation and acknowledgement without feedback; simulated Chromium protocol, not Word'); + // Native safety source guard: ordinary polling must never invalidate the ribbon or select a range. + const adapter=fs.readFileSync(path.resolve(__dirname,'../../PlotDirector.NativeCompanion/Vsto/WordAdapter.cs'),'utf8');const observation=adapter.split('private void CaptureSelection()')[1].split('private int DocumentEnd')[0];assert.doesNotMatch(observation,/invalidateRibbon\(|\.Select\(/);assert.match(adapter,/command.Kind=="navigate"/);console.log('PASS native source invariant: selection observation contains no ribbon invalidation or range selection (not runtime Word proof)'); +}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); diff --git a/PlotLine.Tests/Browser/writing-context-navigation.cjs b/PlotLine.Tests/Browser/writing-context-navigation.cjs index 67947e8e..a0bf7b4a 100644 --- a/PlotLine.Tests/Browser/writing-context-navigation.cjs +++ b/PlotLine.Tests/Browser/writing-context-navigation.cjs @@ -18,7 +18,7 @@ const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; },theme); for(const script of ['story-position','writing-follow','writing-context'])await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/'+script+'.js')}); assert.equal(await page.locator('iframe').count(),0); - await page.click('[data-writing-context-tab=people]');await page.locator('[data-writing-context-tab=people]').press('ArrowRight');assert.ok(await page.locator('[data-writing-context-panel=relationships]').isVisible());await page.locator('[data-writing-context-tab=relationships]').press('ArrowLeft');await page.selectOption('[data-writing-context-scene-select]','23'); + await page.click('[data-writing-context-tab=people]');await page.locator('[data-writing-context-tab=people]').press('ArrowRight');assert.ok(await page.locator('[data-writing-context-panel=relationships]').isVisible());await page.locator('[data-writing-context-tab=relationships]').press('ArrowLeft');await page.locator('[data-writing-context-scene-select]').press('End'); await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='23');await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested')); assert.equal(commands,1);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-chapter-id'),'11'); assert.ok(await page.evaluate(()=>originalWritingShell===document.querySelector('[data-writing-context]'))); @@ -28,7 +28,7 @@ const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; await beat(23);await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='23');assert.equal(commands,2,'Word follow must not command Word back');assert.ok(Math.abs(await page.evaluate(()=>scrollY)-150)<=2,`Word scene changes retain page scroll where space permits: ${width} ${theme}, actual ${await page.evaluate(()=>scrollY)}`);assert.equal(await page.evaluate(()=>focusCalls),0,'cursor following must not focus the browser window');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible()); await page.evaluate(()=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[]})));await page.click('[data-writing-scene-step="22"]');await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='22'); await beat(23);await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='23');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible(),'reconnection follows actual Word scene without resetting view'); - const before=commands;fullPage=true;await page.selectOption('[data-writing-context-scene-select]','22');await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Context unavailable');assert.equal(await page.locator('nav').filter({hasText:'Timeline shell must never appear here'}).count(),0);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'23');assert.equal(commands,before,'invalid fragments cannot trigger Word navigation'); + const before=commands;fullPage=true;await page.locator('[data-writing-context-scene-select]').press('Home');await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Context unavailable');assert.equal(await page.locator('nav').filter({hasText:'Timeline shell must never appear here'}).count(),0);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'23');assert.equal(commands,before,'invalid fragments cannot trigger Word navigation'); assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`overflow ${width} ${theme}`); await page.close(); } diff --git a/PlotLine.Tests/WritingContextNavigationTests.cs b/PlotLine.Tests/WritingContextNavigationTests.cs index 3bb9f9f0..f94b6d7f 100644 --- a/PlotLine.Tests/WritingContextNavigationTests.cs +++ b/PlotLine.Tests/WritingContextNavigationTests.cs @@ -47,6 +47,17 @@ internal static class WritingContextNavigationTests var lease=presence.Read(7,12).Single();var capture=Guid.NewGuid();Check(presence.RequestCapture(7,lease,capture),"Fixture starts an existing capture command"); Check(await Navigate() is ConflictObjectResult&&presence.TakeNavigation(7,"installation",instance,session)?.Id==capture,"Navigation cannot overwrite pending capture, synchronisation or maintenance work"); presence.Remove(7,"installation",instance,session);Check(await Navigate() is ConflictObjectResult,"Disconnected Word is reported honestly; saved scene navigation remains independent"); + Beat();var explicitId=Guid.NewGuid(); + Check(presence.Navigate(7,12,instance,session,manuscript,3,100,navigationId:explicitId),"Explicit navigation has a stable correlation identity"); + Check(presence.TakeNavigation(7,"installation",instance,session)?.Id==explicitId,"Navigation identity reaches the one-shot native command"); + for(int i=0;i<20;i++)Beat(); + Check(presence.TakeNavigation(7,"installation",instance,session)==null,"Twenty ordinary presence observations never queue a selection command"); + Check(presence.Navigate(7,12,instance,session,manuscript,3,100,navigationId:explicitId)&&presence.TakeNavigation(7,"installation",instance,session)==null,"Retried explicit request cannot execute the same navigation twice after acknowledgement"); + Check(!presence.Navigate(7,12,instance,session,manuscript,3,110,navigationId:explicitId),"A correlation identity cannot be reused for a different target"); + var statusAccess=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(new(){BookId=12,ManuscriptId=manuscript,SessionId=Guid.NewGuid(),WordRevision=3})); + var diagnostics=await native.Status(statusAccess) as JsonResult; + var diagnosticJson=System.Text.Json.JsonSerializer.Serialize(diagnostics?.Value); + Check(diagnosticJson.Contains("Word reopened or changed"),"Reopened-session mapping is explained without reassigning paragraph identities"); var denied=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(false)); Check(await controller.ContextPlotLines(7,12,null!,denied) is NotFoundResult,"Plot Lines rejects unauthorised projects before loading saved data"); Check(await controller.ContextMetrics(7,12,null!,denied,null!,null!) is NotFoundResult,"Recorded metrics rejects unauthorised projects before querying raw repositories"); diff --git a/PlotLine/Controllers/NativePresenceController.cs b/PlotLine/Controllers/NativePresenceController.cs index 0aee65de..bb785380 100644 --- a/PlotLine/Controllers/NativePresenceController.cs +++ b/PlotLine/Controllers/NativePresenceController.cs @@ -8,7 +8,7 @@ using PlotLine.Data; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")] -public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext? live=null,INativePositionRepository? positions=null,NativeManuscriptCapture? capture=null,IHubContext? wizard=null):ControllerBase +public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext? live=null,INativePositionRepository? positions=null,NativeManuscriptCapture? capture=null,IHubContext? wizard=null,ILogger? logger=null):ControllerBase { private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); private string Grant=>User.FindFirstValue("NativeCompanion.Grant")??throw new InvalidOperationException(); @@ -31,10 +31,14 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC if(input.ChapterId.HasValue&&chapter==null){input.ChapterId=null;input.SceneId=null;} var before=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session); if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."}); - if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable||before.Position.WordRunning!=input.WordRunning))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted); + if(before==null||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.WordSaved!=input.WordSaved||before.Position.Revision!=input.Revision) + logger?.LogInformation("Native cursor observation User={User} Book={Book} Instance={Instance} Session={Session} Sequence={Sequence} Manuscript={Manuscript} WordRevision={WordRevision} Saved={Saved} Cursor={Cursor} Chapter={Chapter} Scene={Scene} ParagraphSnapshot={HasSnapshot} ParagraphRevision={ParagraphRevision}; observation does not request navigation",Author,input.BookId,instance,session,input.Sequence,input.ManuscriptId,input.Revision,input.WordSaved,input.CursorStart,input.ChapterId,input.SceneId,paragraphPosition?.HasSnapshot,paragraphPosition?.Revision); + if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable||before.Position.WordRunning!=input.WordRunning||before.Position.WordSaved!=input.WordSaved))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted); if(input.CaptureRequestId.HasValue&&capture!=null&&wizard!=null){var progress=await capture.Progress(Author,Grant,input.CaptureRequestId.Value,input.CaptureProgress,instance,session,input.ManuscriptId,input.Revision);if(progress!=null)await wizard.Clients.Group(WordCompanionFollowHub.PresenceGroup(Author)).SendAsync("OnboardingScanProgress",progress,HttpContext.RequestAborted);} if(input.CanParagraphSync&&capture!=null){var lease=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);if(lease!=null)await capture.ObserveParagraphSave(Author,lease);} - input.CatalogVersion=presence.CatalogVersion(Author);input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);return Ok(input); + input.CatalogVersion=presence.CatalogVersion(Author);input.Navigation=presence.TakeNavigation(Author,Grant,instance,session); + if(input.Navigation is {Kind:"navigate"} command)logger?.LogInformation("Deliver explicit Word navigation Id={NavigationId} User={User} Book={Book} Instance={Instance} Session={Session} Revision={Revision} Position={Position}",command.Id,Author,input.BookId,instance,session,command.Revision,command.Chapter?.Start); + return Ok(input); } [HttpDelete("instances/{instance:guid}/documents/{session:guid}/presence")] public IActionResult Remove(Guid instance,Guid session,long? throughSequence=null){presence.Remove(Author,Grant,instance,session,throughSequence);return Ok(new NativePresence());} diff --git a/PlotLine/Controllers/NativeWorkspaceController.cs b/PlotLine/Controllers/NativeWorkspaceController.cs index 7d250124..f5218348 100644 --- a/PlotLine/Controllers/NativeWorkspaceController.cs +++ b/PlotLine/Controllers/NativeWorkspaceController.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotDirector.Companion.Protocol; using PlotLine.Data; +using PlotLine.Models; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [Authorize,Route("native-companion")] @@ -30,11 +31,15 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB public async Task ImportCommit(string confirmation,bool confirm,[FromServices] NativeImportService importer) {if(!confirm)return BadRequest("Explicit import confirmation is required.");try{return View(await importer.Commit(Author,confirmation));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return Conflict(e.Message);}catch(Microsoft.Data.SqlClient.SqlException){return Conflict("Import could not commit. Review decisions are preserved. Preview again; existing story data has not been replaced.");}} [HttpGet("status")] - public async Task Status() + public async Task Status([FromServices] IParagraphManuscriptRepository? paragraphs=null) { Response.Headers.CacheControl="no-store";var leases=presence.Read(Author,0);var allowed=new HashSet{0}; foreach(var book in leases.Select(l=>l.Position.BookId).Where(b=>b>0).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book); - return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)})); + var snapshots=new Dictionary(); + if(paragraphs!=null)foreach(var book in leases.Where(l=>l.Position.WordAvailable&&allowed.Contains(l.Position.BookId)&&l.Position.BookId>0).Select(l=>l.Position.BookId).Distinct())snapshots[book]=await paragraphs.Status(Author,book); + return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.CanParagraphSync, + positionMessage=l.Position.WordSaved==false?"Save Word, then synchronise to refresh its scene mapping":l.Position.SceneId.HasValue?null:snapshots.GetValueOrDefault(l.Position.BookId) is {} snapshot?(snapshot.ManuscriptId!=l.Position.ManuscriptId?"This Word document does not match the book's saved manuscript identity":snapshot.SessionId!=l.Session||snapshot.WordRevision!=l.Position.Revision?"Word reopened or changed; synchronise from Word to verify this session's paragraph positions":snapshot.Paused?"Scene mapping is unresolved; synchronisation is paused while existing book processing finishes":"Current paragraph has no verified scene assignment") : "Synchronise from Word to establish a verified paragraph mapping", + updated=l.Updated,expires=l.Updated.AddSeconds(45)})); } [HttpGet("reviews/{id:guid}")] public async Task Review(Guid id) diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index 712ea88b..30bee065 100644 --- a/PlotLine/Controllers/WritingController.cs +++ b/PlotLine/Controllers/WritingController.cs @@ -250,7 +250,7 @@ public sealed class WritingController( [HttpPost("Context/Navigate"),ValidateAntiForgeryToken] public async Task NavigateWord(int bookId,int sceneId,Guid? instanceId,Guid? sessionId, - [FromServices] IWordCompanionRepository access,[FromServices] IParagraphManuscriptRepository paragraphs,[FromServices] NativePresenceStore presence) + [FromServices] IWordCompanionRepository access,[FromServices] IParagraphManuscriptRepository paragraphs,[FromServices] NativePresenceStore presence,Guid? navigationId=null) { if(!ModelState.IsValid||bookId<=0||sceneId<=0||instanceId.HasValue!=sessionId.HasValue)return BadRequest(new{message="Choose a valid scene and a complete Word document session. No navigation was sent."}); var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); @@ -265,9 +265,11 @@ public sealed class WritingController( var target=state.Scenes.FirstOrDefault(s=>!s.Retired&&s.CanonicalId==sceneId&&s.ChapterId==chapter.ChapterId); var first=target==null?null:state.Paragraphs.Where(p=>p.Story&&p.SceneId==target.Id).OrderBy(p=>p.Occurrence.Ordinal).FirstOrDefault(); if(first?.PositionVerified!=true)return Conflict(new{message="The scene start is unresolved. Saved scene information remains available."}); + var commandId=navigationId??Guid.NewGuid(); var verified=await paragraphs.Position(user,bookId,state.ManuscriptId,state.SessionId,state.WordRevision,first.Occurrence.Start); - if(HttpContext.RequestAborted.IsCancellationRequested||verified?.HasSnapshot!=true||verified.Revision!=state.Revision||verified.SceneID!=sceneId||verified.ChapterID!=chapter.ChapterId||!presence.Navigate(user,bookId,lease.Instance,lease.Session,state.ManuscriptId,state.WordRevision,first.Occurrence.Start,requireSaved:true))return Conflict(new{message="The Word mapping changed or Word is busy. No navigation was sent."}); - return Ok(new{message="Navigation requested in Word."}); + if(HttpContext.RequestAborted.IsCancellationRequested||verified?.HasSnapshot!=true||verified.Revision!=state.Revision||verified.SceneID!=sceneId||verified.ChapterID!=chapter.ChapterId||!presence.Navigate(user,bookId,lease.Instance,lease.Session,state.ManuscriptId,state.WordRevision,first.Occurrence.Start,requireSaved:true,navigationId:commandId))return Conflict(new{message="The Word mapping changed or Word is busy. No navigation was sent."}); + logger.LogInformation("Explicit Context navigation queued Id={NavigationId} Trace={Trace} User={User} Book={Book} Scene={Scene} Instance={Instance} Session={Session} Revision={Revision} Position={Position}",commandId,HttpContext.TraceIdentifier,user,bookId,sceneId,lease.Instance,lease.Session,state.WordRevision,first.Occurrence.Start); + return Ok(new{navigationId=commandId,message="Navigation requested in Word."}); } private static IReadOnlyList BuildSceneOptions(SceneEditViewModel scene) diff --git a/PlotLine/Services/NativeCompanion/NativePresenceStore.cs b/PlotLine/Services/NativeCompanion/NativePresenceStore.cs index 2b127aed..351db1bd 100644 --- a/PlotLine/Services/NativeCompanion/NativePresenceStore.cs +++ b/PlotLine/Services/NativeCompanion/NativePresenceStore.cs @@ -8,8 +8,9 @@ public sealed class NativePresenceStore(TimeProvider clock) public Guid CatalogVersion(int user){lock(gate)return catalogs.GetValueOrDefault(user,catalogEpoch);} public void BooksChanged(int user){lock(gate){if(catalogs.Count>=4096)catalogs.Clear();catalogs[user]=Guid.NewGuid();}} private readonly Dictionary<(int,Guid,Guid),AdapterCommand> navigation=[]; + private readonly Dictionary<(int,Guid,Guid,Guid),(DateTimeOffset Expires,long Revision,int Start)> navigationReceipts=[]; private readonly object gate=new();private readonly Dictionary<(int,Guid,Guid),NativeLease> leases=[];private readonly Dictionary revoked=[]; - private void Prune(){var now=clock.GetUtcNow();foreach(var key in leases.Where(p=>now-p.Value.Updated>=TimeSpan.FromSeconds(45)||p.Value.GrantExpires<=now).Select(p=>p.Key).ToArray()){leases.Remove(key);navigation.Remove(key);}foreach(var key in revoked.Where(p=>p.Value<=now).Select(p=>p.Key).ToArray())revoked.Remove(key);} + private void Prune(){var now=clock.GetUtcNow();foreach(var receipt in navigationReceipts.Where(p=>p.Value.Expires<=now).Select(p=>p.Key).ToArray())navigationReceipts.Remove(receipt);foreach(var key in leases.Where(p=>now-p.Value.Updated>=TimeSpan.FromSeconds(45)||p.Value.GrantExpires<=now).Select(p=>p.Key).ToArray()){leases.Remove(key);navigation.Remove(key);}foreach(var key in revoked.Where(p=>p.Value<=now).Select(p=>p.Key).ToArray())revoked.Remove(key);} private readonly Dictionary<(int User,int Book,Guid Manuscript,Guid Session,long Revision),(int End,(int Start,int Chapter,int? Scene)[] Items)> mappings=[]; public void Map(int user,int book,Guid manuscript,Guid session,long revision,int end,(int Start,int Chapter,int? Scene)[] items){lock(gate){if(items.Length>8192)return;foreach(var key in mappings.Keys.Where(k=>k.User==user&&k.Session==session).ToArray())mappings.Remove(key);if(mappings.Count>=64)mappings.Remove(mappings.Keys.First());mappings[(user,book,manuscript,session,revision)]=(end,items);}} public (int Chapter,int? Scene)? Resolve(int user,NativePresence position,Guid session){lock(gate){if(position.WordSaved!=true||!position.CursorStart.HasValue||!mappings.TryGetValue((user,position.BookId,position.ManuscriptId,session,position.Revision),out var map)||position.CursorStart<0||position.CursorStart>=map.End)return null;var boundary=map.Items.LastOrDefault(i=>i.Start<=position.CursorStart);return boundary.Chapter>0?(boundary.Chapter,boundary.Scene):null;}} @@ -21,8 +22,8 @@ public sealed class NativePresenceStore(TimeProvider clock) leases[key]=new(user,grant,expires,instance,session,new NativePresence{ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;} } public NativeLease[] Read(int user,int book){lock(gate){Prune();return leases.Values.Where(p=>p.User==user&&(book==0||p.Position.BookId==book)).OrderByDescending(p=>p.Updated).ToArray();}} - public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start,bool requireSaved=false) - {lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||(requireSaved&&lease.Position.WordSaved!=true)||start<0||(navigation.TryGetValue(key,out var queued)&&queued.Kind!="navigate"))return false;navigation[key]=new(){Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}} + public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start,bool requireSaved=false,Guid? navigationId=null) + {lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||(requireSaved&&lease.Position.WordSaved!=true)||start<0||(navigation.TryGetValue(key,out var queued)&&queued.Kind!="navigate"))return false;var id=navigationId??Guid.NewGuid();if(id==Guid.Empty)return false;var receipt=(user,instance,session,id);if(navigationReceipts.TryGetValue(receipt,out var prior))return prior.Revision==revision&&prior.Start==start;if(navigationReceipts.Count>=8192)return false;navigationReceipts[receipt]=(clock.GetUtcNow().AddMinutes(15),revision,start);navigation[key]=new(){Id=id,Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}} public void RequestCancellation(int user,NativeLease selected){lock(gate){var key=(user,selected.Instance,selected.Session);if(leases.TryGetValue(key,out var current)&¤t.Grant==selected.Grant&¤t.Position.Revision==selected.Position.Revision)navigation[key]=new(){Kind="cancel",SessionId=selected.Session,Revision=selected.Position.Revision};}} public bool RequestCapture(int user,NativeLease selected,Guid request,int book=0,bool paragraphs=false,bool synchronise=false,long baseRevision=0,string baseHash="") {lock(gate){Prune();var key=(user,selected.Instance,selected.Session);if(!leases.TryGetValue(key,out var lease)||lease.Grant!=selected.Grant||lease.Position.Revision!=selected.Position.Revision||lease.Position.ManuscriptId!=selected.Position.ManuscriptId||(book>0&&lease.Position.BookId!=0&&lease.Position.BookId!=book)||!lease.Position.CanCapture||navigation.ContainsKey(key))return false;navigation[key]=new(){Id=request,BaseRevision=baseRevision,BaseSnapshotHash=baseHash,BookId=book,ParagraphTracking=paragraphs,Kind=synchronise?"paragraph-snapshot":"wizard-capture",SessionId=lease.Session,Revision=lease.Position.Revision};return true;}} diff --git a/PlotLine/wwwroot/js/native-companion-status.js b/PlotLine/wwwroot/js/native-companion-status.js index 3282eb08..cb4a0f5d 100644 --- a/PlotLine/wwwroot/js/native-companion-status.js +++ b/PlotLine/wwwroot/js/native-companion-status.js @@ -1,6 +1,6 @@ (() => { 'use strict';const root=document.querySelector('#native-companion-status');if(!root)return; - const text=root.querySelector('#native-companion-status-text');let pending=false,seen=false; + const text=root.querySelector('#native-companion-status-text');let pending=false,seen=false,refreshAgain=false,reconnectPending=false; const details=document.querySelector('#writing-connection-details'), documents=details?.querySelector('#writing-word-document'); root.addEventListener('click',()=>details?.showModal()); details?.querySelector('[data-close-word-details]')?.addEventListener('click',()=>details.close()); @@ -25,7 +25,7 @@ details.querySelector('[data-word-connection-diagnostics]').textContent=leases.length?'Current authenticated sessions: '+leases.length+'. Heartbeats expire after 45 seconds. Last checked '+new Date().toLocaleTimeString()+'. No manuscript text is transferred by these checks.':'No current Word session. Open Companion, check sign-in and book association, then reopen the manuscript.'; } function offline(message){root.dataset.nativeAuthority=root.dataset.officeConnected==='true'?'false':'true';root.dataset.connected='false';root.classList.remove('is-connected');root.classList.add('is-offline');text.textContent=message;root.title=message+' · saved PlotDirector information remains available.';} - async function update(reconnected=false){if(pending||document.hidden)return;pending=true;try{ + async function update(reconnected=false){reconnectPending ||= reconnected;if(document.hidden)return;if(pending){refreshAgain=true;return;}pending=true;const reconnect=reconnectPending;reconnectPending=false;try{ const response=await fetch('/native-companion/status',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error();const leases=(await response.json()).filter(l=>Date.parse(l.expires)>Date.now());const active=leases.filter(l=>l.active&&l.wordAvailable),words=leases.filter(l=>l.wordAvailable);const lease=active.length===1?active[0]:words.length===1?words[0]:words.length===0?leases[0]:null;if(words.length>1&&active.length!==1){seen=true;offline('Choose an active Word document');} if(lease){leases.connectionState="Connected";leases.known=true;seen=true;root.dataset.nativeAuthority='true';root.dataset.connectionState='Connected';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');text.textContent=lease.wordAvailable?'Word connected':'Companion connected';root.title=lease.wordAvailable?lease.documentTitle+' · verified document heartbeat · last update '+new Date(lease.updated).toLocaleTimeString():'Companion connected; open a linked manuscript in Word.';} else { @@ -33,8 +33,8 @@ const device=stateResponse.ok?await stateResponse.json():null;leases.connectionState=device?.state||"Disconnected";leases.known=!!device?.known; if(device?.known){seen=true;const label=device.state==='Connected'?'Companion connected · Word not connected':device.state;offline(label);root.dataset.connectionState=device.state;if(device.state==='Connected'){root.dataset.nativeAuthority='true';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');root.title='Approved Companion is connected. No live Word document is registered.';}} else if(seen)offline('Word disconnected or stale');else if(text.textContent==='Checking Word…')offline('Word disconnected'); - }leases.reconnected=reconnected;renderDetails(leases);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases})); - }catch{if(seen){offline('Companion status unavailable');}leases.reconnected=reconnected;renderDetails(leases);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[]}));}finally{pending=false;}} - void update();const timer=setInterval(()=>void update(),15000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer)); - if(window.signalR){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',()=>{clearTimeout(refresh);refresh=setTimeout(()=>void update(),250);});connection.onreconnected(()=>void update(true));void connection.start().then(()=>void update()).catch(()=>{});window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});} + }leases.reconnected=reconnect;root.nativePresence=leases;renderDetails(leases);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases})); + }catch{offline('Companion status unavailable');const unavailable=[];unavailable.connectionState='Disconnected';unavailable.reconnected=reconnect;root.nativePresence=unavailable;renderDetails(unavailable);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:unavailable}));}finally{pending=false;if(refreshAgain){refreshAgain=false;void update();}}} + let reconnectHub=()=>{};void update();const timer=setInterval(()=>{reconnectHub();void update();},15000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer)); + if(window.signalR){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',()=>{clearTimeout(refresh);refresh=setTimeout(()=>void update(),250);});connection.onreconnected(()=>void update(true));let starting=false;reconnectHub=()=>{if(starting||connection.state&&connection.state!=='Disconnected')return;starting=true;void connection.start().then(()=>void update(true)).catch(()=>{}).finally(()=>starting=false);};reconnectHub();window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});} })(); diff --git a/PlotLine/wwwroot/js/writing-context-components.js b/PlotLine/wwwroot/js/writing-context-components.js index 4c26a272..5fd32167 100644 --- a/PlotLine/wwwroot/js/writing-context-components.js +++ b/PlotLine/wwwroot/js/writing-context-components.js @@ -44,6 +44,6 @@ if(target.hasAttribute('data-context-refresh')){root.dispatchEvent(new CustomEvent('writing-view-before-refresh'));delete host.dataset.loaded;void load(host);} if(target.hasAttribute('data-context-explore')){host.dataset.exploring='true';explore(host,Number(target.dataset.contextExplore));} if(target.hasAttribute('data-context-center')){delete host.dataset.exploring;delete host.dataset.currentSignature;refresh(host);center(host);} - if(target.hasAttribute('data-context-go-scene')){delete host.dataset.exploring;delete host.dataset.currentSignature;const select=root.querySelector('[data-writing-context-scene-select]');if(select&&[...select.options].some(o=>o.value===target.dataset.contextGoScene)){select.value=target.dataset.contextGoScene;select.dispatchEvent(new Event('change'));}} + if(target.hasAttribute('data-context-go-scene')){delete host.dataset.exploring;delete host.dataset.currentSignature;const select=root.querySelector('[data-writing-context-scene-select]');if(select&&[...select.options].some(o=>o.value===target.dataset.contextGoScene)){select.value=target.dataset.contextGoScene;}} }); })(); diff --git a/PlotLine/wwwroot/js/writing-follow.js b/PlotLine/wwwroot/js/writing-follow.js index fd454fee..1353b678 100644 --- a/PlotLine/wwwroot/js/writing-follow.js +++ b/PlotLine/wwwroot/js/writing-follow.js @@ -196,16 +196,16 @@ }); }); - const navigate = async (id) => { + const navigate = async (id, userInitiated=false) => { const sceneId = parsePositiveInt(id); if (!sceneId) return; const manual=++manualGeneration;navigationRequest?.abort(); const fragment = contentHost?.querySelector(config.fragmentSelector); const position = { source: config.source, projectId: parsePositiveInt(fragment?.dataset.projectId || root.dataset.scopeProjectId), bookId: parsePositiveInt(fragment?.dataset.bookId || root.dataset.scopeBookId), sceneId }; - await loadPosition(position); - if (manual!==manualGeneration || currentSceneId !== sceneId || root.dataset.followMode === 'snapshot') return; + await loadPosition(position, true); + if (manual!==manualGeneration || currentSceneId !== sceneId || root.dataset.followMode === 'snapshot' || !userInitiated) return; const token = root.querySelector('[name=__RequestVerificationToken]')?.value; if (!token) return; - const body = new URLSearchParams({bookId: position.bookId, sceneId, __RequestVerificationToken: token}); + const body = new URLSearchParams({bookId: position.bookId, sceneId, navigationId:crypto.randomUUID(), __RequestVerificationToken: token}); if (selectedDocument) { const [instanceId, sessionId] = selectedDocument.split('/'); body.set('instanceId', instanceId); body.set('sessionId', sessionId); } const beforeNavigation=nativePositionKey; try { @@ -215,9 +215,10 @@ if (manual===manualGeneration&¤tSceneId === sceneId&&nativePositionKey===beforeNavigation) setStatus(result.message || 'Saved scene selected; Word navigation unavailable.'); } catch (error) { if (manual===manualGeneration&&error?.name!=='AbortError'&¤tSceneId === sceneId) setStatus('Saved scene selected. Word navigation is unavailable.'); } }; - contentHost?.querySelector(config.selectSelector)?.addEventListener('change', event => void navigate(event.target.value)); - contentHost?.querySelectorAll('[data-writing-scene-step]').forEach(button => button.addEventListener('click', () => void navigate(button.dataset.writingSceneStep))); + contentHost?.querySelector(config.selectSelector)?.addEventListener('change', event => void navigate(event.target.value,event.isTrusted)); + contentHost?.querySelectorAll('[data-writing-scene-step]').forEach(button => button.addEventListener('click', event => void navigate(button.dataset.writingSceneStep,event.isTrusted))); + root.navigateExplicitScene=navigate; contentHost?.querySelector("[data-writing-intent-chapter-select]")?.addEventListener("change", (event) => { const chapterId = parsePositiveInt(event.target.value); if (!chapterId) { @@ -246,7 +247,7 @@ return true; }; - const loadPosition = async (position) => { + const loadPosition = async (position, userInitiated=false) => { const hasScene = Number.isInteger(position?.sceneId) && position.sceneId > 0; const hasChapter = Number.isInteger(position?.chapterId) && position.chapterId > 0; if (!position || !inScope(position) || (!hasScene && (!config.allowChapterOnly || !hasChapter))) { @@ -294,7 +295,7 @@ // Only the expected server-rendered fragment may enter this workspace. Never embed a shell/login/Timeline page. const fragment = fragmentFromHtml(html, config.fragmentSelector); const tab = activeTab(), scroll = {x: window.scrollX, y: window.scrollY}; - const focused=document.hasFocus()&&contentHost.contains(document.activeElement)?document.activeElement:null; + const focused=userInitiated&&document.hasFocus()&&contentHost.contains(document.activeElement)?document.activeElement:null; const focusedTab=focused?.dataset[config.tabDataKey],focusedSelect=focused?.matches(config.selectSelector); saveView(); for(const panel of contentHost.querySelectorAll('[data-writing-stable-panel]')) { @@ -344,9 +345,9 @@ const chosen = selectedDocument ? available.filter(l => l.instanceId + '/' + l.sessionId === selectedDocument) : active.length === 1 ? active : available; const lease = chosen.length === 1 ? chosen[0] : null; if (!lease) { nativeWasConnected = false; nativePositionKey = ''; setStatus(available.length > 1 && !selectedDocument ? 'Choose a Word document using the connection indicator' : selectedDocument ? 'Selected Word document is disconnected · saved scene remains available' : leases.some(l=>l.wordAvailable) ? 'Saved scene · no live Word position for this book' : 'Word disconnected · saved scene remains available'); return; } - const key = [lease.instanceId, lease.sessionId, lease.chapterId, lease.sceneId].join(':'); - if ((!lease.sceneId && !(config.allowChapterOnly && lease.chapterId)) || lease.wordSaved === false) { nativeWasConnected = true; nativePositionKey = key; setStatus('No trustworthy current Word scene · saved scene remains available'); return; } - if (!nativeWasConnected || key !== nativePositionKey) { + const key = [lease.instanceId, lease.sessionId, lease.chapterId, lease.sceneId, lease.wordSaved].join(':'); + if ((!lease.sceneId && !(config.allowChapterOnly && lease.chapterId)) || lease.wordSaved === false) { nativeWasConnected = true; nativePositionKey = key; setStatus(lease.positionMessage?lease.positionMessage+' · saved scene remains available':lease.wordSaved===false?'Save Word, then synchronise to refresh its scene mapping · saved scene remains available':'Word scene mapping is unavailable · synchronise from Word; saved scene remains available'); return; } + if (!nativeWasConnected || key !== nativePositionKey || (!pendingRequest && Number(lease.sceneId)!==currentSceneId)) { nativeWasConnected = true; nativePositionKey = key; void loadPosition({source:'WordCompanion',projectId:scopedProjectId || parsePositiveInt(currentFragment?.dataset.projectId),bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:lease.sceneId?Number(lease.sceneId):null}); setStatus('Following Word'); @@ -361,6 +362,7 @@ if (root.dataset.followMode === "snapshot") { wireFragment(); setStatus("Saved PlotDirector snapshot — manual selection"); return { loadPosition, activateTab }; } document.addEventListener(window.PlotDirectorStoryPosition?.eventName || "plotdirector:story-position-changed", (event) => { + if(selectedDocument||nativeLeases.some(l=>l.wordAvailable&&Date.parse(l.expires)>Date.now()&&(!scopedBookId||Number(l.bookId)===scopedBookId)))return; void loadPosition(event.detail); }); @@ -415,8 +417,10 @@ ); } + root.addEventListener('click',event=>{const button=event.target.closest('[data-context-go-scene]');if(button&&event.isTrusted)void root.navigateExplicitScene?.(button.dataset.contextGoScene,true);}); wireFragment(); restoreView(); + const observed=document.querySelector('#native-companion-status')?.nativePresence;if(observed)followNative(observed); return { loadPosition, activateTab }; };