From 81833c6b0d778c15399872bf70336076f7d9627f Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Tue, 3 Nov 2026 22:12:36 +0000 Subject: [PATCH] Recover Writer connections and isolate writing window identities --- Docs/Sprints/2026-11-03-phase2.md | 60 +++++ PlotLine.Tests/Browser/package-lock.json | 208 ++++++++++++++++++ PlotLine.Tests/Browser/package.json | 4 +- PlotLine.Tests/Browser/writer-workspace.cjs | 95 ++++++++ PlotLine.Tests/ToolbarBrowserHost.cs | 87 +++++++- .../wwwroot/js/writing-workspace-launcher.js | 34 ++- PlotLine/wwwroot/js/writing-workspace.js | 43 +++- 7 files changed, 514 insertions(+), 17 deletions(-) create mode 100644 Docs/Sprints/2026-11-03-phase2.md create mode 100644 PlotLine.Tests/Browser/writer-workspace.cjs diff --git a/Docs/Sprints/2026-11-03-phase2.md b/Docs/Sprints/2026-11-03-phase2.md new file mode 100644 index 00000000..cf1b532c --- /dev/null +++ b/Docs/Sprints/2026-11-03-phase2.md @@ -0,0 +1,60 @@ +# Phase 2 improvement programme — 3 November 2026 + +## Baseline + +- Repository: /srv/repos/PlotDirector. +- Starting branch: codex/overnight-improvements-20261103. +- Starting commit: 06f2bf78219e6fd01ec6098019af4e24630ef6ee; worktree clean. +- Isolated branch: codex/phase2-development-20261103. +- Development service active; deployed DLL matches archived 1930007 release with SHA-256 5a86109eb96338fc3ec77f416410e1efe33600d4a22cf761a10b30dd513f8689. +- Reviewed Phase 1 report and build/browser/deployment guides. Prior improvements are the baseline. Phase 2 explicitly supersedes the Locations segmented-button presentation. +- No authenticated live browser session established. Real Razor fixtures and production scripts will be identified as fixture verification. + +## Durable queue + +1. CURRENT: verify Writer connection-recovery repair and repeated full-layout navigation; inspect chapter-goal unsaved navigation. +2. Verify Writer commands and repeated entry/exit, legitimate unsaved-change guards and cancelled/saved/discarded navigation. +3. Repair Writer spacing after functional repair or explicit deferral. +4. Build rendered page inventory covering all requested areas/modes/themes; capture and inspect screenshots; repair evidenced shared spacing defects. +5. Distinguish Maps/Floor Plans navigation icons. +6. Replace Locations segments with conventional icon/label ribbon commands and depressed active styling. +7. Add established right-edge drag handles and verify both drag modes/accessibility. +8. Build persistent project-entity/file/format inventory against actual schema and backup/restore implementations. +9. Repair backup/restore omissions safely; verify synthetic isolated database round trips, references, assets, transactions and available historical fixtures. +10. Inventory every import/export workflow and its intended fidelity; verify applicable synthetic round trips, compatibility and errors. +11. Final serial build/harness, focused integration/browser/visual checks; safe Development deployment and handover. + +## Execution record + +- Baseline established. Next: add Writer real-Razor fixture and reproduce symptoms with production shell scripts; no cosmetic Writer changes yet. + +## Coverage and evidence + +Coverage inventories will record tested pages, entities and formats explicitly. Representative cases will not be labelled exhaustive. + +## Deployment + +Phase 2 not deployed. Production excluded. No database state changes performed. + +### Writer investigation checkpoint + +- Added a full-layout Writer fixture, including the real Razor layout, shell, help drawer, production scripts and real SignalR SDK. The fixture now hosts the production WordCompanionFollowHub and its production in-memory Word/Writer presence services; no database connection or app workers are used. +- Basic section selection remained responsive in browser/PWA with both the original compact fixture and full layout. No invisible blocking overlay or immediate generic shell mutation loop was reproduced in these cases. The reported whole-page lock still needs live acceptance evidence; do not claim that exact symptom independently reproduced. +- Confirmed failure reproduced: fail only the first real SignalR negotiation with HTTP 503, restore the endpoint, then click Start/Reapply. Before repair, no second negotiation occurs because connectionPromise permanently retains the initial rejection. Initial registration also silently leaves status placeholders Checking. +- Applied local repair: clear failed/terminal connection promises so user commands can reconnect; re-register the launcher when retrying Start; report initial registration failure; accurately handle blocked popup/focus results and release command disabled states in finally blocks. +- Initial real-Hub recovery regression passed in browser/PWA. Expanded tests now cover actual Context/Intent Razor windows, terminal reconnect, popup denial feedback and repeated Writer→Locations→Writer navigation. Expanding the fixture surfaced and corrected test-only endpoint ambiguity; production routing was untouched. +- Added exact-version SignalR 8.0.7 browser-test dependency to match the production SDK, avoiding a temporary-file test dependency. +- Current build/test evidence: baseline and intermediate solution builds passed with zero warnings/errors; expanded Writer test verification is ongoing. No Phase 2 code committed or deployed yet. + +### Writer recovery and presence repair — verified + +Confirmed and repaired two independent defects using the full Razor layout, real SignalR 8.0.7 SDK, production Hub and production in-memory presence services: + +1. Initial negotiation failure permanently cached a rejected promise; later commands never retried. Terminal disconnects also retained a disconnected connection. Failed/closed connections now release the cached promise and Start re-registers the launcher before reapplying the workspace. Unavailable presence is labelled explicitly instead of remaining Checking. +2. Browser-created pop-ups cloned the launcher's sessionStorage ID. The failing test observed one unique ID across Launcher/Context/Intent instead of three, and the windows overwrote one another's role/focus presence. IDs now belong to the named window (with opener-clone detection), remain stable across reloads, and remain stable within a document if storage is unavailable. + +Also corrected false success feedback when a popup is blocked and protected role-command disabled states with finally/error handling. A valid server-side focus request still succeeds when an existing role window is available. + +Verification: solution build passed (0 warnings/errors); full executable harness passed (405 checks); full-layout Writer browser/PWA regression passed. It exercises one failed real negotiation followed by recovery, terminal stop/reconnect, actual Context and Intent Razor windows, three distinct IDs, reload stability, focus reuse, popup denial feedback, three leave/return cycles per mode, project Focus submission, Writing Plans/Schedule Setup/Schedule Preview real controller/view routes, and unsupported display-detection fallback. No whole-page blocking overlay was observed in these fixtures. Live authenticated PWA acceptance remains unperformed. + +Next functional item: chapter-goal editing has no beforeunload/navigation guard. Probe confirmed that leaving Writer is not intercepted after typing. Browser back-cache may retain the draft temporarily; it is not a save or a reliable protection against closing/reloading the page. Add save/discard/cancel protection using the established application dialog and explicit save acknowledgement before visual work. diff --git a/PlotLine.Tests/Browser/package-lock.json b/PlotLine.Tests/Browser/package-lock.json index 2734819f..1f8cce03 100644 --- a/PlotLine.Tests/Browser/package-lock.json +++ b/PlotLine.Tests/Browser/package-lock.json @@ -5,6 +5,7 @@ "packages": { "": { "devDependencies": { + "@microsoft/signalr": "8.0.7", "chart.js": "4.4.9", "playwright": "1.58.2", "sharp": "^0.35.5" @@ -603,6 +604,33 @@ "dev": true, "license": "MIT" }, + "node_modules/@microsoft/signalr": { + "version": "8.0.7", + "resolved": "https://registry.npmjs.org/@microsoft/signalr/-/signalr-8.0.7.tgz", + "integrity": "sha512-PHcdMv8v5hJlBkRHAuKG5trGViQEkPYee36LnJQx4xHOQ5LL4X0nEWIxOp5cCtZ7tu+30quz5V3k0b1YNuc6lw==", + "dev": true, + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "eventsource": "^2.0.2", + "fetch-cookie": "^2.0.3", + "node-fetch": "^2.6.7", + "ws": "^7.4.5" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dev": true, + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, "node_modules/chart.js": { "version": "4.4.9", "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.4.9.tgz", @@ -626,6 +654,37 @@ "node": ">=8" } }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/eventsource": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz", + "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fetch-cookie": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/fetch-cookie/-/fetch-cookie-2.2.0.tgz", + "integrity": "sha512-h9AgfjURuCgA2+2ISl8GbavpUdR+WGAM2McW/ovn4tVccegp8ZqCKWSBR8uRdM8dDNlx5WdKRWxBYUwteLDCNQ==", + "dev": true, + "license": "Unlicense", + "dependencies": { + "set-cookie-parser": "^2.4.8", + "tough-cookie": "^4.0.0" + } + }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", @@ -641,6 +700,27 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, "node_modules/playwright": { "version": "1.58.2", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", @@ -673,6 +753,43 @@ "node": ">=18" } }, + "node_modules/psl": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz", + "integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "funding": { + "url": "https://github.com/sponsors/lupomontero" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "dev": true, + "license": "MIT" + }, "node_modules/semver": { "version": "7.8.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", @@ -686,6 +803,13 @@ "node": ">=10" } }, + "node_modules/set-cookie-parser": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.3.tgz", + "integrity": "sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==", + "dev": true, + "license": "MIT" + }, "node_modules/sharp": { "version": "0.35.5", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", @@ -736,6 +860,29 @@ } } }, + "node_modules/tough-cookie": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", + "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.2.0", + "url-parse": "^1.5.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "dev": true, + "license": "MIT" + }, "node_modules/tslib": { "version": "2.9.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", @@ -743,6 +890,67 @@ "dev": true, "license": "0BSD", "optional": true + }, + "node_modules/universalify": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", + "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/url-parse": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/ws": { + "version": "7.5.13", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", + "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } } } } diff --git a/PlotLine.Tests/Browser/package.json b/PlotLine.Tests/Browser/package.json index aa507ad0..0351029f 100644 --- a/PlotLine.Tests/Browser/package.json +++ b/PlotLine.Tests/Browser/package.json @@ -20,9 +20,11 @@ "test:relationships-ribbon": "node relationships-ribbon.cjs", "test:relationship-focus": "node relationship-focus-stability.cjs", "test:maps": "node maps-engine.cjs && node maps-workspace.cjs", - "test:maps-story": "node maps-story-engine.cjs && node maps-story.cjs" + "test:maps-story": "node maps-story-engine.cjs && node maps-story.cjs", + "test:writer": "node writer-workspace.cjs" }, "devDependencies": { + "@microsoft/signalr": "8.0.7", "chart.js": "4.4.9", "playwright": "1.58.2", "sharp": "^0.35.5" diff --git a/PlotLine.Tests/Browser/writer-workspace.cjs b/PlotLine.Tests/Browser/writer-workspace.cjs new file mode 100644 index 00000000..62280a50 --- /dev/null +++ b/PlotLine.Tests/Browser/writer-workspace.cjs @@ -0,0 +1,95 @@ +const { chromium } = require('playwright'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const base = 'http://127.0.0.1:5238'; +(async () => { + const browser = await chromium.launch(); + try { + for (const pwa of [false,true]) { + const context = await browser.newContext({viewport:{width:1600,height:1000}}); + if (pwa) await context.addInitScript(() => Object.defineProperty(navigator,'standalone',{value:true})); + const page = await context.newPage(); + const errors=[];page.on('pageerror',error=>errors.push(error.message)); context.on('page',popup=>popup.on('pageerror',error=>errors.push(error.message))); + // Use the real SDK, production Hub/presence services, full Razor layout and scripts. + // Only the first network negotiation is failed; subsequent traffic reaches the loopback Hub. + await context.route('**/signalr.min.js',route=>route.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8') + ` +;window.__writerConnections=[];const originalHubBuild=signalR.HubConnectionBuilder.prototype.build;signalR.HubConnectionBuilder.prototype.build=function(){const connection=originalHubBuild.call(this);window.__writerConnections.push(connection);return connection;};`})); + let negotiations=0; + await page.route('**/hubs/word-companion-follow/negotiate?*',route=>++negotiations===1?route.fulfill({status:503,body:'Transient fixture outage'}):route.continue()); + await page.goto(base+'/fixture?page=writer&layout=full'); + await page.waitForFunction(()=>!!window.PlotDirectorWritingWorkspace); + await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-word]').textContent==='Unavailable'); + assert.equal(negotiations,1,'Initial failed connection is not retried in a tight loop'); + const start=page.getByRole('button',{name:'Start / Reapply Workspace',exact:true}); + await page.evaluate(()=>{window.__originalWindowOpen=window.open;window.open=()=>null;}); + await start.click(); + await page.waitForFunction(()=>!document.querySelector('[data-start-writing-workspace]').disabled); + assert.ok(negotiations>=2,'A user command must retry after the initial connection failure'); + assert.equal(await page.locator('[data-writing-workspace-word]').textContent(),'Not connected'); + await page.evaluate(()=>window.open=window.__originalWindowOpen); + const windows=[]; + for(const role of ['context','intent']){ + const opened=context.waitForEvent('page'); + await page.locator(`[data-open-writing-${role}]`).click(); + const popup=await opened;await popup.waitForLoadState(); + assert.equal(await popup.locator('[data-writing-mode]').count(),1,'Production writing-window view renders successfully'); + windows.push(popup); + } + const identities=await Promise.all(context.pages().map(tab=>tab.evaluate(()=>window.PlotDirectorWritingWorkspace.getBrowserWindowId()))); + assert.equal(new Set(identities).size,3,'Launcher, Context and Intent must have distinct presence identities even when sessionStorage is cloned from an opener'); + await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-context]').textContent==='Open' && document.querySelector('[data-writing-workspace-intent]').textContent==='Open'); + for(const popup of windows){ + const before=await popup.evaluate(()=>window.PlotDirectorWritingWorkspace.getBrowserWindowId()); + await popup.reload();await popup.waitForFunction(()=>!!window.PlotDirectorWritingWorkspace); + assert.equal(await popup.evaluate(()=>window.PlotDirectorWritingWorkspace.getBrowserWindowId()),before,'Reload preserves the identity owned by this window'); + } + await page.locator('[data-focus-writing-context]').click(); + await page.locator('[data-focus-writing-intent]').click(); + assert.equal(context.pages().length,3,'Focus commands reuse the existing writing windows'); + const beforeRestart=negotiations; + await page.evaluate(()=>window.__writerConnections.at(-1).stop()); + await start.click(); + await page.waitForFunction(()=>!document.querySelector('[data-start-writing-workspace]').disabled); + assert.ok(negotiations>beforeRestart,'A terminal disconnect permits a fresh connection'); + assert.equal(context.pages().length,3,'Reapply reuses existing Context/Intent windows'); + for(const popup of windows)await popup.close(); + await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-context]').textContent==='Not open'); + await page.evaluate(()=>{window.__originalWindowOpen=window.open;window.open=()=>null;}); + await page.getByRole('button',{name:'Open Context',exact:true}).click(); + await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-message]').textContent.includes('blocked')); + assert.equal(await page.getByRole('button',{name:'Open Context',exact:true}).isEnabled(),true); + await page.evaluate(()=>window.open=window.__originalWindowOpen); + await page.route('**/Locations?*',async route=>route.fulfill({response:await page.request.get(base+'/fixture?desktop=Locations')})); + for(let pass=0;pass<3;pass++){ + await page.getByRole('tab',{name:'World',exact:true}).click(); + await page.getByRole('link',{name:'Locations',exact:true}).first().click(); + await page.waitForURL('**/Locations?*'); + assert(await page.locator('.location-page').isVisible()); + await page.getByRole('tab',{name:'Project',exact:true}).click(); + await page.getByRole('link',{name:'Writer',exact:true}).first().click(); + await page.waitForURL(url=>url.pathname==='/Writer'); + await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-word]').textContent!=='Checking...'); + assert(await page.getByRole('button',{name:'Start / Reapply Workspace',exact:true}).isEnabled()); + } + await page.evaluate(()=>{window.__screenDetails=window.getScreenDetails;Object.defineProperty(window,'getScreenDetails',{value:undefined,configurable:true});}); + await page.getByRole('button',{name:'Detect displays',exact:true}).click(); + await page.waitForFunction(()=>!document.querySelector('[data-detect-writing-displays]').disabled); + assert.match(await page.locator('[data-writing-workspace-message]').textContent(),/unavailable/); + const focus= pwa ? page.locator('[data-pwa-context-controls]').getByRole('button',{name:'Focus',exact:true}) : page.locator('.writer-dashboard-heading').getByRole('button',{name:'Focus',exact:true}); + await focus.click(); + await page.waitForURL(url=>url.pathname==='/Writer'&&url.searchParams.get('projectId')==='7'); + for(const [name,route] of [['Writing Plans','WritingPlans'],['Schedule Setup','ScheduleSetup'],['Schedule Preview','SchedulePreview']]){ + const host=pwa?page.locator('[data-pwa-context-controls]'):page.locator('.writer-dashboard-heading'); + const link=host.getByRole('link',{name,exact:true,includeHidden:true}); + const menu=link.locator('xpath=ancestor::details[@data-compact="true"]').last(); + if(await menu.count()&&!(await menu.evaluate(node=>node.open)))await menu.locator(':scope > summary').click(); + const response=page.waitForResponse(response=>response.request().isNavigationRequest()&&new URL(response.url()).pathname==='/Writer/'+route); + await link.click();assert.equal((await response).status(),200,name+' real controller/view route'); + await page.goto(base+'/Writer'); + } + assert.deepEqual(errors,[]); + await context.close(); + } + console.log('PASS full-layout Writer browser/PWA negotiation recovery, terminal reconnect, actual Context/Intent windows, blocked pop-ups and repeated section navigation'); + } finally {await browser.close();} +})().catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index d5a02952..d6390a9f 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -66,14 +66,75 @@ internal static class ToolbarBrowserHost }}; } + private static T FixtureProxy(Func handler) where T : class + { + var proxy = System.Reflection.DispatchProxy.Create(); + ((StoryPointProxy)(object)proxy).Handler = handler; + return proxy; + } + + private static WriterDashboardViewModel WriterFixture() => new() { + ProjectID = 7, ProjectOptions = [new SelectListItem("The Glass Harbour", "7", true)], + WriteNext = [new() { ProjectID = 7, BookID = 12, BookTitle = "A Distant Shore", ChapterID = 21, ChapterNumber = 1, SceneID = 101, SceneNumber = 1, SceneTitle = "The crossing", RevisionStatusName = "Outlined", Summary = "A synthetic writing task." }] + }; + + private static async Task RenderFullAsync(HttpContext context, string controller, string actionName, object model) + { + context.Request.RouteValues["controller"] = controller; + context.Request.RouteValues["action"] = actionName; + var action = new ActionContext(context, new RouteData(context.Request.RouteValues), new ActionDescriptor()); + var view = context.RequestServices.GetRequiredService().GetView(null, $"/Views/{controller}/{actionName}.cshtml", true); + if (!view.Success) throw new Exception(string.Join(",", view.SearchedLocations)); + using var writer = new StringWriter(); + await view.View.RenderAsync(new ViewContext(action, view.View, + new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }, + new TempDataDictionary(context, context.RequestServices.GetRequiredService()), writer, new HtmlHelperOptions())); + context.Response.ContentType = "text/html; charset=utf-8"; + await context.Response.WriteAsync(writer.ToString()); + } + public static async Task RunAsync() { var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(ToolbarController).Assembly.FullName, ContentRootPath = Path.GetFullPath("PlotLine") }); builder.Services.AddControllersWithViews().AddApplicationPart(typeof(ToolbarController).Assembly); + builder.Services.AddSignalR(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); + builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); + builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); + builder.Services.AddSingleton(); builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton(); - builder.Services.AddScoped(_ => new ApplicationNavigation(null!, null!, null!)); + builder.Services.AddScoped(services => new ApplicationNavigation( + FixtureProxy((name, args) => name == "GetForUserAsync" + ? Task.FromResult(new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = "Owner" }) : throw new NotSupportedException(name)), + FixtureProxy((name, args) => name == "ListByProjectAsync" + ? Task.FromResult>([new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }]) : throw new NotSupportedException(name)), + services.GetRequiredService())); + builder.Services.AddSingleton(FixtureProxy((name, args) => name switch { + "GetDashboardAsync" => Task.FromResult(WriterFixture()), + "GetChapterWorkflowAsync" => Task.FromResult(new() { + Project = new() { ProjectID = 7, ProjectName = "The Glass Harbour" }, + Book = new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }, + Chapter = new() { ChapterID = 21, BookID = 12, ChapterNumber = 1, ChapterTitle = "The crossing" }, + Goal = new() { ChapterID = 21, GoalSummary = "Reveal the consequence" } + }), + "SaveChapterGoalAsync" => Task.CompletedTask, + _ => throw new NotSupportedException(name) + })); + builder.Services.AddSingleton(FixtureProxy((name, args) => name switch { + "GetTodayDashboardAsync" => Task.FromResult(new WritingScheduleDashboardViewModel()), + "GetWritingPlansForManagementAsync" => Task.FromResult(new WritingPlansManagementViewModel()), + "GetSchedulePreviewAsync" => Task.FromResult(new WritingSchedulePreviewViewModel()), + "GetScheduleSetupAsync" => Task.FromResult(new WritingScheduleSetupViewModel()), + _ => throw new NotSupportedException(name) + })); + builder.Services.AddSingleton(FixtureProxy((name, args) => name == "GetEffectiveEntitlementAsync" ? Task.FromResult(new EffectiveEntitlement { UserID = 4, State = EntitlementState.ActivePaid }) : throw new NotSupportedException(name))); + builder.Services.AddSingleton(FixtureProxy((name, args) => name == "CountAttentionForUserAsync" ? Task.FromResult(0) : throw new NotSupportedException(name))); + builder.Services.AddSingleton(FixtureProxy((name, args) => name == "ShouldShowWordCompanionHeaderAsync" ? Task.FromResult(false) : throw new NotSupportedException(name))); + builder.Services.AddSingleton(FixtureProxy((name, args) => name == "GetForCurrentUserAsync" ? Task.FromResult(new StoryIntelligenceGlobalProgressViewModel()) : throw new NotSupportedException(name))); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -165,8 +226,15 @@ internal static class ToolbarBrowserHost context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync(writer.ToString()); }); + app.MapGet("/Writing/Context", context => RenderFullAsync(context, "Writing", "Context", new WritingContextPageViewModel { ProjectID = 7, BookID = 12 })).WithOrder(-1); + app.MapGet("/Writing/Intent", context => RenderFullAsync(context, "Writing", "Intent", new WritingIntentPageViewModel { ProjectID = 7, BookID = 12 })).WithOrder(-1); app.MapGet("/fixture", async context => { + if (context.Request.Query["page"] == "writer" && context.Request.Query["layout"] == "full") + { + await RenderFullAsync(context, "Writer", "Index", WriterFixture()); + return; + } var model = new ApplicationNavigationViewModel { ActiveSection = "Calendar", ShowCompanionPresence = true }; if (context.Request.Query["project"] != "none") { @@ -175,6 +243,7 @@ internal static class ToolbarBrowserHost model.Books = [model.Book, new Book { BookID = 13, ProjectID = 7, BookTitle = "The Return", BookNumber = 2 }]; } string? recordLayout = null; + var writerScripts = ""; var dashboardPage = context.Request.Query["page"] == "dashboard"; var timelinePage = context.Request.Query["page"] == "timeline"; if (dashboardPage) model.ActiveSection = "Overview"; @@ -199,6 +268,14 @@ internal static class ToolbarBrowserHost await scripts(); } + if (name == "Writer/Index" && view.View is Microsoft.AspNetCore.Mvc.Razor.RazorView writerView + && writerView.RazorPage.SectionWriters.TryGetValue("Scripts", out var writerSection)) + { + using var scriptWriter = new StringWriter(); + writerView.RazorPage.ViewContext.Writer = scriptWriter; + await writerSection(); + writerScripts = scriptWriter.ToString(); + } return writer.ToString(); } if (context.Request.Query["page"] == "scene-edit" && context.Request.Query.TryGetValue("editor", out var requestedEditor)) @@ -217,6 +294,7 @@ internal static class ToolbarBrowserHost model.Books = scene.Book is null ? [] : [scene.Book]; } if (context.Request.Query["page"] == "maps") { model.ActiveSection = "Maps"; route.Values["controller"] = "Maps"; } + if (context.Request.Query["page"] == "writer") { model.ActiveSection = "Writer"; route.Values["controller"] = "Writer"; } var menu = await Render("Shared/_ApplicationShell"); var toolbar = ""; var calendar = new StoryCalendarViewModel { Project = model.Project ?? new(), SelectedBookID = model.Book?.BookID, @@ -238,7 +316,7 @@ internal static class ToolbarBrowserHost calendar.EarliestStoryDate = new DateOnly(2026, 10, 3); calendar.LatestStoryDate = new DateOnly(2026, 10, 24); } - var surface = dashboardPage || context.Request.Query["page"] == "relationships" || context.Request.Query["page"] == "maps" ? "" : await Render("StoryCalendar/_StoryCalendarSurface", calendar); + var surface = dashboardPage || context.Request.Query["page"] == "writer" || context.Request.Query["page"] == "relationships" || context.Request.Query["page"] == "maps" ? "" : await Render("StoryCalendar/_StoryCalendarSurface", calendar); if (context.Request.Query["page"] == "calendar-test") surface = "
" + surface + "
"; if (timelinePage) @@ -386,6 +464,8 @@ internal static class ToolbarBrowserHost Blocks = [new() { FloorPlanBlockID = 51, FloorPlanFloorID = 41, LocationName = "Study", X = 2, Y = 2, WidthCells = 3, HeightCells = 2 }] }); } + if (context.Request.Query["page"] == "writer") + surface = await Render("Writer/Index", WriterFixture()); surface += await Render("Shared/_ConfirmationDialog"); var initialTheme = appearance.ThemeKey ?? "warm-light"; var appearanceScript = ""; @@ -393,8 +473,9 @@ internal static class ToolbarBrowserHost PlotLine.TagHelpers.RibbonContributionTagHelper.Snapshot(context).WriteTo(contributionWriter, System.Text.Encodings.Web.HtmlEncoder.Default); var contributions = contributionWriter.ToString(); context.Response.ContentType = "text/html; charset=utf-8"; - await context.Response.WriteAsync("
" + menu + toolbar + "
" + surface + "
" + appearanceScript + ""); + await context.Response.WriteAsync("
" + menu + toolbar + "
" + surface + "
" + appearanceScript + "" + writerScripts + ""); }); + app.MapHub("/hubs/word-companion-follow"); await app.RunAsync(); } } diff --git a/PlotLine/wwwroot/js/writing-workspace-launcher.js b/PlotLine/wwwroot/js/writing-workspace-launcher.js index 86257ec2..26fe0303 100644 --- a/PlotLine/wwwroot/js/writing-workspace-launcher.js +++ b/PlotLine/wwwroot/js/writing-workspace-launcher.js @@ -130,7 +130,11 @@ const targetDisplay = role === workspace.roles.context ? screenInfo.layout?.contextDisplay : screenInfo.layout?.intentDisplay; - await workspace.focusRole(role, scope, targetDisplay); + const opened = await workspace.focusRole(role, scope, targetDisplay); + if (!opened) { + setMessage(`Your browser blocked the ${role} window. Allow pop-ups for PlotDirector, then try Open ${role} again.`); + return; + } setMessage(`${role} requested on ${displayLabel(targetDisplay, "the selected display")}. If it is behind Word, use the taskbar once; future clicks should reuse it.`); await refresh(); }; @@ -162,6 +166,7 @@ startButton.disabled = true; setMessage("Starting writing workspace..."); try { + await workspace.registerWindow({ ...activeScope, writingRole: workspace.roles.launcher, displayLabel: "Writing Workspace" }); const result = await workspace.startWorkspace(activeScope, { requestScreens: true, displayPreferences: selectedDisplayPreferences() @@ -184,10 +189,21 @@ } }); - contextButton?.addEventListener("click", () => openOrFocus(workspace.roles.context)); - intentButton?.addEventListener("click", () => openOrFocus(workspace.roles.intent)); - focusContextButton?.addEventListener("click", () => openOrFocus(workspace.roles.context)); - focusIntentButton?.addEventListener("click", () => openOrFocus(workspace.roles.intent)); + const bindRoleCommand = (button, role) => button?.addEventListener("click", async () => { + button.disabled = true; + try { + await openOrFocus(role); + } catch (error) { + console.debug("Writing window could not be opened.", error); + setMessage(`${role} could not be opened. Check your connection and try again; you can still use the other PlotDirector sections.`); + } finally { + button.disabled = false; + } + }); + bindRoleCommand(contextButton, workspace.roles.context); + bindRoleCommand(intentButton, workspace.roles.intent); + bindRoleCommand(focusContextButton, workspace.roles.context); + bindRoleCommand(focusIntentButton, workspace.roles.intent); contextDisplaySelect?.addEventListener("change", () => { setMessage("Context display preference updated. Click Start / Reapply Workspace to use it."); }); @@ -217,5 +233,11 @@ const screenInfo = await workspace.getScreenLayout(false, selectedDisplayPreferences()); updateDisplayOptions(screenInfo); text(statusNodes.layout, screenInfo.layout?.mode || "adaptive"); - }).catch(() => null); + }).catch(error => { + text(statusNodes.word, "Unavailable"); + text(statusNodes.context, "Unavailable"); + text(statusNodes.intent, "Unavailable"); + setMessage("Writing workspace presence is unavailable. Check your connection and retry Start / Reapply Workspace; other PlotDirector sections remain available."); + console.debug("Writing workspace registration unavailable.", error); + }); })(); diff --git a/PlotLine/wwwroot/js/writing-workspace.js b/PlotLine/wwwroot/js/writing-workspace.js index 39088fdc..5ed8a3a1 100644 --- a/PlotLine/wwwroot/js/writing-workspace.js +++ b/PlotLine/wwwroot/js/writing-workspace.js @@ -16,23 +16,37 @@ let registration = null; let latestStatus = null; let latestPosition = null; + let browserWindowId = null; const parsePositiveInt = (value) => { const parsed = Number.parseInt(value || "", 10); return Number.isInteger(parsed) && parsed > 0 ? parsed : null; }; + const newWindowId = () => window.crypto?.randomUUID?.() || `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; const getBrowserWindowId = () => { + if (browserWindowId) return browserWindowId; try { let value = sessionStorage.getItem(storageKeys.windowId); - if (!value) { - value = window.crypto?.randomUUID?.() || `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; + const ownerKey = `${storageKeys.windowId}.owner`; + const owner = window.name || "main"; + let inherited = false; + try { + inherited = !!window.opener && value === window.opener.PlotDirectorWritingWorkspace?.getBrowserWindowId(); + } catch { /* An unrelated cross-origin opener cannot share workspace identity. */ } + // window.open clones the opener's sessionStorage. A named writing window + // must own its identity instead of overwriting the launcher's presence. + if (!value || sessionStorage.getItem(ownerKey) !== owner || inherited) { + value = newWindowId(); sessionStorage.setItem(storageKeys.windowId, value); } - return value; + sessionStorage.setItem(ownerKey, owner); + browserWindowId = value; } catch { - return window.crypto?.randomUUID?.() || `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; + // Keep one identity for this document even when storage is unavailable. + browserWindowId = newWindowId(); } + return browserWindowId; }; const cleanRole = (role) => { @@ -237,7 +251,22 @@ } }); - connectionPromise = connection.start().then(() => connection); + const startingConnection = connection; + connection.onclose(() => { + if (connection === startingConnection) { + connection = null; + connectionPromise = null; + } + }); + connectionPromise = startingConnection.start().then(() => startingConnection).catch(error => { + // A failed initial negotiation is not covered by SignalR automatic reconnect. + // Let a later user command retry instead of retaining a rejected promise. + if (connection === startingConnection) { + connection = null; + connectionPromise = null; + } + throw error; + }); return connectionPromise; }; @@ -302,8 +331,8 @@ return true; } - await invoke("RequestWritingWindowFocus", scopeFrom(scope), role).catch(() => null); - return false; + const status = await invoke("RequestWritingWindowFocus", scopeFrom(scope), role).catch(() => null); + return !!roleWindow(status, role, scope); }; const startWorkspace = async (scope, options = {}) => {