From 218e2bd1d526edca4d91066a166613e8a2e5b6f4 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sat, 21 Nov 2026 22:27:01 +0000 Subject: [PATCH] Replace Context and Intent windows with unified two-pane foundation --- ...d-Context-Workspace-Foundation-20261121.md | 137 ++++++ .../Browser/context-workspace-development.cjs | 37 ++ .../Browser/context-workspace-foundation.cjs | 84 ++++ PlotLine.Tests/Browser/package.json | 2 +- .../Browser/word-companion-regressions.cjs | 65 --- .../Browser/writing-context-development.cjs | 48 -- .../writing-context-follow-recovery.cjs | 59 --- .../Browser/writing-context-navigation.cjs | 36 -- .../Browser/writing-context-scale.cjs | 11 - .../Browser/writing-context-shell.cjs | 22 - PlotLine.Tests/Browser/writing-desks.cjs | 2 - PlotLine.Tests/Program.cs | 353 +------------- PlotLine.Tests/ToolbarBrowserHost.cs | 36 +- PlotLine.Tests/WordMarkerSecurityTests.cs | 4 +- PlotLine.Tests/WriterFoundationTests.cs | 5 +- .../WritingContextNavigationTests.cs | 2 +- .../WritingContextPlotLinesTests.cs | 2 +- PlotLine.Tests/WritingIntegrationTests.cs | 35 +- .../Controllers/NativeWorkspaceController.cs | 2 +- .../Controllers/WordCompanionController.cs | 8 +- PlotLine/Controllers/WritingController.cs | 242 +++------- PlotLine/Hubs/NativeCompanionPresenceHub.cs | 2 +- PlotLine/Hubs/WordCompanionFollowHub.cs | 85 +--- .../Models/WritingWorkspacePresenceModels.cs | 76 --- PlotLine/Program.cs | 3 +- .../ContextReferenceInvalidationFilter.cs | 19 + .../Services/ContextWorkspaceNotifications.cs | 16 + .../Manuscript/ParagraphManuscriptService.cs | 3 +- .../Services/WordCompanionPresenceMonitor.cs | 39 +- .../WritingWorkspacePresenceService.cs | 218 --------- .../Views/NativeWorkspace/Workspace.cshtml | 4 +- PlotLine/Views/WordCompanionHost/Index.cshtml | 2 +- PlotLine/Views/Writer/Legacy.cshtml | 10 +- PlotLine/Views/Writer/_WriterWrite.cshtml | 4 +- PlotLine/Views/Writing/Context.cshtml | 80 ++-- PlotLine/Views/Writing/Intent.cshtml | 51 -- PlotLine/Views/Writing/_ContextTab.cshtml | 5 + .../Writing/_WritingContextContent.cshtml | 93 ---- .../Writing/_WritingIntentContent.cshtml | 121 ----- PlotLine/wwwroot/css/context-workspace.css | 34 ++ PlotLine/wwwroot/css/site.css | 137 +----- PlotLine/wwwroot/js/context-workspace.js | 255 ++++++++++ .../wwwroot/js/native-companion-status.js | 6 +- .../wwwroot/js/native-companion-workspace.js | 4 +- PlotLine/wwwroot/js/word-companion-host.js | 25 +- .../wwwroot/js/writing-context-components.js | 50 -- PlotLine/wwwroot/js/writing-context.js | 17 - PlotLine/wwwroot/js/writing-follow.js | 439 ------------------ PlotLine/wwwroot/js/writing-intent.js | 18 - .../wwwroot/js/writing-workspace-launcher.js | 281 +---------- PlotLine/wwwroot/js/writing-workspace.js | 405 +--------------- 51 files changed, 819 insertions(+), 2875 deletions(-) create mode 100644 Docs/Writer/Unified-Context-Workspace-Foundation-20261121.md create mode 100644 PlotLine.Tests/Browser/context-workspace-development.cjs create mode 100644 PlotLine.Tests/Browser/context-workspace-foundation.cjs delete mode 100644 PlotLine.Tests/Browser/word-companion-regressions.cjs delete mode 100644 PlotLine.Tests/Browser/writing-context-development.cjs delete mode 100644 PlotLine.Tests/Browser/writing-context-follow-recovery.cjs delete mode 100644 PlotLine.Tests/Browser/writing-context-navigation.cjs delete mode 100644 PlotLine.Tests/Browser/writing-context-scale.cjs delete mode 100644 PlotLine.Tests/Browser/writing-context-shell.cjs delete mode 100644 PlotLine.Tests/Browser/writing-desks.cjs delete mode 100644 PlotLine/Models/WritingWorkspacePresenceModels.cs create mode 100644 PlotLine/Services/ContextReferenceInvalidationFilter.cs create mode 100644 PlotLine/Services/ContextWorkspaceNotifications.cs delete mode 100644 PlotLine/Services/WritingWorkspacePresenceService.cs delete mode 100644 PlotLine/Views/Writing/Intent.cshtml create mode 100644 PlotLine/Views/Writing/_ContextTab.cshtml delete mode 100644 PlotLine/Views/Writing/_WritingContextContent.cshtml delete mode 100644 PlotLine/Views/Writing/_WritingIntentContent.cshtml create mode 100644 PlotLine/wwwroot/css/context-workspace.css create mode 100644 PlotLine/wwwroot/js/context-workspace.js delete mode 100644 PlotLine/wwwroot/js/writing-context-components.js delete mode 100644 PlotLine/wwwroot/js/writing-context.js delete mode 100644 PlotLine/wwwroot/js/writing-follow.js delete mode 100644 PlotLine/wwwroot/js/writing-intent.js diff --git a/Docs/Writer/Unified-Context-Workspace-Foundation-20261121.md b/Docs/Writer/Unified-Context-Workspace-Foundation-20261121.md new file mode 100644 index 00000000..77c2bcc1 --- /dev/null +++ b/Docs/Writer/Unified-Context-Workspace-Foundation-20261121.md @@ -0,0 +1,137 @@ +# Unified Context Workspace — foundation + +21 November 2026. This replaces the separate Context/Intent window framework. Only **Overview** and **Characters in Scene** are registered. Existing planning records, canonical data, full editors, map/plot/metric tools and explicit AI Evidence services remain intact for subsequent tab migrations. + +## Architecture and routes + +`WritingController.Context` serves `/Writing/Context`, always using `_WritingCompanionLayout`. The page is a viewport shell: connection indicator/dialog, shared manuscript navigation, layout controls, two pane slots and a divider. The shared toast host remains in the layout, outside partial replacement. No framework dependency or schema migration was introduced. + +Each pane has its own tool chooser, scroll container, component records, request generation and dirty/busy state. Both panes use one manuscript position and one chosen native document session. Either tool can appear in either or both panes; server responses are parsed independently into different DOM nodes. The initial partials contain no repeated fixed IDs. + +| Route | Ownership | +| --- | --- | +| GET `/Writing/Context` | Authorized window shell and saved-scene choices. Accepts project/book/chapter/scene, document GUID, pinned flag and complete native instance/session. | +| GET `/Writing/Context/Tabs/overview` | `ContextScene` → existing canonical context composition → `_ContextTab` / `_WritingContextOverview`. | +| GET `/Writing/Context/Tabs/characters` | `ContextCharacters` → canonical context composition → `_ContextTab` / `_WritingContextPeople`. | +| GET `/Writing/Context/Position` | Account-scoped authoritative Office presence recovery; book/project access checked independently. | +| POST `/Writing/Context/Navigate` | Existing antiforgery-protected, session/revision/accepted-position-verified native navigation; command behavior retained. | +| GET `/Writing/Intent` and `/Writing/Intent/Scene` | Compatibility redirects to Context, preserving scoped position, document/session and pinned parameters. There is no Intent shell behind them. | +| `/Writing/Intent/Assessment` and `/decision` | Existing explicit Evidence GET/POST/decision endpoints, retained; never invoked by the two initial tabs. | + +Both tab endpoints independently validate model binding, project/book/scene relationships and project access. Native requests additionally verify the selected saved session mapping both before and after data loading. A changed mapping returns 409. Missing/unavailable saved scenes do not become authorized browser selections. An event or stored UI record never grants access. + +## Registration and lifecycle contract + +The small declarative registry lives in `Views/Writing/Context.cshtml`, serialized as JSON for `wwwroot/js/context-workspace.js`: + +```text +id, displayName, endpoint +scope: None | Book | Chapter | Scene | Paragraph +contentRefresh: none | relevant-scope +lifecycle: name of a registered lifecycle implementation +refreshGuard: defer-while-dirty-or-busy +``` + +The two current registrations use Scene scope, relevant saved-content refresh and the reference lifecycle. Navigation scopes are hierarchical: project/book identity precedes chapter, scene and paragraph. Paragraph IDs remain null unless supplied by an authoritative future integration; no paragraph position is invented from a scene ID or cursor offset. + +A future component can register lifecycle hooks through `window.PlotDirectorContextLifecycles` before controller initialization, or `root.contextController.registerLifecycle(name, hooks)` before mounting it. Hooks are `mount(node, {paneId, windowId, position})`, `dispose(node)` and optional `canRefresh(node, record)`. Hooks own component behavior; the window controller has no Overview/Characters business branches. + +A pane dispatches `context-panel-state` with `{dirty, busy}` when interaction must defer replacement. While guarded, refresh marks the record stale and shows an inline notice; changing tools is deferred too. Clearing both flags loads the latest pending context. A future editor must retain its original record identity and implement server concurrency checks. This foundation adds no inline planning editor or automatic save. + +On replacement the controller disposes the old component and mounts a fresh server fragment; it restores pane scroll and preserves equivalent link focus when possible. Shell controls and toasts are never replaced. Hidden records retain stale flags and presentation state, and load only when selected/visible. Lifecycle disposal also runs when a pane is hidden or the window closes. + +## Connection ownership and accepted data + +Each live Context window owns exactly one browser SignalR connection, to the existing cookie-authenticated `/hubs/native-companion` (`NativeCompanionPresenceHub`). The group remains server-derived per authenticated user; clients cannot select another account's group. Pinned snapshots start no Context connection. + +The same connection carries: + +- Existing `NativePresenceChanged` hints, causing the existing native status reader to recover current leases over ordinary HTTP. +- `ContextPositionChanged` hints from the Office current-scene API, registration/heartbeat/disconnection and stale-presence monitor. The window re-reads `/Writing/Context/Position`; it does not install arbitrary event payloads as current position. +- `ContextInvalidated` lightweight book/chapter/scene hints at existing accepted manuscript save and successful editor/API update boundaries. These mark saved reference content stale, including when scene ID is unchanged. + +`ContextWorkspaceNotifications` publishes account-group hints and catches transport failures so a committed save is never reported as failed because a browser notification could not be sent. `ParagraphManuscriptService.Save` announces after accepted persistence and the existing derived-statistics step. `WordCompanionController` announces after successful existing scene/manuscript/link/progress update calls. `ContextReferenceInvalidationFilter` covers successful Scene editor POSTs and chapter-goal saves. It does not run capture, typing analysis or AI. + +`native-companion-status.js` retains its HTTP recovery, document selection, connection dialog, synchronization controls, lease expiry, visibility handling and 15-second recovery polling. In a Context shell it does **not** create its own hub connection. Other application pages keep their existing status behavior. The Context controller supplies its native wake/reconnect events. Native leases take precedence over Office fallback; ambiguous, disconnected, unsaved or unverified sessions retain saved content with explicit persistent warnings. A selected document never silently falls back to another instance. + +Existing Word/native observation sequence checks, chapter/paragraph acceptance, native-agent command connections, navigation receipts, typing debounce, batching, reconciliation and Story Intelligence pipeline are unchanged. Observing a new Word revision is not evidence that prose or canonical analysis completed. Accepted-data hints request fresh saved reads; they never claim analysis completion. + +On reconnect the controller re-reads authoritative position/status and invalidates visible content even for unchanged scene IDs. Initial connection failures can retry on the existing recovery interval. Visibility recovery revalidates authority. Office recovery fetches are serialized and guarded against a newer native selection/observation. Full-page/login HTML and redirected partial responses are rejected rather than inserted. + +## Refresh and request ordering + +The controller tracks record staleness independently for each pane/tool. Relevant navigation or saved-data invalidation refreshes visible clean tools; inactive tools wait until next selection. Scope invalidation is conservative within the current book because established reference records may affect later scene context. Unknown-scope editor invalidations revalidate current saved reference, not manuscript analysis. + +Equivalent concurrent requests from both panes share one HTTP response promise for the same endpoint/context/generation; each pane constructs and owns its own fragment. Navigation/invalidation cancels obsolete requests. Window generation plus pane revision, tab identity and visibility checks reject late results. Detached, superseded or guarded panels never receive a replacement. Persistent inline status explains missing mappings, access/session expiry, interrupted requests and retained stale content. Refresh saved data offers explicit retry; routine passive updates stay silent. + +## Window and pane state + +Versioned localStorage keys are `plotdirector.context.v1..`. sessionStorage records the current window identity; managed launches pass a fresh `contextWindow` UUID. Ordinary refresh/navigation restores that window's layout, ratio, both pane selections, selected document and per-tool scroll. No manuscript prose or unsaved form drafts are persisted. + +New Context, Writer, native launcher and Office launches open independent windows with a fresh UUID/default single-pane arrangement. Role-wide popup names, role focus selection and global active-tab keys are gone. An opener check plus account-scoped BroadcastChannel identity claims detects cloned/duplicated live tabs; the newcomer receives a new identity/default layout. Explicit native document parameters are retained during clone repair. Optional storage/channel failures do not prevent the reference workspace from operating; without BroadcastChannel, unmanaged browser tab duplication cannot be guaranteed collision-free, although managed launches and opener clones remain isolated. + +Single mode retains pane two's tool and state. Layouts are Single, Side by side and Stacked. Pointer drag and arrow/Home/End keyboard controls resize the separator; orientation, value and controlled pane IDs are exposed for assistive technology. Ratios are bounded; pane-size constraints are clamped to the available viewport. On very small/zoomed displays users can select stacked or single layout rather than relying on operating-system snapping. + +`context-workspace.css` makes pane content an inline-size container, uses independently scrollable flex/grid slots, wraps shell controls and reflows cards/facts by pane width. It removes page-height assumptions inside panes. The parent cannot develop horizontal overflow from the reference cards. Full map/floor/plot editor layout work is intentionally outside this two-tab phase. + +## Removed legacy components + +- Standalone `Views/Writing/Intent.cshtml` and aggregate `_WritingContextContent` / `_WritingIntentContent` shells. +- `writing-follow.js`, its `writing-context.js` / `writing-intent.js` initializers and `writing-context-components.js` page controller. +- Browser role registration, fixed popup names, multi-monitor Context-versus-Intent placement and global selected-tab persistence from `writing-workspace.js` / launcher. These files now contain only independent Context launch behavior. +- `WritingWorkspacePresenceService`, its role/window models and registration/watch/heartbeat/focus methods in `WordCompanionFollowHub`; obsolete background role-presence cleanup/broadcasts. +- Styles exclusive to the retired window/page/tab shells. Reusable cards, facts and dormant feature styles remain. +- Legacy browser/static tests asserting the removed architecture, replaced by the Context foundation suite and updated server integration tests. + +`WordCompanionFollowHub` itself remains necessary for Office presence/onboarding/import. It is not loaded by Context. The native notification hub and native agent command connection remain operational for their existing responsibilities. + +## Retained, deliberately dormant features + +Relationships, floor plans, maps, Story/continuity, Plot Lines, Metrics, chapter/scene planning, Must Include, Notes, Threads, Checklist/workflow and AI Evidence implementation/data remain. Reusable feature partials and map/plot/assessment JavaScript are preserved but not registered or loaded by the new shell. Remaining standalone feature endpoints are not a second Context window architecture. Old helper-based map/plot browser fixtures will need their tab integration adapted when those features are migrated. + +The Scene editor, Writer Chapter workflows, full Maps/Floor Plans/Relationships/Plot Lines/Calendar and Story Intelligence review workspaces remain available. Overview's saved source links and the full Scene editor are preserved. Character knowledge remains author reference with established source provenance, not an assertion that the viewpoint character knows another participant's information. AI Evidence hashes, decisions and explicit POST semantics are untouched. + +## Verification and qualification + +- Normal `dotnet build PlotLine.slnx`: clean build, zero warnings/errors at the recorded gate. +- Full executable regression harness: 673 PASS lines, exit 0; includes updated native session/access/ownership/reference-data checks and existing native command/authentication suites. Additional notification-boundary assertions are included in focused Writing integration qualification. +- `--writing-integration`: authoritative reference hydration, scope/access, exact native session, unsaved/stale mappings, during-load changes, chronology/provenance and request reuse. +- `Browser/context-workspace-foundation.cjs`: real compiled Razor shell and both partials in the isolated loopback host, with synthetic reference data and controllable HTTP/SignalR inputs. Covers layouts, pointer/keyboard divider, same/different tabs, shared reads, hidden staleness, same-scene invalidation, rapid chapter/scene races, dirty/busy deferral, access/session failures, reconnect, native ambiguity/document selection, Office fallback/native precedence, independent windows, cloned storage, persistence, pinned snapshots and Office/Intent launch compatibility. +- Browser sizes include 1366×768, 760×768, 683×384 and 480×700 at 125% CSS zoom; shell/card reflow and no document-wide horizontal overflow are checked. The 683×384 viewport approximates the CSS space at 200% on a 1366×768 display. +- Shared notifications browser checks pass in browser and simulated standalone presentation. Existing Evidence request/cancel/isolation checks remain applicable. +- Standalone presentation is simulated Chromium qualification. Physical installed-PWA, Windows Word/VSTO and OS-level zoom/assistive-technology acceptance remain manual; these are not claimed as automated physical tests. + +Browser suite uses the existing isolated host: + +```sh +dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --toolbar-browser-host +node PlotLine.Tests/Browser/context-workspace-foundation.cjs +``` + +No real author manuscript was used. Development smoke uses a dedicated disposable account, a synthetic project/book/chapter created through normal authenticated forms, and a new synthetic scene saved through the existing SceneRepository after explicit disposable ownership checks; no import or AI run is needed. Deployment and authenticated smoke evidence are recorded below after execution. + +## Development deployment evidence + +Pending final publish/install and authenticated smoke verification. Production is outside this task's authorization and remains untouched. No schema migration is required. The normal active-work guard must pass immediately before restarting Development. + +## Adding a future tab + +1. Reuse its canonical service/repository and introduce an independently authorized partial GET; keep business interpretation and access checks on the server. Do not initiate analysis on GET. +2. Return one `_ContextTab`-compatible fragment with authoritative scope attributes. Make IDs and presentation state instance-safe; avoid document-global component selectors/listeners. +3. Add registry metadata and, when needed, an instance lifecycle. Use pane container dimensions; dispose observers/listeners/requests on replacement. +4. Declare dirty/busy protection, explicit save actions and server concurrency checks. Place transient outcomes in the existing toast service; retain persistent validation/recovery inline. +5. Identify accepted-data invalidation boundaries and verify reconnect/same-scene refresh. Reuse existing sync acceptance; do not add a typing debounce or new analysis pipeline. +6. Qualify the same tab twice, both orientations, hidden staleness, response ordering, focus/scroll, narrow/zoom presentation and two independent windows. + +## Manual acceptance steps + +1. Sign into Development, open a book/scene, then choose **Context** from Writer or **Open Context** from Companion. Confirm Overview displays the saved scene and only two tools are offered. +2. Choose **Side by side** and **Characters in Scene** in pane two. Check saved participants, roles, physical/emotional state, location/movement and established knowledge/source links against the Scene editor. +3. Choose Overview in both panes, then Characters in both. Scroll each independently; change one chooser and verify the other is unchanged. +4. Drag the divider. Focus it and use the orientation-appropriate arrows plus Home/End. Switch to **Stacked**, then Single, then split again; verify pane two's selection survives. +5. Refresh the browser. Verify layout, proportion, selected tools, document selection and practical scroll state restore. Open **New Context window** and verify a fresh single-pane layout; alter it without affecting the first. Duplicate a live browser tab and verify its identity/layout becomes independent. +6. Move through chapters/scenes in a saved, correctly linked Word document. Confirm both panes follow the same verified scene. Select among two native documents via the connection indicator; ambiguous/unverified mappings must explain why following is unavailable, without guessing a scene or sending navigation. +7. Save an accepted manuscript update while staying in the same scene, or save a scene change in another PlotDirector window. Verify visible reference content refreshes without an AI request or routine toast; a hidden tool should refresh when selected. +8. Interrupt/reconnect the notification connection and restore Word. Verify authoritative scene recovery and same-scene revalidation. Try an unsaved/missing mapping and confirm saved browsing/recovery explanations remain available. +9. Open `?pinned=true&sceneId=&bookId=` and verify Word movement does not retarget it. Manual scene navigation still works. Check an old Intent link redirects to Context with its scope/session intact. +10. At 1366×768, a narrow browser and 125–200% browser zoom, check both orientations, scroll, labels and keyboard focus. Repeat in the installed PWA and physical Word environment when available. Signing out/expiring a session must produce sign-in/access feedback rather than nesting a login page in a pane. diff --git a/PlotLine.Tests/Browser/context-workspace-development.cjs b/PlotLine.Tests/Browser/context-workspace-development.cjs new file mode 100644 index 00000000..e0134ed7 --- /dev/null +++ b/PlotLine.Tests/Browser/context-workspace-development.cjs @@ -0,0 +1,37 @@ +// Opt-in Development smoke. Only edits a specifically named disposable synthetic scene. +const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict'); +(async()=>{ + const identity=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)); + const scope=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE)); + assert.equal(identity.Database,'PlotDirector_Development');assert.equal(identity.UserID,scope.user); + assert(identity.Email.startsWith('pwa-browser-')&&identity.Email.endsWith('@example.invalid')); + const base='https://dev.plotdirector.com',browser=await chromium.launch();let step='login',restore; + try { + const context=await browser.newContext({viewport:{width:1366,height:768}}),page=await context.newPage(); + 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('button[type=submit]').click()]); + step='ownership and synthetic identity';await page.goto(base+'/Projects/Details/'+scope.project);assert(await page.getByText('Context foundation disposable qualification',{exact:true}).count()); + const url=`${base}/Writing/Context?projectId=${scope.project}&bookId=${scope.book}&sceneId=${scope.scene}`; + let connections=0,reads=0;const errors=[];page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(r.url().includes('/hubs/')&&r.url().includes('/negotiate'))connections++;if(r.url().includes('/Writing/Context/Tabs/overview'))reads++;}); + step='real authorized Overview';await page.goto(url);await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').waitFor(); + const title=await page.locator('[data-context-pane="0"] [data-context-tab-fragment]>h2').innerText();assert.equal(title,'Synthetic foundation scene'); + await page.waitForTimeout(500);assert.equal(connections,1,'one real browser SignalR connection'); + step='Characters and split';await page.selectOption('[data-context-layout]','columns');await page.locator('[data-context-pane="1"] [data-context-tab-fragment]').waitFor();assert.match(await page.locator('[data-context-pane="1"]').innerText(),/No characters recorded/); + await page.selectOption('[data-context-pane="1"] [data-context-tab]','overview');await page.waitForFunction(()=>document.querySelectorAll('[data-context-tab-fragment]>h2').length===2); + step='independent window';const opened=page.waitForEvent('popup');await page.click('[data-context-new]');const popup=await opened;await popup.waitForSelector('[data-context-tab-fragment]');assert.equal(await popup.locator('[data-context-layout]').inputValue(),'single'); + const editor=await context.newPage();await editor.goto(base+`/Scenes/Edit/${scope.scene}`);await editor.click('[data-scene-editor="scene-details"]');const form=editor.locator('[data-scene-editor-form]').filter({has:editor.locator('[name="SceneTitle"]')});await form.waitFor(); + const saved=await form.evaluate(n=>({action:n.action,fields:Object.fromEntries([...new FormData(n)].filter(([,v])=>typeof v==='string'))}));assert.equal(saved.fields.SceneTitle,title);restore=async()=>{const response=await page.request.post(saved.action,{form:saved.fields});assert(response.ok(),'synthetic title restore failed');}; + await page.waitForTimeout(300);const before=reads; + step='real cross-window invalidation';const response=await editor.request.post(saved.action,{form:{...saved.fields,SceneTitle:title+' updated through editor'}});assert(response.ok()); + await page.waitForFunction(()=>[...document.querySelectorAll('[data-context-tab-fragment]>h2')].every(n=>n.textContent.includes('updated through editor'))); + await popup.waitForFunction(()=>document.querySelector('[data-context-tab-fragment]>h2').textContent.includes('updated through editor')); + assert.equal(reads-before,1,'same tab in two panes shares one real refresh request');await restore();restore=null;await page.waitForFunction(()=>[...document.querySelectorAll('[data-context-tab-fragment]>h2')].every(n=>n.textContent==='Synthetic foundation scene')); + step='persistence';await page.selectOption('[data-context-layout]','rows');const id=await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId);await page.reload();await page.waitForSelector('[data-context-tab-fragment]');assert.equal(await page.locator('[data-context-layout]').inputValue(),'rows');assert.equal(await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId),id); + step='snapshot and real authorization';const pinned=await context.newPage();let snapshotConnections=0;pinned.on('request',r=>{if(r.url().includes('/hubs/')&&r.url().includes('/negotiate'))snapshotConnections++;});await pinned.goto(url+'&pinned=true');await pinned.waitForSelector('[data-context-tab-fragment]');assert.equal(snapshotConnections,0); + const native=await page.request.get(`${base}/Writing/Context/Tabs/overview?bookId=${scope.book}&sceneId=${scope.scene}&instanceId=11111111-1111-4111-8111-111111111111&sessionId=22222222-2222-4222-8222-222222222222`);assert.equal(native.status(),409); + const foreign=await page.request.get(`${base}/Writing/Context/Tabs/overview?bookId=2147483647&sceneId=${scope.scene}`);assert([403,404].includes(foreign.status())); + const old=await page.request.get(`${base}/Writing/Intent?projectId=${scope.project}&bookId=${scope.book}&sceneId=${scope.scene}`,{maxRedirects:0});assert.equal(old.status(),302);assert.match(old.headers().location,/Writing\/Context/); + const anonymous=await browser.newContext();const denied=await anonymous.request.get(`${base}/Writing/Context/Tabs/characters?sceneId=${scope.scene}`,{maxRedirects:0});assert([302,401].includes(denied.status()));await anonymous.close(); + assert.deepEqual(errors,[]);await context.close();console.log('PASS Development actual saved Razor data, one real SignalR connection, two panes/shared read, cross-window editor invalidation, independent window, persistence, pinned snapshot, native session/access denial and Intent redirect; synthetic title restored'); + } catch(error){console.error('FAILED at '+step+': '+error.message);process.exitCode=1;} finally{if(restore)await restore();await browser.close();} +})().catch(()=>{console.error('Development Context smoke could not complete');process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/context-workspace-foundation.cjs b/PlotLine.Tests/Browser/context-workspace-foundation.cjs new file mode 100644 index 00000000..c3617650 --- /dev/null +++ b/PlotLine.Tests/Browser/context-workspace-foundation.cjs @@ -0,0 +1,84 @@ +// Actual compiled Razor shell and partials; isolated loopback fixture, no database or Word writes. +const {chromium}=require('playwright'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; +const fakeSignalR=`window.contextConnections=[];window.signalR={HubConnectionBuilder:class{withUrl(url){this.url=url;return this}withAutomaticReconnect(){return this}build(){const c={url:this.url,state:'Disconnected',handlers:{},on(n,f){this.handlers[n]=f},onreconnecting(f){this.reconnecting=f},onreconnected(f){this.reconnected=f},onclose(f){this.closed=f},async start(){this.state='Connected'},async stop(){this.state='Disconnected'}};contextConnections.push(c);return c}}};`; +const lease=(extra={})=>({instanceId:'11111111-1111-4111-8111-111111111111',sessionId:'22222222-2222-4222-8222-222222222222',manuscriptId:'33333333-3333-4333-8333-333333333333',bookId:12,chapterId:10,sceneId:22,wordAvailable:true,wordSaved:true,active:true,positionVerified:true,mappingCurrent:true,snapshotRevision:1,revision:1,documentTitle:'Synthetic manuscript',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString(),...extra}); +(async()=>{ + const browser=await chromium.launch();let step='setup'; + try{ + const context=await browser.newContext({viewport:{width:1366,height:768}}); + let leases=[lease()],office={connected:false,position:null},revision=1,mode='ok',delayScene=null,requests=[]; + await context.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fakeSignalR})); + await context.route('**/native-companion/status',r=>r.fulfill({json:leases})); + await context.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected'}})); + await context.route('**/Writing/Context/Position?*',r=>r.fulfill({json:office})); + await context.route('**/Writing/Context/Navigate',r=>r.fulfill({status:409,json:{message:'No current Word mapping. Saved scene selected.'}})); + await context.route('**/Writing/Context/Tabs/*',async route=>{ + const url=new URL(route.request().url());const tool=url.pathname.split('/').at(-1),scene=url.searchParams.get('sceneId'); + requests.push({tool,scene,revision});const captured=revision; + if(mode==='expired')return route.fulfill({status:401,body:'Sign in'}); + if(mode==='mapping')return route.fulfill({status:409,body:'Mapping pending'}); + const response=await route.fetch({url:`${base}/context-tab-fixture/${tool}?sceneId=${scene}`}); + const html=(await response.text()).replace('Saved scene summary and provenance',`Saved scene summary and provenance · revision ${captured}`); + if(delayScene===scene)await new Promise(resolve=>setTimeout(resolve,350)); + try{await route.fulfill({contentType:'text/html',body:html});}catch{/* Navigation may abort an obsolete shared read. */} + }); + const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message)); + step='single-pane actual Razor';await page.goto(base+'/Writing/Context'); + await page.locator('[data-context-pane="0"] [data-context-tab-fragment][data-scene-id="22"]').waitFor(); + assert.equal(await page.evaluate(()=>contextConnections.length),1,'one shared connection, including native status shell'); + assert.equal(await page.locator('[data-context-pane="1"]').isVisible(),false); + assert.match(await page.locator('[data-context-pane="0"]').innerText(),/viewpoint knowledge|POV/i); + step='columns, independent tools';await page.selectOption('[data-context-layout]','columns'); + await page.locator('[data-context-pane="1"] [data-context-tab-fragment]').waitFor(); + assert.match(await page.locator('[data-context-pane="1"]').innerText(),/Fixture participant/); + assert.match(await page.locator('[data-context-pane="1"]').innerText(),/Uncertain/); + assert.match(await page.locator('[data-context-pane="1"]').innerText(),/Hall.*Garden/s); + if(process.env.PD_CONTEXT_EVIDENCE){fs.mkdirSync(process.env.PD_CONTEXT_EVIDENCE,{recursive:true});await page.screenshot({path:process.env.PD_CONTEXT_EVIDENCE+'/columns-1366.png'});} + step='same tab twice and shared HTTP request';requests=[]; + await page.selectOption('[data-context-pane="1"] [data-context-tab]','overview'); + await page.waitForFunction(()=>[...document.querySelectorAll('[data-context-pane-content]')].every(n=>n.textContent.includes('Saved scene summary'))); + await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate()); + await page.waitForTimeout(180); + assert.equal(requests.length,2,'one new pane initial read plus one shared invalidation read'); + const ids=await page.locator('[id]').evaluateAll(nodes=>nodes.map(n=>n.id));assert.equal(ids.length,new Set(ids).size,'no duplicate IDs'); + assert.equal(await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').evaluate((n)=>n===document.querySelector('[data-context-pane="1"] [data-context-tab-fragment]')),false); + step='divider keyboard and drag';const divider=page.locator('[data-context-divider]');await divider.focus();const initial=Number(await divider.getAttribute('aria-valuenow'));await page.keyboard.press('ArrowRight');assert(Number(await divider.getAttribute('aria-valuenow'))>initial); + let box=await divider.boundingBox();await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();await page.mouse.move(850,box.y+box.height/2);await page.mouse.up();assert(Number(await divider.getAttribute('aria-valuenow'))>55); + step='stacked layout';await page.selectOption('[data-context-layout]','rows');assert.equal(await divider.getAttribute('aria-orientation'),'horizontal');await divider.focus();await page.keyboard.press('ArrowUp'); + const a=await page.locator('[data-context-pane="0"]').boundingBox(),b=await page.locator('[data-context-pane="1"]').boundingBox();assert(b.y>a.y+a.height); + step='single retains second pane selection';await page.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await page.selectOption('[data-context-layout]','single');await page.selectOption('[data-context-layout]','columns');assert.equal(await page.locator('[data-context-pane="1"] [data-context-tab]').inputValue(),'characters'); + step='same scene accepted content and inactive stale selection';revision=2;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({bookId:12}));await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 2')); + await page.selectOption('[data-context-pane="0"] [data-context-tab]','characters');await page.selectOption('[data-context-pane="0"] [data-context-tab]','overview');await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 2')); + step='rapid scene/chapter navigation and out of order responses';delayScene='23';await page.evaluate(()=>{const c=document.querySelector('[data-context-workspace]').contextController;c.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23});setTimeout(()=>c.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22}),30);});await page.waitForTimeout(550);assert.equal(await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').getAttribute('data-scene-id'),'22');delayScene=null; + step='dirty/busy deferral';await page.evaluate(()=>document.querySelector('[data-context-pane="0"]').dispatchEvent(new CustomEvent('context-panel-state',{detail:{dirty:true}})));revision=3;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({bookId:12}));await page.waitForTimeout(160);assert.match(await page.locator('[data-context-pane="0"]').innerText(),/revision 2/);assert.match(await page.locator('[data-context-pane="0"] [data-context-pane-status]').innerText(),/editing|busy/); + await page.evaluate(()=>document.querySelector('[data-context-pane="0"]').dispatchEvent(new CustomEvent('context-panel-state',{detail:{dirty:false,busy:false}})));await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 3')); + step='session expiry and mapping conflict';mode='expired';await page.click('[data-context-refresh]');await page.waitForFunction(()=>document.querySelector('[data-context-pane-status]').textContent.includes('Sign in'));assert.match(await page.locator('[data-context-pane="0"]').innerText(),/revision 3/);mode='mapping';await page.click('[data-context-refresh]');await page.waitForFunction(()=>document.querySelector('[data-context-pane-status]').textContent.includes('mapping'));mode='ok'; + step='disconnect and unchanged-position reconnect';revision=4;await page.evaluate(()=>contextConnections[0].reconnecting());assert.match(await page.locator('[data-context-status]').innerText(),/reconnecting/);await page.evaluate(()=>contextConnections[0].reconnected());await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 4')); + step='native ambiguity and missing mapping';leases=[lease(),lease({instanceId:'44444444-4444-4444-8444-444444444444',active:true})];await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-status]').textContent.includes('Choose a Word document')); + await page.click('#native-companion-status');await page.selectOption('#writing-word-document','44444444-4444-4444-8444-444444444444/22222222-2222-4222-8222-222222222222');await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.instanceId==='44444444-4444-4444-8444-444444444444');await page.selectOption('#writing-word-document','');await page.click('[data-close-word-details]'); + leases=[lease({positionVerified:false,positionMessage:'Mapping pending'})];await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-status]').textContent.includes('Mapping pending')); + step='Office fallback and native precedence';leases=[];office={connected:true,position:{projectId:7,bookId:12,chapterId:11,sceneId:23}};await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===23); + leases=[lease()];await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===22); + step='persistence';await page.selectOption('[data-context-layout]','rows');const identity=await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId);await page.reload();await page.waitForSelector('[data-context-tab-fragment]');assert.equal(await page.locator('[data-context-layout]').inputValue(),'rows');assert.equal(await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId),identity); + step='cloned window storage';const storage=await page.evaluate(()=>({id:sessionStorage.getItem('plotdirector.context.window.v1')}));const clone=await context.newPage();await clone.addInitScript(s=>sessionStorage.setItem('plotdirector.context.window.v1',s.id),storage);await clone.goto(base+'/Writing/Context');await clone.waitForFunction(id=>document.querySelector('[data-context-workspace]')?.contextController?.windowId!==id,identity);assert.equal(await clone.locator('[data-context-layout]').inputValue(),'single');assert.equal(await page.locator('[data-context-layout]').inputValue(),'rows');await clone.close(); + step='multiple windows';const popupPromise=page.waitForEvent('popup');await page.click('[data-context-new]');const popup=await popupPromise;await popup.waitForSelector('[data-context-tab-fragment]');assert.equal(await popup.locator('[data-context-layout]').inputValue(),'single');assert.notEqual(await popup.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId),identity);assert.equal(await popup.evaluate(()=>contextConnections.length),1);await popup.close(); + step='laptop, narrow pane, zoom and standalone presentation';for(const [width,height,zoom]of [[1366,768,1],[760,768,1],[683,384,1],[480,700,1.25]]){ + await page.setViewportSize({width,height});await page.evaluate(zoom=>document.documentElement.style.zoom=zoom,zoom); + for(const layout of ['single','columns','rows']){await page.selectOption('[data-context-layout]',layout);await page.waitForTimeout(40);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`window overflow ${width}/${layout}/${zoom}`);assert(await page.locator('[data-context-pane="0"] [data-context-pane-content]').evaluate(n=>n.clientHeight>30));} + } + await page.evaluate(()=>{document.documentElement.style.zoom='1';Object.defineProperty(navigator,'standalone',{value:true});}); + step='pinned snapshot';leases=[lease({sceneId:23,chapterId:11})];const pinned=await context.newPage();await pinned.goto(base+'/Writing/Context?pinned=true&sceneId=22');await pinned.waitForSelector('[data-context-tab-fragment]');assert.equal(await pinned.evaluate(()=>contextConnections.length),0);assert.equal(await pinned.locator('[data-context-tab-fragment]').getAttribute('data-scene-id'),'22');await pinned.selectOption('[data-context-scene]','23');await pinned.waitForSelector('[data-context-tab-fragment][data-scene-id="23"]');await pinned.close(); + step='Office launch URL contract'; + const host=fs.readFileSync(require('node:path').join(__dirname,'../../PlotLine/wwwroot/js/word-companion-host.js'),'utf8'); + const launch=host.slice(host.indexOf(' const writingWorkspaceUrl ='),host.indexOf(' const openWritingWindow =')); + const build=new Function('window','crypto','URL','writingWorkspaceScope','currentDocumentGuid','resolvedChapterId','resolvedSceneId','detectedChapterAnchorId','detectedSceneAnchorId',launch+';return writingWorkspaceUrl'); + const launchUrl=build({location:{origin:base}},require('node:crypto').webcrypto,URL,()=>({projectId:7,bookId:12}),()=> '33333333-3333-4333-8333-333333333333',10,22,null,null); + const first=new URL(launchUrl('context'),base),second=new URL(launchUrl('workspace'),base); + assert.equal(first.pathname,'/Writing/Context');assert.equal(second.pathname,'/Writing/Context');assert.equal(first.searchParams.get('sceneId'),'22');assert.notEqual(first.searchParams.get('contextWindow'),second.searchParams.get('contextWindow')); + step='Intent compatibility';const redirected=await page.request.get(base+'/Writing/Intent?bookId=12&sceneId=23',{maxRedirects:0});assert.equal(redirected.status(),302);assert.match(redirected.headers().location,/Writing\/Context.*sceneId=23/); + assert.deepEqual(errors,[]);await context.close();console.log('PASS Context foundation: compiled Razor, two tabs, layouts/divider, shared requests, stale/race guards, dirty safety, native/Office/reconnect, windows/storage, auth failures, snapshot, narrow/zoom/standalone presentation'); + }catch(error){console.error('FAILED at '+step);throw error;}finally{await browser.close();} +})().catch(error=>{console.error(error);process.exit(1);}); diff --git a/PlotLine.Tests/Browser/package.json b/PlotLine.Tests/Browser/package.json index 244e6a96..246bf104 100644 --- a/PlotLine.Tests/Browser/package.json +++ b/PlotLine.Tests/Browser/package.json @@ -23,7 +23,7 @@ "test:maps-story": "node maps-story-engine.cjs && node maps-story.cjs", "test:writer": "node writer-workspace.cjs", "test:writer-goals": "node writer-goal-navigation.cjs", - "test:word-companion": "node word-companion-regressions.cjs" + "test:word-companion": "node context-workspace-foundation.cjs" }, "devDependencies": { "@microsoft/signalr": "8.0.7", diff --git a/PlotLine.Tests/Browser/word-companion-regressions.cjs b/PlotLine.Tests/Browser/word-companion-regressions.cjs deleted file mode 100644 index 5c826e70..00000000 --- a/PlotLine.Tests/Browser/word-companion-regressions.cjs +++ /dev/null @@ -1,65 +0,0 @@ -const {chromium}=require('playwright'); -const fs=require('node:fs'); -const path=require('node:path'); -const assert=require('node:assert/strict'); -const scripts=path.join(__dirname,'../../PlotLine/wwwroot/js'); -(async()=>{ - const browser=await chromium.launch(); - try{ - for(const role of ['context','intent']){ - const page=await browser.newPage(); - await page.goto('about:blank'); - await page.setContent(`
initial
`); - await page.addScriptTag({content:`window.__requests=[];window.fetch=(url,options)=>new Promise((resolve,reject)=>__requests.push({url:String(url),signal:options.signal,resolve,reject}));`}); - await page.addScriptTag({content:fs.readFileSync(path.join(scripts,'writing-follow.js'),'utf8')}); - await page.evaluate(role=>{ - // Override origin only in test URL construction; no network request is issued. - const OriginalURL=URL;window.URL=class extends OriginalURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}}; - window.follow=PlotDirectorWritingFollow.initialize({rootSelector:'#root',contentSelector:'#content',fragmentSelector:'#fragment',statusTextSelector:'#status',tabSelector:'.tab',panelSelector:'.panel',selectSelector:'.scene-select',defaultEndpoint:'/fragment',allowChapterOnly:role==='intent'}); - window.load=(sceneId,chapterId=1)=>follow.loadPosition({projectId:1,bookId:2,chapterId,sceneId}); - window.finish=(index,sceneId,chapterId=1)=>__requests[index].resolve({ok:true,text:async()=>`
${sceneId||chapterId}
`}); - },role); - await page.evaluate(()=>{window.first=load(11);window.second=load(12);}); - await page.evaluate(async()=>{finish(1,12);await second;finish(0,11);await first;}); - assert.equal(await page.locator('#fragment').getAttribute('data-scene-id'),'12',role+' late response cannot overwrite newer scene'); - assert.equal(await page.evaluate(()=>__requests[0].signal.aborted),true); - await page.evaluate(()=>{window.pending=load(13);void load(12);}); - await page.evaluate(async()=>{finish(2,13);await pending;}); - assert.equal(await page.locator('#fragment').getAttribute('data-scene-id'),'12',role+' returning to displayed scene cancels obsolete request'); - await page.evaluate(()=>{window.older=load(14);window.newer=load(15);}); - await page.evaluate(async()=>{__requests[3].reject(new Error('old failure'));await older;}); - assert.equal(await page.locator('#status').textContent(),'Updating',role+' old failure cannot replace newest loading state'); - await page.evaluate(async()=>{finish(4,15);await newer;}); - assert.equal(await page.locator('#fragment').getAttribute('data-scene-id'),'15'); - if(role==='intent'){ - await page.evaluate(()=>{window.chapter=load(null,2);}); - await page.evaluate(async()=>{finish(5,null,2);await chapter;}); - assert.equal(await page.locator('#fragment').getAttribute('data-scene-id'),null); - await page.evaluate(()=>{window.returnScene=load(15,2);}); - await page.evaluate(async()=>{finish(6,15,2);await returnScene;}); - assert.equal(await page.locator('#fragment').getAttribute('data-scene-id'),'15','chapter-only intent does not retain stale scene dedup identity'); - } - console.log('PASS '+role+' actual browser delayed responses, abort, current-scene return, old failure and chapter identity');await page.close(); - } - for(const mode of ['context','intent']){ - const pinned=await browser.newPage();await pinned.goto('about:blank');await pinned.setContent('
saved scene
'); - await pinned.addScriptTag({content:'window.signalR={HubConnectionBuilder:class{constructor(){throw new Error("Pinned view must not connect SignalR")}}};window.PlotDirectorWritingWorkspace={registerWindow(){throw new Error("Pinned view must not register latest-window routing")},roles:{context:"Context",intent:"Intent"}};'}); - await pinned.addScriptTag({content:fs.readFileSync(path.join(scripts,'writing-follow.js'),'utf8')}); - await pinned.evaluate(mode=>PlotDirectorWritingFollow.initialize({rootSelector:'#pinned',contentSelector:'#content',fragmentSelector:'#fragment',statusTextSelector:'#status',tabSelector:'.tab',panelSelector:'.panel',selectSelector:'.select',defaultEndpoint:'/fragment',source:mode==='context'?'WritingContext':'WritingIntent'}),mode); - await pinned.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:1,bookId:2,sceneId:99}}))); - assert.equal(await pinned.locator('#fragment').textContent(),'saved scene');assert.match(await pinned.locator('#status').textContent(),/snapshot/); - console.log('PASS pinned '+mode+' retains scoped saved content without SignalR/latest Word/window registration');await pinned.close(); - } - const page=await browser.newPage();await page.goto('about:blank'); - await page.addScriptTag({content:`window.__opened=[];window.open=(url,name)=>{__opened.push(name);const target=new URL(url,'https://fixture.invalid');return{location:{pathname:target.pathname,search:target.search,assign(value){const next=new URL(value,'https://fixture.invalid');this.pathname=next.pathname;this.search=next.search;}},focus(){}}};const peer={on(){},onreconnected(){},onclose(){},start:async()=>{},invoke:async()=>({projectID:1,bookID:2,windows:[]})};window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return peer}}};`}); - await page.addScriptTag({content:fs.readFileSync(path.join(scripts,'writing-workspace.js'),'utf8')}); - await page.evaluate(async()=>{ - const NativeURL=URL;window.URL=class extends NativeURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}}; - await PlotDirectorWritingWorkspace.registerWindow({projectID:1,bookID:2,writingRole:'Launcher'}); - window.__started=await PlotDirectorWritingWorkspace.startWorkspace({projectID:1,bookID:2}); - }); - assert.equal(await page.evaluate(()=>__started.ok),true);assert.deepEqual(await page.evaluate(()=>__opened),['PlotDirectorContext','PlotDirectorIntent']); - await page.evaluate(()=>{PlotDirectorWritingWorkspace.openRoleWindow('Context',{projectID:1,bookID:2});PlotDirectorWritingWorkspace.openRoleWindow('Context',{projectID:1,bookID:3});});assert.equal(await page.evaluate(()=>__opened.length),2,'Repeated launches and book changes reuse one Context window'); - console.log('PASS fresh Writer launcher opens both missing role windows without undeclared currentRole');await page.close(); - }finally{await browser.close();} -})().catch(error=>{console.error(error);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/writing-context-development.cjs b/PlotLine.Tests/Browser/writing-context-development.cjs deleted file mode 100644 index d112277a..00000000 --- a/PlotLine.Tests/Browser/writing-context-development.cjs +++ /dev/null @@ -1,48 +0,0 @@ -// Explicit live Development protocol verification. Requires guarded synthetic account/snapshot files. -// No AI calls, manuscript imports, Windows automation or real Word COM operations. -const {chromium}=require('playwright'); -const fs=require('node:fs'),crypto=require('node:crypto'),assert=require('node:assert/strict'); -const base='https://dev.plotdirector.com';let step='validate fixture files'; -(async()=>{ - const [identityPath,scopePath]=process.argv.slice(2); - assert.ok(identityPath?.startsWith('/tmp/pd-dev-browser-')&&scopePath?.startsWith('/tmp/pd-context-')); - assert.equal(fs.statSync(identityPath).mode&0o077,0); - const identity=JSON.parse(fs.readFileSync(identityPath)),scope=JSON.parse(fs.readFileSync(scopePath)); - assert.equal(identity.Database,'PlotDirector_Development');assert.equal(identity.UserID,scope.User);assert.match(identity.Email,/^pwa-browser-.*@example\.invalid$/);assert.equal(scope.SceneStarts.length,2); - 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();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); - response=await page.request.post(base+'/api/native-companion/token',{data:{code,verifier}});assert.equal(response.status(),200);const tokens=await response.json();const headers={Authorization:'Bearer '+tokens.accessToken}; - let sequence=0,cursor=scope.SceneStarts[0],revision=1;const commands=[]; - const presencePath=(instance=scope.Instance,session=scope.Session)=>base+`/api/native-companion/instances/${instance}/documents/${session}/presence`; - async function heartbeat(){const r=await page.request.post(presencePath(),{headers,data:{bookId:scope.Book,manuscriptId:scope.Manuscript,revision,sequence:++sequence,documentTitle:'Synthetic context manuscript.docx',wordRunning:true,wordAvailable:true,wordSaved:true,canCapture:true,canParagraphSync:true,active:true,cursorStart:cursor}});assert.equal(r.status(),200,'Native registration');const data=await r.json();if(data.navigation)commands.push(data.navigation);return data;} - 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]'); - 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.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='direct existing synchronisation action and exact document selection';const syncToken=await page.locator('[data-word-sync-form] [name=__RequestVerificationToken]').inputValue(); - response=await page.request.post(base+'/manuscript/paragraphs/snapshot',{headers:{'X-Requested-With':'XMLHttpRequest'},form:{bookId:String(scope.Book),instanceId:scope.Instance,sessionId:crypto.randomUUID(),__RequestVerificationToken:syncToken}});assert.equal(response.status(),409);assert.match((await response.json()).message,/selected Word document/i); - await page.click('#native-companion-status');await page.locator('[data-word-sync-button]').waitFor({state:'visible'});await page.waitForFunction(()=>!document.querySelector('[data-word-sync-button]').disabled); - const submitted=page.waitForResponse(r=>r.url().endsWith('/manuscript/paragraphs/snapshot')&&r.request().method()==='POST');await page.click('[data-word-sync-button]');response=await submitted;assert.equal(response.status(),200);const requestedSnapshot=await response.json();assert.match(requestedSnapshot.requestId,/^[0-9a-f-]{36}$/i); - const snapshotCommand=(await heartbeat()).navigation;assert.equal(snapshotCommand.kind,'paragraph-snapshot');assert.equal(snapshotCommand.id,requestedSnapshot.requestId);assert.equal(snapshotCommand.sessionId,scope.Session);assert.equal(commands.filter(c=>c.kind==='navigate').length,1);assert.ok(!(await page.locator('[data-word-sync-feedback]').textContent()).includes('accepted.'),'request alone is not acceptance'); - await page.request.delete(base+'/api/native-companion/manuscript-capture/'+snapshotCommand.id,{headers});await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('ended without an accepted snapshot'));await page.click('[data-close-word-details]'); - 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. 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 deleted file mode 100644 index 6b6ea941..00000000 --- a/PlotLine.Tests/Browser/writing-context-follow-recovery.cjs +++ /dev/null @@ -1,59 +0,0 @@ -// 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,wordSaved=true,verified=true,fragmentReads=0,failStatus=false,holdStatus=false,release,reads=0,commands=0,fragmentFailure=false,fragmentConflict=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,positionVerified:verified,active:true,documentTitle:'Synthetic',expires:new Date(Date.now()+45000).toISOString()}]});} - if(u.pathname==='/Writing/Context/Scene'){ - fragmentReads++;assert.equal(u.searchParams.get('instanceId')||'instance','instance');assert.equal(u.searchParams.get('sessionId')||'session','session'); - if(holdFragment){holdFragment=false;await new Promise(resolve=>releaseFragment=resolve);} - return r.fulfill(fragmentConflict?{status:409}: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'); - const repeated=fragmentReads; - for(let i=0;i<8;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,0);assert.equal(await page.evaluate(()=>focusCalls),0);assert.equal(fragmentReads,repeated,'unchanged native scenes do not recompute context fragments'); - // 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,[]); - // A pending/unsaved mapping must invalidate an older in-flight scene response. - holdFragment=true;current=23;await pulse();while(!releaseFragment)await page.waitForTimeout(10); - wordSaved=false;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Save Word')); - releaseFragment();await page.waitForTimeout(150);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22','late fragment cannot restore an earlier cursor after native mapping becomes pending'); - wordSaved=true;verified=false;await pulse();await page.waitForTimeout(60);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22','unverified claimed native scene cannot replace saved context'); - verified=true;fragmentConflict=true;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('awaiting verification'));assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22');fragmentConflict=false;await pulse();await scene(23);assert.equal(commands,1); - console.log('PASS pending native response cancellation, unverified mapping refusal, exact-session query parameters and no recomputation for repeated unchanged scenes'); - 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 deleted file mode 100644 index a0bf7b4a..00000000 --- a/PlotLine.Tests/Browser/writing-context-navigation.cjs +++ /dev/null @@ -1,36 +0,0 @@ -const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path'); -const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; -(async()=>{const browser=await chromium.launch();try{ - for(const width of [400,760,1600]) for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']){ - const page=await browser.newPage({viewport:{width,height:850}});let commands=0,fullPage=false; - await page.route('**/Writing/Context/Navigate',async route=>{commands++;assert.equal(route.request().method(),'POST');await route.fulfill({json:{message:'Navigation requested in Word. Cursor confirmation is still pending.'}});}); - await page.route('**/Writing/Context/Scene?*',async route=>{ - if(fullPage){await route.fulfill({contentType:'text/html',body:''});return;} - const id=new URL(route.request().url()).searchParams.get('sceneId');await new Promise(r=>setTimeout(r,80)); - const response=await route.fetch({url:base+'/writing-desk-fixture/context?fragment=true&sceneId='+id});await route.fulfill({response}); - }); - await page.goto(base+'/writing-desk-fixture/context'); - await page.evaluate(theme=>{ - document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light'; - const root=document.querySelector('main');root.dataset.writingContext='';root.dataset.contextUrl='/Writing/Context/Scene';root.dataset.scopeProjectId='7';root.dataset.scopeBookId='12'; - const host=document.createElement('section');host.dataset.writingContextContent='';while(root.firstChild)host.append(root.firstChild);root.append(host); - const status=document.createElement('p');status.dataset.writingContextStatusText='';root.prepend(status);const input=document.createElement('input');input.type='hidden';input.name='__RequestVerificationToken';input.value='fixture';root.append(input);window.originalWritingShell=root;window.focusCalls=0;window.focus=()=>focusCalls++; - },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.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]'))); - await page.click('[data-writing-scene-step="22"]');await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='22');await page.waitForTimeout(30);assert.equal(commands,2); - const beat=async id=>page.evaluate(id=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{instanceId:'instance',sessionId:'document',bookId:12,chapterId:id===23?11:10,sceneId:id,active:true,wordAvailable:true,wordSaved:true,expires:new Date(Date.now()+45000).toISOString()}]})),id); - await page.evaluate(()=>{const spacer=document.createElement('div');spacer.style.height='1400px';document.body.append(spacer);window.scrollTo(0,150);});await page.waitForFunction(()=>Math.abs(scrollY-150)<=2); - 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.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(); - } - console.log('PASS actual Razor fragments, stable shell, cross-chapter Previous/Next and jump, tab persistence, Word follow without feedback, disconnect/reconnect and full-page response rejection at three widths in four themes'); -}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); diff --git a/PlotLine.Tests/Browser/writing-context-scale.cjs b/PlotLine.Tests/Browser/writing-context-scale.cjs deleted file mode 100644 index 30879e82..00000000 --- a/PlotLine.Tests/Browser/writing-context-scale.cjs +++ /dev/null @@ -1,11 +0,0 @@ -const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path'); -(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage({viewport:{width:1440,height:950}}),base='http://127.0.0.1:5238';let reads=0; - await page.route('**/Writing/Context/PlotLines?*',async r=>{reads++;await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/plots?large=true'})});}); - await page.route('**/Writing/Context/Scene?*',async r=>r.fulfill({response:await r.fetch({url:base+'/writing-desk-fixture/context?fragment=true&large=true&sceneId='+new URL(r.request().url()).searchParams.get('sceneId')})})); - await page.goto(base+'/writing-desk-fixture/context?large=true');await page.evaluate(()=>{const root=document.querySelector('main');root.dataset.writingContext='';root.dataset.contextUrl='/Writing/Context/Scene';root.dataset.scopeProjectId='7';root.dataset.scopeBookId='12';const host=document.createElement('section');host.dataset.writingContextContent='';while(root.firstChild)host.append(root.firstChild);root.append(host);}); - for(const script of ['story-position','writing-follow','writing-context-plots','writing-context-components','writing-context'])await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/'+script+'.js')}); - const began=Date.now();await page.click('[data-writing-context-tab=plots]');await page.waitForSelector('[data-writing-component=plots][data-loaded=true]');const load=Date.now()-began;assert.ok(await page.locator('[data-plot-scene-strip] button').count()<=7);assert.equal(await page.locator('[data-plot-line]').count(),10);assert.equal(await page.locator('[data-context-chart-scene]').count(),0);await page.evaluate(()=>window.originalPlot=document.querySelector('[data-writing-component=plots]')); - const changes=Date.now();for(const scene of [100,200,300,421]){await page.evaluate(scene=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{instanceId:'large',sessionId:'large',bookId:12,chapterId:10+Math.floor((scene-22)/8),sceneId:scene,active:true,wordAvailable:true,wordSaved:true,expires:new Date(Date.now()+45000).toISOString()}]})),scene);await page.waitForFunction(scene=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId===String(scene),scene);} - assert.equal(reads,1);assert.ok(await page.evaluate(()=>originalPlot===document.querySelector('[data-writing-component=plots]')));assert.equal(await page.locator('[data-plot-scene="399"]').getAttribute('aria-current'),'location');assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false); - console.log(`PASS 400-scene, 10-line actual Razor browser fixture: initial chart ${load}ms; four scene changes ${Date.now()-changes}ms; one chart read, retained panel/compact scene strip and no page overflow. Chromium fixture measurements only, not Word performance.`); -}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); diff --git a/PlotLine.Tests/Browser/writing-context-shell.cjs b/PlotLine.Tests/Browser/writing-context-shell.cjs deleted file mode 100644 index c5c44af1..00000000 --- a/PlotLine.Tests/Browser/writing-context-shell.cjs +++ /dev/null @@ -1,22 +0,0 @@ -const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); -const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; -(async()=>{const browser=await chromium.launch();try{ - for(const embedded of [false,true])for(const installed of [false,true]){ - const page=await browser.newPage({viewport:{width:1280,height:900}});await page.addInitScript(installed=>{if(installed){const match=window.matchMedia.bind(window);window.matchMedia=query=>query==='(display-mode: standalone)'?{matches:true,media:query,addEventListener(){},removeEventListener(){},addListener(){},removeListener(){}}:match(query);}},installed); - let snapshotRevision=1,syncFailure=false,syncRequests=0,repairRequests=0,modern=false,transferState='pending'; - await page.route('**/manuscript/paragraphs/snapshot',async r=>{syncRequests++;const body=new URLSearchParams(r.request().postData());assert.equal(body.get('bookId'),'12');assert.equal(body.get('instanceId'),'fixture');assert.equal(body.get('sessionId'),'doc');assert.ok(body.get('__RequestVerificationToken'));await r.fulfill({status:syncFailure?409:200,json:{requestId:'11111111-1111-4111-8111-111111111111',message:syncFailure?'Word is unavailable; saved snapshot preserved.':'Word snapshot requested; awaiting acceptance.'}});}); - await page.route('**/manuscript/paragraphs/repair',async r=>{repairRequests++;assert.equal(new URLSearchParams(r.request().postData()).get('bookId'),'12');await r.fulfill({json:{requestId:'22222222-2222-4222-8222-222222222222',message:'Chapter repair requested.'}});}); - await page.route('**/native-companion/status',r=>r.fulfill({json:[{instanceId:'fixture',sessionId:'doc',bookId:12,chapterId:10,sceneId:22,active:true,wordAvailable:true,wordSaved:true,canParagraphSync:true,canChapterSync:modern,snapshotRevision,mappingCurrent:true,paragraphTransfer:repairRequests?{requestId:'22222222-2222-4222-8222-222222222222',state:transferState,kind:'chapter',message:'Chapter repair '+transferState}:syncRequests?{requestId:'11111111-1111-4111-8111-111111111111',state:transferState}:null,documentTitle:'Synthetic manuscript.docx',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}]})); - await page.route('**/Writing/Context/Scene?*',async r=>r.fulfill({response:await r.fetch({url:base+'/writing-desk-fixture/context?fragment=true&sceneId='+new URL(r.request().url()).searchParams.get('sceneId')})})); - await page.route(/\/Writing\/Context\/(PlotLines|Metrics|Map)\?/,async r=>{const url=new URL(r.request().url()),kind=url.pathname.endsWith('PlotLines')?'plots':url.pathname.endsWith('Metrics')?'metrics':'map';await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/'+kind+url.search})});}); - const response=await page.goto(base+'/Writing/Context?bookId=12'+(embedded?'&embedded=true':''));assert.equal(response.status(),200); - await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('#native-companion-status').count(),1);await page.click('#native-companion-status');assert.ok(await page.locator('#writing-connection-details').isVisible());assert.ok(await page.getByRole('option',{name:'Synthetic manuscript.docx · active in Word'}).count());await page.locator('[data-word-sync-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('requested'));assert.equal(syncRequests,1);assert.ok(await page.locator('[data-word-sync-button]').isDisabled(),'request is not completion');snapshotRevision=2;await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForTimeout(100);assert.ok(!(await page.locator('[data-word-sync-feedback]').textContent()).includes('accepted'),'an unrelated revision is not snapshot acceptance');transferState='accepted';await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('accepted'));assert.ok(await page.locator('[data-word-sync-button]').isEnabled());syncFailure=true;await page.locator('[data-word-sync-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('unavailable'));assert.equal(syncRequests,2);assert.ok(await page.locator('[data-word-repair-button]').isDisabled(),'legacy add-in must not receive chapter commands');modern=true;transferState='pending';await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>!document.querySelector('[data-word-repair-button]').disabled);await page.locator('[data-word-repair-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('repair pending'));assert.equal(repairRequests,1);transferState='accepted';await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('repair accepted'));assert.equal(snapshotRevision,2,'metadata-only chapter acceptance does not need a new global prose revision');await page.click('[data-close-word-details]'); - await page.click('[data-writing-context-tab=people]');await page.selectOption('[data-writing-context-scene-select]','23');await page.waitForSelector('[data-writing-context-fragment][data-scene-id="23"]');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.equal(await page.locator('iframe').count(),0); - await page.click('#native-companion-status');await page.click('[data-word-return-to-current]');await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible()); - if(embedded)assert.equal(await page.locator('.pd-application-header').count(),0,'dedicated workspace has no normal ribbon'); - await page.evaluate(()=>window.dispatchEvent(new StorageEvent('storage',{key:'plotdirector.applicationTheme',newValue:'warm-dark'})));await page.waitForFunction(()=>document.documentElement.dataset.appTheme==='warm-dark'&&document.documentElement.dataset.bsTheme==='dark'); - if(process.env.PD_SCREENSHOT_DIR&&embedded&&!installed){fs.mkdirSync(process.env.PD_SCREENSHOT_DIR,{recursive:true});for(const tab of ['plots','metrics','maps']){await page.click('[data-writing-context-tab='+tab+']');await page.waitForFunction(tab=>document.querySelector('[data-writing-context-panel='+tab+'] [data-writing-component]').dataset.loaded==='true',tab);await page.screenshot({path:process.env.PD_SCREENSHOT_DIR+'/'+tab+'-warm-dark.png',fullPage:true});}} - await page.close(); - } - console.log('PASS full compiled Context page, compact connection dialog/document selection, live native event path, fragment navigation and People tab in browser/PWA and dedicated-window layouts; no iframe'); -}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); diff --git a/PlotLine.Tests/Browser/writing-desks.cjs b/PlotLine.Tests/Browser/writing-desks.cjs deleted file mode 100644 index d5c7d559..00000000 --- a/PlotLine.Tests/Browser/writing-desks.cjs +++ /dev/null @@ -1,2 +0,0 @@ -const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('path'); -(async()=>{const browser=await chromium.launch();try{for(const role of ['context','intent'])for(const width of [400,760,1440])for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']){const page=await browser.newPage({viewport:{width,height:1000}});const response=await page.goto(`http://127.0.0.1:5238/writing-desk-fixture/${role}`);assert.equal(response.status(),200);await page.evaluate(({role,theme})=>{document.documentElement.setAttribute('data-app-theme',theme);document.documentElement.setAttribute('data-theme',theme.endsWith('dark')?'dark':'light');const main=document.querySelector('main');main.setAttribute('data-writing-'+role,'');main.dataset.followMode='snapshot';const wrap=document.createElement('div');wrap.setAttribute('data-writing-'+role+'-content','');while(main.firstChild)wrap.append(main.firstChild);main.append(wrap);},{role,theme});await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/writing-follow.js')});await page.addScriptTag({path:path.resolve(__dirname,`../../PlotLine/wwwroot/js/writing-${role}.js`)});assert.ok(await page.getByText('A deliberately long scene title for a narrow reference screen',{exact:true}).count());assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`${role} overflow ${width} ${theme}`);if(role==='context'){assert.ok(await page.getByText('People at this point',{exact:true}).isVisible());assert.ok(await page.getByText('No participants saved for this scene.',{exact:true}).isVisible());await page.click('[data-writing-context-tab="place"]');assert.equal(await page.locator('[data-writing-context-panel="place"]').isVisible(),true);}else{await page.click('[data-writing-intent-tab="evidence"]');assert.equal(await page.locator('[data-intent-assessment]').isVisible(),true);assert.ok(await page.getByText('Edit intentions and objective completion',{exact:true}).isVisible());}await page.close();}const empty=await browser.newPage();await empty.goto('http://127.0.0.1:5238/writing-desk-fixture/context?empty=true');assert.ok(await empty.getByText('No current Word scene',{exact:true}).isVisible());const evidence=await browser.newPage();await evidence.goto('http://127.0.0.1:5238/writing-desk-fixture/evidence');assert.ok(await evidence.getByText('Evidence matches the saved prose and plan.',{exact:false}).isVisible());assert.equal(await evidence.locator('[data-intent-decision]').count(),4);await evidence.goto('http://127.0.0.1:5238/writing-desk-fixture/evidence?stale=true');assert.ok(await evidence.getByText('Out of date',{exact:false}).isVisible());assert.equal(await evidence.locator('[data-intent-decision]').count(),0,'stale suggestions cannot be decided');console.log('PASS actual Context/Intent Razor, tab navigation, missing metadata, objective edit link, 400/760/1440 layouts and four light/dark/warm themes');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 757024df..daa9bd20 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -543,40 +543,24 @@ var tests = new (string Name, Action Test)[] ("Whole-book Plot Intelligence production code remains fixture agnostic", WholeBookPlotIntelligenceProductionCodeRemainsFixtureAgnostic), ("Story Intelligence narrative review creates canonical records via existing procs", StoryIntelligenceNarrativeReviewCreatesCanonicalRecordsViaExistingProcs), ("Story Intelligence narrative stage follows knowledge", StoryIntelligenceNarrativeStageFollowsKnowledge), - ("Word Companion replays live current scene to writing panes", WordCompanionReplaysLiveCurrentSceneToWritingPanes), ("Scan review post supports full-book form submissions", ScanReviewPostSupportsFullBookFormSubmissions), ("StoryPosition rejects incomplete or invalid runtime scene positions", StoryPositionRejectsInvalidRuntimeScenePositions), ("StoryPosition builds canonical runtime scene navigation", StoryPositionBuildsCanonicalRuntimeSceneNavigation), ("StoryPosition derives canonical scene context identity", StoryPositionDerivesCanonicalSceneContextIdentity), ("Writing Context route uses canonical story context service", WritingContextRouteUsesCanonicalStoryContextService), - ("Writing Context client follows canonical story position events", WritingContextClientFollowsCanonicalStoryPositionEvents), - ("Writing Context preserves selected tab and avoids event loops", WritingContextPreservesSelectedTabAndAvoidsEventLoops), - ("Writing Intent route uses canonical story context and planning data", WritingIntentRouteUsesCanonicalStoryContextAndPlanningData), - ("Writing Intent client uses shared writing follow helper", WritingIntentClientUsesSharedWritingFollowHelper), - ("Obsolete global Word navigation is removed while writing windows remain live", GlobalWordNavigationIsRemoved), ("Appearance preferences and ribbon destinations", AppearanceTests.RegistryAndPersistence), ("Toolbar preferences, authorisation and contextual routes", ToolbarTests.PreferencesAndRoutes), ("Application navigation resolves authorised project and book context", ApplicationNavigationTests.ContextAndPermissions), - ("Writing pair shares canonical follow infrastructure", WritingPairSharesCanonicalFollowInfrastructure), ("Writing Context and Intent resolve native sessions, preserve decisions and reuse bounded chronological data", () => WritingIntegrationTests.Run().GetAwaiter().GetResult()), ("Writing Context Plot Lines preserves canonical associations, developments and book access", () => WritingContextPlotLinesTests.Run().GetAwaiter().GetResult()), - ("Writing workspace presence scopes browser windows", WritingWorkspacePresenceScopesBrowserWindows), - ("Writing workspace client uses session window identity and stable names", WritingWorkspaceClientUsesSessionIdentityAndStableNames), - ("Writing workspace launcher uses progressive screen placement", WritingWorkspaceLauncherUsesProgressiveScreenPlacement), - ("Writing workspace pages register roles without changing follow behavior", WritingWorkspacePagesRegisterRolesWithoutChangingFollowBehavior), ("Word marker client acknowledgements require authenticated ownership", WordMarkerSecurityTests.HubChecks), ("Word Companion exposes writing workspace launch actions", WordCompanionExposesWritingWorkspaceLaunchActions), - ("Word Companion writing screens receive resolved context identifiers", WordCompanionWritingScreensReceiveResolvedContextIdentifiers), ("Word Companion canonical markers drive runtime follow", WordCompanionCanonicalMarkersDriveRuntimeFollow), ("Word Companion runtime follows multiple imported scene anchors", WordCompanionRuntimeFollowsMultipleImportedSceneAnchors), ("Word Companion existing project book linking remains available", WordCompanionExistingProjectBookLinkingRemainsAvailable), ("Word Companion document identity survives reconnect", WordCompanionDocumentIdentitySurvivesReconnect), - ("Word Companion multiscreen launch and follow remain reachable", WordCompanionMultiscreenLaunchAndFollowRemainReachable), ("Word Companion modes remain distinct", WordCompanionModesRemainDistinct), - ("Writing pages do not require Story Intelligence", WritingPagesDoNotRequireStoryIntelligence), ("Word Companion host script has valid tab mapping", WordCompanionHostScriptHasValidTabMapping), - ("Writing screens show diagnostic empty states", WritingScreensShowDiagnosticEmptyStates), - ("Word Companion three-screen flow logs connection identifiers", WordCompanionThreeScreenFlowLogsConnectionIdentifiers), ("Admin Story Intelligence reset returns to diagnostics with messages", AdminStoryIntelligenceResetReturnsToDiagnosticsWithMessages), ("Project hard delete clears Story Intelligence dependencies in transaction", ProjectHardDeleteClearsStoryIntelligenceDependenciesInTransaction), ("Permanent project delete keeps archive and name safety gates", PermanentProjectDeleteKeepsArchiveAndNameSafetyGates), @@ -2006,245 +1990,22 @@ static void WritingContextRouteUsesCanonicalStoryContextService() Assert(controller.Contains("[Route(\"Writing\")", StringComparison.Ordinal), "Writing Context controller should expose the /Writing route prefix."); Assert(controller.Contains("[HttpGet(\"Context\")", StringComparison.Ordinal), "Writing Context shell route is missing."); - Assert(controller.Contains("[HttpGet(\"Context/Scene\")", StringComparison.Ordinal), "Writing Context partial route is missing."); + Assert(controller.Contains("[HttpGet(\"Context/Tabs/overview\")", StringComparison.Ordinal), "Writing Context partial route is missing."); Assert(controller.Contains("IStoryContextService storyContext", StringComparison.Ordinal), "Writing Context must consume IStoryContextService."); Assert(controller.Contains("storyContext.GetForSceneAsync", StringComparison.Ordinal), "Writing Context scene requests must load canonical story context."); Assert(!controller.Contains("ISceneService", StringComparison.Ordinal), "Writing Context should not bypass canonical story context with ISceneService."); Assert(viewModel.Contains("StoryContextViewModel? Context", StringComparison.Ordinal), "Writing Context display model should carry canonical story context."); } -static void WritingContextClientFollowsCanonicalStoryPositionEvents() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - var initializer = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-context.js")); - var view = File.ReadAllText(Path.Combine(root, "Views/Writing/Context.cshtml")); - Assert(view.Contains("data-writing-context", StringComparison.Ordinal), "Writing Context shell should expose a stable script root."); - Assert(view.Contains("data-writing-mode=\"context\"", StringComparison.Ordinal), "Writing Context should identify itself as a writing-mode page."); - Assert(view.Contains("~/js/writing-follow.js", StringComparison.Ordinal), "Writing Context should load the shared writing follow helper."); - Assert(initializer.Contains("window.PlotDirectorWritingFollow?.initialize", StringComparison.Ordinal), "Writing Context should initialize the shared writing follow helper."); - Assert(script.Contains("window.PlotDirectorStoryPosition?.eventName", StringComparison.Ordinal), "Writing Context must subscribe to canonical browser story-position events."); - Assert(script.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "Writing Context must bridge SignalR story-position events."); - Assert(script.Contains("fetch(url", StringComparison.Ordinal), "Writing Context should refresh context content without full page navigation."); - Assert(initializer.Contains("[data-writing-context-scene-select]", StringComparison.Ordinal), "Writing Context manual fallback selector should be wired."); - Assert(script.Contains("publishChanged", StringComparison.Ordinal), "Manual scene selection should publish canonical story-position changes."); -} -static void WritingContextPreservesSelectedTabAndAvoidsEventLoops() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - var initializer = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-context.js")); - Assert(initializer.Contains("plotdirector.writingContext.activeTab", StringComparison.Ordinal), "Writing Context should remember the selected tab."); - Assert(script.Contains("activateTab(tab)", StringComparison.Ordinal), "Writing Context should restore the selected tab after content refresh."); - Assert(script.Contains("position.sceneId === currentSceneId", StringComparison.Ordinal), "Writing Context should ignore duplicate current-scene events."); - Assert(script.Contains("position.sceneId === loadingSceneId", StringComparison.Ordinal), "Writing Context should ignore duplicate in-flight scene events."); - Assert(!script.Contains("window.location.assign", StringComparison.Ordinal) && !script.Contains("window.location.href", StringComparison.Ordinal), "Writing Context must not navigate away when Word changes scene."); -} -static void WritingIntentRouteUsesCanonicalStoryContextAndPlanningData() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var controller = File.ReadAllText(Path.Combine(root, "Controllers/WritingController.cs")); - var viewModel = File.ReadAllText(Path.Combine(root, "ViewModels/CoreViewModels.cs")); - var contentView = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingIntentContent.cshtml")); - Assert(controller.Contains("[HttpGet(\"Intent\")", StringComparison.Ordinal), "Writing Intent shell route is missing."); - Assert(controller.Contains("[HttpGet(\"Intent/Scene\")", StringComparison.Ordinal), "Writing Intent partial route is missing."); - Assert(controller.Contains("IStoryContextService storyContext", StringComparison.Ordinal), "Writing Intent must share canonical story context service injection."); - Assert(controller.Contains("storyContext.GetForSceneAsync", StringComparison.Ordinal), "Writing Intent scene requests must use canonical story context."); - Assert(controller.Contains("IWriterWorkspaceService writerWorkspace", StringComparison.Ordinal), "Writing Intent should reuse existing writer planning data."); - Assert(controller.Contains("writerWorkspace.GetChapterWorkflowAsync", StringComparison.Ordinal), "Writing Intent should load chapter workflow planning data."); - Assert(controller.Contains("projectId.HasValue && chapterWorkflow.Project.ProjectID != projectId.Value", StringComparison.Ordinal), "Writing Intent should reject mismatched project scope."); - Assert(controller.Contains("bookId.HasValue && chapterWorkflow.Book.BookID != bookId.Value", StringComparison.Ordinal), "Writing Intent should reject mismatched book scope."); - Assert(viewModel.Contains("public sealed class WritingIntentDisplayViewModel", StringComparison.Ordinal), "Writing Intent display model is missing."); - Assert(viewModel.Contains("StoryContextViewModel? Context", StringComparison.Ordinal), "Writing Intent display should carry canonical story context."); - Assert(viewModel.Contains("ChapterWorkflowViewModel? ChapterWorkflow", StringComparison.Ordinal), "Writing Intent display should carry chapter planning workflow."); - Assert(contentView.Contains("No current scene. Showing chapter intent.", StringComparison.Ordinal), "Writing Intent should support chapter-only fallback."); - Assert(contentView.Contains("No scene-specific plan. Showing chapter intent.", StringComparison.Ordinal), "Writing Intent should prefer chapter intent when scene planning is sparse."); -} -static void WritingIntentClientUsesSharedWritingFollowHelper() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var helper = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - var initializer = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-intent.js")); - var view = File.ReadAllText(Path.Combine(root, "Views/Writing/Intent.cshtml")); - var contentView = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingIntentContent.cshtml")); - Assert(view.Contains("data-writing-intent", StringComparison.Ordinal), "Writing Intent shell should expose a stable script root."); - Assert(view.Contains("data-writing-mode=\"intent\"", StringComparison.Ordinal), "Writing Intent should identify itself as a writing-mode page."); - Assert(view.Contains("~/js/writing-follow.js", StringComparison.Ordinal), "Writing Intent should load the shared writing follow helper."); - Assert(initializer.Contains("window.PlotDirectorWritingFollow?.initialize", StringComparison.Ordinal), "Writing Intent should initialize the shared helper."); - Assert(initializer.Contains("plotdirector.writingIntent.activeTab", StringComparison.Ordinal), "Writing Intent should remember the selected tab."); - Assert(initializer.Contains("defaultEndpoint: \"/Writing/Intent/Scene\"", StringComparison.Ordinal), "Writing Intent should refresh from its partial route."); - Assert(initializer.Contains("allowChapterOnly: true", StringComparison.Ordinal), "Writing Intent should accept canonical chapter-only positions."); - Assert(helper.Contains("window.PlotDirectorStoryPosition?.eventName", StringComparison.Ordinal), "Writing Intent should receive canonical story-position events through the shared helper."); - Assert(helper.Contains("fetch(url", StringComparison.Ordinal), "Writing Intent should update in place."); - Assert(helper.Contains("position.sceneId === currentSceneId", StringComparison.Ordinal), "Writing Intent should ignore duplicate current-scene events."); - Assert(helper.Contains("position.sceneId === loadingSceneId", StringComparison.Ordinal), "Writing Intent should ignore duplicate in-flight events."); - Assert(helper.Contains("position.bookId && position.bookId !== scopedBookId", StringComparison.Ordinal), "Writing Intent should ignore unrelated scoped book events."); - Assert(helper.Contains("publishChanged", StringComparison.Ordinal), "Writing Intent manual fallback should publish canonical story-position changes."); - Assert(contentView.Contains("data-writing-intent-scene-select", StringComparison.Ordinal), "Writing Intent manual scene selector should be wired."); - Assert(contentView.Contains("data-writing-intent-chapter-select", StringComparison.Ordinal), "Writing Intent manual chapter selector should be wired."); - Assert(!helper.Contains("window.location.assign", StringComparison.Ordinal) && !helper.Contains("window.location.href", StringComparison.Ordinal), "Writing Intent must not navigate away when Word changes scene."); -} -static void GlobalWordNavigationIsRemoved() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var site = File.ReadAllText(Path.Combine(root, "wwwroot/js/site.js")); - var controller = File.ReadAllText(Path.Combine(root, "Controllers/WordCompanionController.cs")); - var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - Assert(!site.Contains("plotdirector.followWordCompanion", StringComparison.Ordinal), "Obsolete persisted global-follow preference must not control the browser."); - Assert(!site.Contains("data-word-companion-follow-toggle", StringComparison.Ordinal), "Obsolete global-follow toggle handler must be removed."); - Assert(!controller.Contains("wordCompanionSceneChanged", StringComparison.Ordinal) && !controller.Contains("wordCompanionCharactersCreated", StringComparison.Ordinal), "Broadcasts used only by global navigation must be removed."); - Assert(site.Contains("window.PlotDirectorStoryPosition", StringComparison.Ordinal), "Shared position event helper must remain for writing windows."); - var workspace = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-workspace.js")); - Assert(workspace.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "The workspace launcher must retain its live canonical-position feed without global follow."); - Assert(controller.Contains("BroadcastToCurrentUserAsync(\"storyPositionChanged\"", StringComparison.Ordinal), "Current scene API must still notify the writing windows."); - Assert(follow.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "Writing windows must still receive canonical positions directly."); -} -static void WritingPairSharesCanonicalFollowInfrastructure() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var context = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-context.js")); - var intent = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-intent.js")); - var helper = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - - Assert(context.Contains("source: \"WritingContext\"", StringComparison.Ordinal), "Writing Context should identify its canonical event source."); - Assert(intent.Contains("source: \"WritingIntent\"", StringComparison.Ordinal), "Writing Intent should identify its canonical event source."); - Assert(context.Contains("window.PlotDirectorWritingFollow?.initialize", StringComparison.Ordinal), "Writing Context should use shared follow initialization."); - Assert(intent.Contains("window.PlotDirectorWritingFollow?.initialize", StringComparison.Ordinal), "Writing Intent should use shared follow initialization."); - Assert(helper.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "The shared helper should bridge Word story-position events for both pages."); - Assert(helper.Contains("document.addEventListener(window.PlotDirectorStoryPosition?.eventName", StringComparison.Ordinal), "Both pages should react to the same canonical browser event."); -} - -static void WritingWorkspacePresenceScopesBrowserWindows() -{ - var service = new WritingWorkspacePresenceService(); - var word = new WordCompanionPresenceStatus - { - UserID = 9, - IsConnected = true, - DocumentOpen = true, - LinkedProjectID = 10, - LinkedBookID = 20 - }; - - service.RegisterAsync(9, "launcher-1", new WritingWindowRegistration - { - BrowserWindowID = "launcher", - ProjectID = 10, - BookID = 20, - WritingRole = WritingWorkspaceRoles.Launcher, - CurrentRoute = "/Writer" - }, word).GetAwaiter().GetResult(); - service.RegisterAsync(9, "context-1", new WritingWindowRegistration - { - BrowserWindowID = "context", - ProjectID = 10, - BookID = 20, - WritingRole = WritingWorkspaceRoles.Context, - CurrentRoute = "/Writing/Context" - }, word).GetAwaiter().GetResult(); - service.RegisterAsync(9, "intent-1", new WritingWindowRegistration - { - BrowserWindowID = "intent", - ProjectID = 10, - BookID = 20, - WritingRole = WritingWorkspaceRoles.Intent, - CurrentRoute = "/Writing/Intent" - }, word).GetAwaiter().GetResult(); - service.RegisterAsync(9, "other-context", new WritingWindowRegistration - { - BrowserWindowID = "other-context", - ProjectID = 10, - BookID = 21, - WritingRole = WritingWorkspaceRoles.Context, - CurrentRoute = "/Writing/Context" - }, word).GetAwaiter().GetResult(); - - var status = service.GetStatusAsync(9, new WritingWorkspaceScope { ProjectID = 10, BookID = 20 }, word).GetAwaiter().GetResult(); - Assert(status.WordCompanionConnected && status.WordDocumentOpen, "Writing workspace should include Word Companion presence."); - Assert(status.ContextOpen && status.IntentOpen, "Matching Context and Intent windows should be open."); - Assert(status.Context?.BrowserWindowID == "context", "Workspace status should choose the matching book's Context window."); - Assert(status.Windows.All(window => window.BookID == 20), "Workspace status should not include another book's windows."); - - service.DisconnectAsync("context-1", word).GetAwaiter().GetResult(); - status = service.GetStatusAsync(9, new WritingWorkspaceScope { ProjectID = 10, BookID = 20 }, word).GetAwaiter().GetResult(); - Assert(!status.ContextOpen && status.IntentOpen, "Disconnected Context should be removed without affecting Intent."); -} - -static void WritingWorkspaceClientUsesSessionIdentityAndStableNames() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-workspace.js")); - var service = File.ReadAllText(Path.Combine(root, "Services/WritingWorkspacePresenceService.cs")); - - Assert(script.Contains("sessionStorage.getItem(storageKeys.windowId)", StringComparison.Ordinal), "Browser window IDs must come from sessionStorage."); - Assert(script.Contains("sessionStorage.setItem(storageKeys.windowId", StringComparison.Ordinal), "Browser window IDs must be stored per tab/window."); - Assert(!script.Contains("localStorage.getItem(storageKeys.windowId)", StringComparison.Ordinal), "Browser window IDs must not be shared through localStorage."); - Assert(script.Contains("PlotDirector${role}", StringComparison.Ordinal), "Context and Intent windows should use stable named targets."); - Assert(script.Contains("url.searchParams.set(\"bookId\", bookId)", StringComparison.Ordinal), "Workspace URLs retain book scope while one named window is reused per role."); - Assert(script.Contains("windowRefs = new Map()", StringComparison.Ordinal), "Launcher-created window references should be retained for focus."); - Assert(script.Contains("RequestWritingWindowFocus", StringComparison.Ordinal), "Launcher should fall back to SignalR focus requests."); - Assert(script.Contains("connection.onreconnected", StringComparison.Ordinal), "Writing workspace windows should re-register after SignalR reconnect."); - Assert(service.Contains("ActiveTimeout = TimeSpan.FromSeconds(45)", StringComparison.Ordinal) && service.Contains("MarkStaleOfflineAsync", StringComparison.Ordinal), "Writing workspace presence should expire stale windows."); -} - -static void WritingWorkspaceLauncherUsesProgressiveScreenPlacement() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-workspace.js")); - var launcher = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-workspace-launcher.js")); - var view = File.ReadAllText(Path.Combine(root, "Views/Writer/Legacy.cshtml")); - - Assert(script.Contains("getScreenDetails", StringComparison.Ordinal), "Workspace launcher should use the Window Management API when available."); - Assert(script.Contains("window-management", StringComparison.Ordinal), "Workspace launcher should check/request window-management permission."); - Assert(script.Contains("sort((a, b) => a.left - b.left", StringComparison.Ordinal), "Screen topology should be derived from physical coordinates."); - Assert(script.Contains("mode: \"three-screen\"", StringComparison.Ordinal), "Three-screen layout decision is missing."); - Assert(script.Contains("key: `screen-${index}`", StringComparison.Ordinal), "Detected displays should receive stable option keys."); - Assert(script.Contains("displayByPreference", StringComparison.Ordinal), "Launcher should resolve logical and physical display preferences."); - Assert(script.Contains("preferences.contextDisplay", StringComparison.Ordinal), "Context display preference is missing."); - Assert(script.Contains("preferences.intentDisplay", StringComparison.Ordinal), "Intent display preference is missing."); - Assert(script.Contains("mode: \"two-screen\"", StringComparison.Ordinal), "Two-screen fallback is missing."); - Assert(script.Contains("mode: \"single-screen\"", StringComparison.Ordinal), "One-screen fallback is missing."); - Assert(script.Contains("localStorage.setItem(storageKeys.preferences", StringComparison.Ordinal), "Remembered layout preferences are missing."); - Assert(script.Contains("window.open(url, name, popupFeatures(display))", StringComparison.Ordinal), "Writing windows should be opened from explicit launcher clicks with placement features."); - Assert(script.Contains("window.open(buildWritingUrl(role, scope), stableWindowName(role, scope), popupFeatures(display))", StringComparison.Ordinal), "Focus actions should open missing windows on the selected display."); - Assert(script.Contains("getScreenLayout(Boolean(options.requestScreens), options.displayPreferences || {})", StringComparison.Ordinal), "Start action should pass selected display preferences into layout detection."); - Assert(script.Contains("openRoleWindow(roles.intent, resolvedScope, layout.intentDisplay)", StringComparison.Ordinal), "Start should open Intent on the selected display instead of converting the launcher window."); - Assert(!script.Contains("window.location.assign(buildWritingUrl(roles.intent", StringComparison.Ordinal), "Start should leave the launcher visible while opening the selected writing windows."); - Assert(launcher.Contains("requestScreens: true", StringComparison.Ordinal), "Screen permission should be requested from the Start action."); - Assert(launcher.Contains("workspace.getScreenLayout(true, selectedDisplayPreferences())", StringComparison.Ordinal), "Detect displays action should request physical display details."); - Assert(launcher.Contains("workspace.focusRole(role, scope, targetDisplay)", StringComparison.Ordinal), "Direct open/focus actions should use the selected display."); - Assert(view.Contains("data-start-writing-workspace", StringComparison.Ordinal), "Writer dashboard launcher start button is missing."); - Assert(view.Contains("data-writing-context-display", StringComparison.Ordinal), "Context display selector is missing."); - Assert(view.Contains("data-writing-intent-display", StringComparison.Ordinal), "Intent display selector is missing."); - Assert(view.Contains("data-detect-writing-displays", StringComparison.Ordinal), "Detect displays button is missing."); - Assert(view.Contains("data-focus-writing-context", StringComparison.Ordinal), "Focus Context action is missing."); - Assert(view.Contains("data-focus-writing-intent", StringComparison.Ordinal), "Focus Intent action is missing."); -} - -static void WritingWorkspacePagesRegisterRolesWithoutChangingFollowBehavior() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var contextView = File.ReadAllText(Path.Combine(root, "Views/Writing/Context.cshtml")); - var intentView = File.ReadAllText(Path.Combine(root, "Views/Writing/Intent.cshtml")); - var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - - Assert(contextView.Contains("writingRole: window.PlotDirectorWritingWorkspace.roles.context", StringComparison.Ordinal), "Writing Context should register its workspace role."); - Assert(intentView.Contains("writingRole: window.PlotDirectorWritingWorkspace.roles.intent", StringComparison.Ordinal), "Writing Intent should register its workspace role."); - Assert(contextView.Contains("data-writing-mode=\"context\"", StringComparison.Ordinal), "Writing Context should remain a writing-mode page."); - Assert(intentView.Contains("data-writing-mode=\"intent\"", StringComparison.Ordinal), "Writing Intent should remain a writing-mode page."); - Assert(follow.Contains("registerWorkspaceRole", StringComparison.Ordinal), "Writing follow should refresh presence scope after Word updates."); - Assert(follow.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "Existing canonical Word follow should remain."); - Assert(!follow.Contains("window.location.assign", StringComparison.Ordinal) && !follow.Contains("window.location.href", StringComparison.Ordinal), "Writing pages must still update in place without navigation."); -} static void WordCompanionExposesWritingWorkspaceLaunchActions() { @@ -2254,31 +2015,13 @@ static void WordCompanionExposesWritingWorkspaceLaunchActions() Assert(view.Contains("data-open-writing-workspace", StringComparison.Ordinal), "Word Companion should expose Open Workspace."); Assert(view.Contains("data-open-writing-context", StringComparison.Ordinal), "Word Companion should expose Open Context."); - Assert(view.Contains("data-open-writing-intent", StringComparison.Ordinal), "Word Companion should expose Open Intent."); - Assert(script.Contains("writingWindowName", StringComparison.Ordinal), "Word Companion should use stable writing window names."); - Assert(script.Contains("PlotDirector${role}_${suffix}", StringComparison.Ordinal), "Word Companion writing window names should be scoped."); + Assert(!view.Contains("data-open-writing-intent", StringComparison.Ordinal), "Standalone Intent launcher is retired."); + Assert(script.Contains("window.open(url, \"_blank\")", StringComparison.Ordinal), "Word Companion opens independent Context windows."); Assert(script.Contains("openWritingWorkspaceButton?.addEventListener", StringComparison.Ordinal), "Word Companion Open Workspace button should be wired."); Assert(script.Contains("openWritingContextButton?.addEventListener", StringComparison.Ordinal), "Word Companion Open Context button should be wired."); - Assert(script.Contains("openWritingIntentButton?.addEventListener", StringComparison.Ordinal), "Word Companion Open Intent button should be wired."); + Assert(!script.Contains("openWritingIntentButton?.addEventListener", StringComparison.Ordinal), "Standalone Intent listener is retired."); } -static void WordCompanionWritingScreensReceiveResolvedContextIdentifiers() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/word-companion-host.js")); - var controller = File.ReadAllText(Path.Combine(root, "Controllers/WritingController.cs")); - var contextView = File.ReadAllText(Path.Combine(root, "Views/Writing/Context.cshtml")); - var intentView = File.ReadAllText(Path.Combine(root, "Views/Writing/Intent.cshtml")); - - Assert(script.Contains("const chapterId = Number.isInteger(resolvedChapterId)", StringComparison.Ordinal), "Word Companion should prefer resolved chapter IDs for writing screen URLs."); - Assert(script.Contains("const sceneId = Number.isInteger(resolvedSceneId)", StringComparison.Ordinal), "Word Companion should prefer resolved scene IDs for writing screen URLs."); - Assert(script.Contains("url.searchParams.set(\"chapterId\", chapterId)", StringComparison.Ordinal), "Writing screen URLs should include chapterId when available."); - Assert(script.Contains("url.searchParams.set(\"sceneId\", sceneId)", StringComparison.Ordinal), "Writing screen URLs should include sceneId when available."); - Assert(script.Contains("url.searchParams.set(\"documentGuid\", documentGuid)", StringComparison.Ordinal), "Writing screen URLs should include documentGuid for diagnostics."); - Assert(controller.Contains("Guid? documentGuid", StringComparison.Ordinal), "Writing routes should accept the Word document identifier."); - Assert(contextView.Contains("data-document-guid=\"@Model.DocumentGuid\"", StringComparison.Ordinal), "Writing Context should retain the document identifier."); - Assert(intentView.Contains("data-document-guid=\"@Model.DocumentGuid\"", StringComparison.Ordinal), "Writing Intent should retain the document identifier."); -} static void WordCompanionCanonicalMarkersDriveRuntimeFollow() { @@ -2373,28 +2116,6 @@ static void WordCompanionDocumentIdentitySurvivesReconnect() Assert(repository.Contains("\"dbo.ManuscriptDocument_UpdateLastOpened\"", StringComparison.Ordinal), "Last-opened update must remain stored-procedure based."); } -static void WordCompanionMultiscreenLaunchAndFollowRemainReachable() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var view = File.ReadAllText(Path.Combine(root, "Views/WordCompanionHost/Index.cshtml")); - var hostScript = File.ReadAllText(Path.Combine(root, "wwwroot/js/word-companion-host.js")); - var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - var contextView = File.ReadAllText(Path.Combine(root, "Views/Writing/Context.cshtml")); - var intentView = File.ReadAllText(Path.Combine(root, "Views/Writing/Intent.cshtml")); - - Assert(view.Contains("data-open-writing-workspace", StringComparison.Ordinal), "Word Companion should expose the workspace launch action."); - Assert(view.Contains("data-open-writing-context", StringComparison.Ordinal), "Word Companion should expose the Context launch action."); - Assert(view.Contains("data-open-writing-intent", StringComparison.Ordinal), "Word Companion should expose the Intent launch action."); - Assert(hostScript.Contains("openWritingWindow(\"context\")", StringComparison.Ordinal), "Context launch should call the writing window helper."); - Assert(hostScript.Contains("openWritingWindow(\"intent\")", StringComparison.Ordinal), "Intent launch should call the writing window helper."); - Assert(hostScript.Contains("new URL(target === \"workspace\" ? \"/Writer\" : `/Writing/${target}`", StringComparison.Ordinal), "Writing windows should target the dedicated Context, Intent, and Workspace routes."); - Assert(hostScript.Contains("url.searchParams.set(\"sceneId\", sceneId)", StringComparison.Ordinal), "Writing windows should receive the current canonical SceneID."); - Assert(follow.Contains("connection.invoke(\"WatchWritingWorkspace\"", StringComparison.Ordinal), "Writing panes should attach to the Word Companion follow hub."); - Assert(follow.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "Writing panes should receive runtime scene changes."); - Assert(follow.Contains("registerWindow", StringComparison.Ordinal), "Writing panes should register their multiscreen role."); - Assert(contextView.Contains("~/js/writing-follow.js", StringComparison.Ordinal), "Context page should load shared follow script."); - Assert(intentView.Contains("~/js/writing-follow.js", StringComparison.Ordinal), "Intent page should load shared follow script."); -} static void WordCompanionModesRemainDistinct() { @@ -2414,22 +2135,6 @@ static void WordCompanionModesRemainDistinct() Assert(script.Contains("setFirstRunMode(false)", StringComparison.Ordinal), "Linked documents should leave the bind/import mode."); } -static void WritingPagesDoNotRequireStoryIntelligence() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var controller = File.ReadAllText(Path.Combine(root, "Controllers/WritingController.cs")); - var contextPartial = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingContextContent.cshtml")); - var intentPartial = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingIntentContent.cshtml")); - var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - - Assert(controller.Contains("IStoryContextService storyContext", StringComparison.Ordinal), "Writing pages should use canonical story context."); - Assert(controller.Contains("IWriterWorkspaceService writerWorkspace", StringComparison.Ordinal), "Writing Intent should use existing writer workspace planning data."); - Assert(!controller.Contains("IStoryIntelligence", StringComparison.Ordinal), "Writing routes should not depend on Story Intelligence services."); - Assert(!controller.Contains("Onboarding", StringComparison.Ordinal), "Writing routes should not depend on import onboarding."); - Assert(contextPartial.Contains("@Model.EmptyTitle", StringComparison.Ordinal), "Writing Context should render a normal empty state when context is unavailable."); - Assert(intentPartial.Contains("@Model.EmptyMessage", StringComparison.Ordinal), "Writing Intent should render a normal empty state when planning data is unavailable."); - Assert(follow.Contains("No current Word scene has been received", StringComparison.Ordinal), "Writing panes should tolerate no current Word scene without Story Intelligence."); -} static void WordCompanionHostScriptHasValidTabMapping() { @@ -2444,43 +2149,7 @@ static void WordCompanionHostScriptHasValidTabMapping() Assert(view.Split("word-companion-review-group").Length - 1 == 3, "Review panel should contain exactly the three review groups."); } -static void WritingScreensShowDiagnosticEmptyStates() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var viewModel = File.ReadAllText(Path.Combine(root, "ViewModels/CoreViewModels.cs")); - var controller = File.ReadAllText(Path.Combine(root, "Controllers/WritingController.cs")); - var contextPartial = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingContextContent.cshtml")); - var intentPartial = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingIntentContent.cshtml")); - var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - Assert(viewModel.Contains("EmptyTitle", StringComparison.Ordinal), "Writing display models should carry an empty-state title."); - Assert(viewModel.Contains("EmptyMessage", StringComparison.Ordinal), "Writing display models should carry an empty-state message."); - Assert(controller.Contains("No current Word scene received", StringComparison.Ordinal), "Writing routes should not default to Waiting for Word forever."); - Assert(controller.Contains("No Story Intelligence context is available", StringComparison.Ordinal), "Writing Context should report missing context clearly."); - Assert(controller.Contains("No writing intent is available", StringComparison.Ordinal), "Writing Intent should report missing intent clearly."); - Assert(contextPartial.Contains("@Model.EmptyTitle", StringComparison.Ordinal), "Writing Context empty state should render the diagnostic title."); - Assert(intentPartial.Contains("@Model.EmptyMessage", StringComparison.Ordinal), "Writing Intent empty state should render the diagnostic message."); - Assert(follow.Contains("setEmptyState", StringComparison.Ordinal), "Writing follow should update empty states after connection/fetch failures."); - Assert(follow.Contains("No current Word scene has been received", StringComparison.Ordinal), "Writing follow should replace indefinite waiting with a diagnostic message."); -} - -static void WordCompanionThreeScreenFlowLogsConnectionIdentifiers() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var hostController = File.ReadAllText(Path.Combine(root, "Controllers/WordCompanionHostController.cs")); - var wordController = File.ReadAllText(Path.Combine(root, "Controllers/WordCompanionController.cs")); - var hub = File.ReadAllText(Path.Combine(root, "Hubs/WordCompanionFollowHub.cs")); - var hostScript = File.ReadAllText(Path.Combine(root, "wwwroot/js/word-companion-host.js")); - var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - - Assert(hostController.Contains("Serving Word Companion host", StringComparison.Ordinal), "Word Companion host route should log which host page is served."); - Assert(wordController.Contains("Word Companion current scene received", StringComparison.Ordinal), "Current-scene API should log received identifiers."); - Assert(wordController.Contains("DocumentGuidPresent", StringComparison.Ordinal), "Current-scene API should log document identifier presence without exposing the value."); - Assert(hub.Contains("Word Companion registered", StringComparison.Ordinal), "Companion SignalR registration should be logged."); - Assert(hub.Contains("Writing window registered", StringComparison.Ordinal), "Context/Intent window registration should be logged."); - Assert(hostScript.Contains("[Word Companion] Opening writing screen.", StringComparison.Ordinal), "Host UI should log direct writing screen opens."); - Assert(follow.Contains("Loading writing position", StringComparison.Ordinal), "Context/Intent follow helper should log received positions."); -} static void WordManuscriptCleanupClassifiesPlotDirectorMarkersByTagOnly() { @@ -8157,20 +7826,6 @@ static void StoryIntelligenceNarrativeStageFollowsKnowledge() Assert(controller.Contains("ImportStoryIntelligenceKnowledge", StringComparison.Ordinal) && controller.Contains("RedirectToAction(nameof(StoryIntelligenceReviewCentre)", StringComparison.Ordinal), "Knowledge completion should return to Review Centre instead of auto-advancing."); } -static void WordCompanionReplaysLiveCurrentSceneToWritingPanes() -{ - var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); - var controller = File.ReadAllText(Path.Combine(root, "Controllers/WordCompanionController.cs")); - var presence = File.ReadAllText(Path.Combine(root, "Services/WordCompanionPresenceService.cs")); - var workspace = File.ReadAllText(Path.Combine(root, "Services/WritingWorkspacePresenceService.cs")); - var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js")); - - Assert(controller.Contains("presence.UpdateCurrentStoryPositionAsync", StringComparison.Ordinal), "Word current-scene updates should update live presence."); - Assert(presence.Contains("CurrentStoryPosition = connected ? record.CurrentStoryPosition : null", StringComparison.Ordinal), "Presence should only replay current scene while Word is live."); - Assert(workspace.Contains("CurrentStoryPosition = wordStatus.CurrentStoryPosition", StringComparison.Ordinal), "Workspace status should carry Word's current scene."); - Assert(script.Contains("storyPositionFromWorkspaceStatus", StringComparison.Ordinal), "Writing panes should read the current scene from workspace status."); - Assert(script.Contains("WatchWritingWorkspace", StringComparison.Ordinal), "Writing panes should request scoped workspace status on startup."); -} static int CountCsvRows(string path) => File.ReadLines(path).Skip(1).Count(line => !string.IsNullOrWhiteSpace(line)); diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index e5e49544..53205b13 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -112,7 +112,7 @@ internal static class ToolbarBrowserHost return model; } - private static async Task RenderFullAsync(HttpContext context, string controller, string actionName, object model) + private static async Task RenderFullAsync(HttpContext context, string controller, string actionName, object model, Dictionary? extras=null) { context.Request.RouteValues["controller"] = controller; context.Request.RouteValues["action"] = actionName; @@ -120,8 +120,10 @@ internal static class ToolbarBrowserHost 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(); + var fullData=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model,["WritingEmbedded"]=true}; + if(extras!=null)foreach(var item in extras)fullData[item.Key]=item.Value; await view.View.RenderAsync(new ViewContext(action, view.View, - new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model, ["WritingEmbedded"] = context.Request.Query["embedded"] == "true" }, + fullData, new TempDataDictionary(context, context.RequestServices.GetRequiredService()), writer, new HtmlHelperOptions())); context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync(writer.ToString()); @@ -140,7 +142,6 @@ internal static class ToolbarBrowserHost builder.Services.AddScoped(); builder.Services.AddSingleton(TimeProvider.System); 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))); @@ -331,7 +332,7 @@ internal static class ToolbarBrowserHost scene.PrimaryLocationID=77;scene.FloorPlanID=1;scene.InitialFloorPlanFloorID=8; ((WritingContextDisplayViewModel)model).FloorPlan=new(){FloorPlan=new(){FloorPlanID=1,Name="The inn"},Floors=[new(){FloorPlanFloorID=8,Name="Upper floor",GridWidth=20,GridHeight=10}],Blocks=[new(){FloorPlanFloorID=8,FloorPlanBlockID=9,LocationID=77,LocationName="Guest room",X=2,Y=2,WidthCells=4,HeightCells=3}]}; } - var writingRoute=new RouteData();writingRoute.Values["controller"]="Writing";var action=new ActionContext(context,writingRoute,new ActionDescriptor());var path=role=="evidence"?"/Views/Writing/_IntentAssessment.cshtml":role=="context"?"/Views/Writing/_WritingContextContent.cshtml":"/Views/Writing/_WritingIntentContent.cshtml"; + var writingRoute=new RouteData();writingRoute.Values["controller"]="Writing";var action=new ActionContext(context,writingRoute,new ActionDescriptor());var path=role=="evidence"?"/Views/Writing/_IntentAssessment.cshtml":role=="context"?"/Views/Writing/_WritingContextOverview.cshtml":"/Views/Writing/_WritingIntentPlan.cshtml"; var view=context.RequestServices.GetRequiredService().GetView(null,path,false);using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions())); if(context.Request.Query["fragment"]=="true"){context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());return;} @@ -378,8 +379,31 @@ internal static class ToolbarBrowserHost if(step=="Preview")model.Preview=new(new(upload,[12,13],0,"Recovered harbour","",Guid.NewGuid(),DateTime.UtcNow.AddMinutes(20)),"fixture-confirmation",snapshot,12,5,context.Request.Query.ContainsKey("full")?0:4,package.Warnings); await RenderFullAsync(context,"BookRecovery",step,step=="Complete"?new BookRecoveryReceipt{ProjectID=7,BooksCreated=2}:model); }); - app.MapGet("/Writing/Context", context => RenderFullAsync(context, "Writing", "Context", new WritingContextPageViewModel { ProjectID = 7, BookID = int.TryParse(context.Request.Query["bookId"].ToString(), out var bookId) ? bookId : 12 })).WithOrder(-1); - app.MapGet("/Writing/Intent", context => RenderFullAsync(context, "Writing", "Intent", new WritingIntentPageViewModel { ProjectID = 7, BookID = int.TryParse(context.Request.Query["bookId"].ToString(), out var bookId) ? bookId : 12 })).WithOrder(-1); + app.MapGet("/Writing/Context", async context => + { + context.Request.RouteValues["controller"] = "Writing"; + var pinned=context.Request.Query["pinned"]=="true"; + var sceneId=int.TryParse(context.Request.Query["sceneId"],out var selected)?selected:22; + var page=new WritingContextPageViewModel { ProjectID=7, BookID=12, ChapterID=10, SceneID=sceneId, + Display=new(){SceneOptions=[new("Chapter one · scene one","22",sceneId==22),new("Chapter two · scene two","23",sceneId==23)]} }; + await RenderFullAsync(context,"Writing","Context",page,new Dictionary { ["NativeSnapshot"]=pinned }); + }).WithOrder(-1); + app.MapGet("/Writing/Intent",context=>{context.Response.Redirect("/Writing/Context"+context.Request.QueryString);return Task.CompletedTask;}).WithOrder(-1); + app.MapGet("/context-tab-fixture/{tool}",async context=> + { + var sceneId=int.TryParse(context.Request.Query["sceneId"],out var id)?id:22; + var scene=new SceneEditViewModel { SceneID=sceneId, ChapterID=sceneId==23?11:10, + SceneTitle="Scene "+sceneId+" · A deliberately long scene title for a narrow reference screen", Summary="Saved scene summary and provenance",ScenePurposeNotes="Reveal the letter",SceneOutcomeNotes="A decision changes the plan", + Project=new(){ProjectID=7,ProjectName="Fixture project"},Book=new(){BookID=12,BookTitle="Fixture book"},Chapter=new(){ChapterID=10,ChapterNumber=1,ChapterTitle="Opening"}, + SceneCharacters=[new(){CharacterID=5,CharacterName="Fixture participant",RoleInSceneTypeName="Observer",EmotionalState="Uncertain",PhysicalCondition="Tired",LocationName="Saved room",EntryLocationName="Hall",ExitLocationName="Garden"}] }; + var model=new WritingContextDisplayViewModel { Context=new(){Position=new(7,12,scene.ChapterID,sceneId),Scene=scene} }; + var action=new ActionContext(context,new RouteData(),new ActionDescriptor()); + var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextTab.cshtml",false); + using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; + data["ContextTabPartial"]=context.Request.RouteValues["tool"]?.ToString()=="characters"?"_WritingContextPeople":"_WritingContextOverview"; + await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions())); + context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); + }); app.MapGet("/scenario-fixture/{view}", async (HttpContext context, string view) => { var project = new Project { ProjectID = 7, ProjectName = "Scenario visual qualification" }; diff --git a/PlotLine.Tests/WordMarkerSecurityTests.cs b/PlotLine.Tests/WordMarkerSecurityTests.cs index 1f74930f..c650a815 100644 --- a/PlotLine.Tests/WordMarkerSecurityTests.cs +++ b/PlotLine.Tests/WordMarkerSecurityTests.cs @@ -27,7 +27,7 @@ internal static class WordMarkerSecurityTests }); var client=Proxy((name,args)=>{sends++;return Task.CompletedTask;}); var clients=Proxy((name,args)=>client); - var hub=new WordCompanionFollowHub(null!,null!,null!,null!,null!,repository,NullLogger.Instance) + var hub=new WordCompanionFollowHub(null!,null!,null!,null!,repository,NullLogger.Instance) {Context=new Caller(),Clients=clients}; foreach(var action in new Func[]{()=>hub.CompleteOnboardingBuildMarkerSync(99),()=>hub.RequireOnboardingBuildManualSave(99,"save"),()=>hub.FailOnboardingBuildMarkerSync(99,"failed")}) { @@ -45,7 +45,7 @@ internal static class WordMarkerSecurityTests var legacy=new PlotLine.Services.WordCompanionPresenceService(); var books=Proxy((_,_)=>Task.FromResult(new(){BookID=3,ProjectID=1})); var access=Proxy((_,_)=>Task.FromResult(new(){BookId=3})); - var combined=new WordCompanionFollowHub(legacy,null!,null!,null!,null!,repository,NullLogger.Instance,nativePresence:native,nativeBooks:books,nativeAccess:access){Context=new Caller(),Groups=Proxy((_,_)=>Task.CompletedTask)}; + var combined=new WordCompanionFollowHub(legacy,null!,null!,null!,repository,NullLogger.Instance,nativePresence:native,nativeBooks:books,nativeAccess:access){Context=new Caller(),Groups=Proxy((_,_)=>Task.CompletedTask)}; var status=await combined.WatchCompanionPresence();Check(status.IsConnected&&status.CompanionVersion=="Native"&&status.LinkedBookID==3&&status.CurrentStoryPosition?.SceneId==20,"Existing website status must use the authoritative native session"); native.Remove(4,"grant",instance,session);Check(!(await combined.WatchCompanionPresence()).IsConnected,"Website status cannot keep a native session green after disconnect"); } diff --git a/PlotLine.Tests/WriterFoundationTests.cs b/PlotLine.Tests/WriterFoundationTests.cs index 0423a80a..9005dae7 100644 --- a/PlotLine.Tests/WriterFoundationTests.cs +++ b/PlotLine.Tests/WriterFoundationTests.cs @@ -55,9 +55,8 @@ internal static class WriterFoundationTests Check(scopes.Count == 0, "inaccessible project never reaches a queue repository"); var missingStory = Proxy((n,a) => Task.FromResult(null)); - var references = new WritingController(missingStory, null!, null!, Proxy((n,a)=>throw new Exception(n)), Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); - var missing = (ViewResult)await references.Context(1,2,null,999,null,pinned:true); - Check(((WritingContextPageViewModel)missing.Model!).WorkingContext == null, "unresolved route scene never becomes a pinned authorised selection"); + var references = new WritingController(missingStory, null!, null!, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + Check(await references.Context(1,2,null,999,null,pinned:true) is ForbidResult, "unresolved or unauthorized scope cannot become a pinned selection"); var plans = new WritingPlanSummary[] { new(){WritingPlanID=1,ProjectID=1,BookID=2}, new(){WritingPlanID=2,ProjectID=1,BookID=3}, new(){WritingPlanID=3,ProjectID=1,BookID=null}, new(){WritingPlanID=4,ProjectID=9,BookID=99} }; var scheduleRepo = Proxy((n,a) => n switch diff --git a/PlotLine.Tests/WritingContextNavigationTests.cs b/PlotLine.Tests/WritingContextNavigationTests.cs index 22af5def..0b4ec29f 100644 --- a/PlotLine.Tests/WritingContextNavigationTests.cs +++ b/PlotLine.Tests/WritingContextNavigationTests.cs @@ -27,7 +27,7 @@ internal static class WritingContextNavigationTests var native=new NativeWorkspaceController(access,NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(new(){BookID=12,ProjectID=7,BookTitle="Fixture book"})),NativeWorkflowTests.Proxy((n,a)=>throw new Exception("Context launch must not load old review/iframe shell")),presence){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}}; var direct=await native.Workspace(12,instance,session,"context") as RedirectToActionResult; Check(direct?.ActionName=="Context"&&direct.ControllerName=="Writing"&&Equals(direct.RouteValues!["instanceId"],instance),"Native Context opens the existing Writing workspace directly and preserves document selection, with no iframe"); - var controller=new WritingController(null!,null!,null!,null!,NullLogger.Instance){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}}; + var controller=new WritingController(null!,null!,null!,NullLogger.Instance){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}}; Task Navigate(Guid? document=null)=>controller.NavigateWord(12,23,document??instance,session,access,paragraphs,presence); Check(await Navigate() is OkObjectResult,"Explicit cross-chapter navigation accepts an owned scene and current verified paragraph start"); var command=presence.TakeNavigation(7,"installation",instance,session);Check(command?.Kind=="navigate"&&command.Chapter?.Start==100&&command.Revision==3,"Existing positional command routes to exact session/revision without writing prose or markers"); diff --git a/PlotLine.Tests/WritingContextPlotLinesTests.cs b/PlotLine.Tests/WritingContextPlotLinesTests.cs index d5f155de..8f2481d2 100644 --- a/PlotLine.Tests/WritingContextPlotLinesTests.cs +++ b/PlotLine.Tests/WritingContextPlotLinesTests.cs @@ -30,7 +30,7 @@ internal static class WritingContextPlotLinesTests var permissions=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(allowed)); var book= new Book{BookID=12,ProjectID=7}; var books=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(book)); - var controller=new WritingController(null!,null!,null!,null!,NullLogger.Instance); + var controller=new WritingController(null!,null!,null!,NullLogger.Instance); Check(await controller.ContextPlotLines(7,12,repository,permissions,books) is NotFoundResult&&reads==0,"Unauthorised requests must not read saved plot data"); allowed=true;book.ProjectID=8; Check(await controller.ContextPlotLines(7,12,repository,permissions,books) is NotFoundResult&&reads==0,"A book in another project must not leak saved developments"); diff --git a/PlotLine.Tests/WritingIntegrationTests.cs b/PlotLine.Tests/WritingIntegrationTests.cs index 828f1aad..b7bdd32c 100644 --- a/PlotLine.Tests/WritingIntegrationTests.cs +++ b/PlotLine.Tests/WritingIntegrationTests.cs @@ -1,3 +1,5 @@ +using Microsoft.AspNetCore.SignalR; +using PlotLine.Hubs; using System.Diagnostics; using System.Reflection; using System.Security.Claims; @@ -34,6 +36,21 @@ internal static class WritingIntegrationTests await ReadOnlyScene(); await ResolutionAndIntent(); await ChronologyAndReuse(); + await NotificationBoundary(); + } + private static async Task NotificationBoundary() + { + string? group=null,eventName=null,payload=null;var fail=false; + var client=Stub((name,args)=>{if(fail)throw new InvalidOperationException("Synthetic disconnected transport");eventName=(string)args![0]!;payload=JsonSerializer.Serialize(args[1]);return Task.CompletedTask;}); + var clients=Stub((name,args)=>{group=(string)args![0]!;return client;}); + var hub=Stub>((name,args)=>clients); + var notifications=new ContextWorkspaceNotifications(hub,NullLogger.Instance); + await notifications.Invalidate(7,2,3,20); + Check(group==NativeCompanionPresenceHub.UserGroup(7)&&eventName=="ContextInvalidated"&&payload!.Contains("bookId"),"Accepted-data invalidations use the authenticated account's existing hub group and lightweight scope"); + await notifications.Position(7); + Check(eventName=="ContextPositionChanged"&&!payload!.Contains("sceneId"),"Office notifications are hints, not invented authoritative cursor payloads"); + fail=true;await notifications.Invalidate(7,2); + Check(true,"Notification transport failure cannot turn a committed manuscript save into failure"); } private static async Task ReadOnlyScene() { @@ -102,7 +119,7 @@ internal static class WritingIntegrationTests var goal=new ChapterGoal{GoalSummary="An author's objective",EmotionalGoal="Doubt → commitment",MustInclude="An unresolved promise",ReaderTakeaway="A possibility, not canon"}; var workflow=new ChapterWorkflowViewModel{Project=scene.Project!,Book=scene.Book!,Chapter=scene.Chapter!,Goal=goal}; var writer=Stub((n,a)=>n=="GetChapterWorkflowAsync"?Task.FromResult(workflow):throw new Exception("Intent read attempted a write")); - var controller=new WritingController(story,null!,null!,writer,NullLogger.Instance,companion,presence,Stub((n,a)=>Task.FromResult(allowed)), + var controller=new WritingController(story,null!,null!,NullLogger.Instance,companion,presence,Stub((n,a)=>Task.FromResult(allowed)), Stub((n,a)=>n=="Position"?Task.FromResult(mapping?new(){Revision=3,ChapterID=2,SceneID=presence.Read(7,2).Single().Position.SceneId}:null):throw new Exception("Context must not synchronise or reconcile"))) {ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}}; Beat(); @@ -110,9 +127,12 @@ internal static class WritingIntegrationTests Check(page.WorkingContext?.VerifiedWord?.Selection.SceneID==20 && page.WorkingContext.Working==null,"Verified native projection leaves working focus independent"); Check(page.SceneID==20&&page.Display!.HasScene&&page.Display.FollowStatus=="Following Word","Native launch opens its exact verified scene rather than the book's first scene"); var before=JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal}); - var intent=(WritingIntentPageViewModel)((ViewResult)await controller.Intent(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; - Check(intent.SceneID==20&&intent.Display!.ChapterWorkflow!.Goal==goal&&intent.Display.Context!.Scene!.ScenePurposeNotes==scene.ScenePurposeNotes,"Native Intent retrieves the selected scene's existing purpose and chapter objectives"); - Check(JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal})==before,"Opening Context and Intent preserves all author-entered decisions verbatim"); + var redirect=(RedirectToActionResult)controller.Intent(1,2,2,20,null,instanceId:instance,sessionId:session); + Check(redirect.ActionName=="Context" && (Guid)redirect.RouteValues!["sessionId"]! == session,"Intent compatibility preserves native session and routes only to Context"); + Check(JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal})==before,"Opening Context preserves all author-entered decisions verbatim"); + Check(await controller.ContextCharacters(1,2,2,20,instance,session) is PartialViewResult characters && characters.ViewName=="_ContextTab","Characters has its own authorized partial endpoint"); + Check(await controller.ContextCharacters(1,2,2,99,instance,session) is ConflictObjectResult,"Partial endpoint refuses a claimed scene different from the current session"); + Check(await controller.ContextCharacters(1,2,2,20,instance,null) is BadRequestResult,"Partial endpoint rejects incomplete native document identity"); Beat(saved:false);var oldReads=reads; page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; Check(!page.Display!.HasScene&&reads==oldReads,"Unsaved native mapping waits without loading an unrelated saved scene"); @@ -120,15 +140,16 @@ internal static class WritingIntegrationTests Check(!page.Display!.HasScene&&reads==oldReads,"A stale database checkpoint cannot launch a scene merely claimed by the last heartbeat");mapping=true; Beat(paragraph:0);page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; Check(!page.Display!.HasScene&&reads==oldReads,"Chapter-capable sessions without accepted position evidence cannot launch claimed scene IDs"); - Beat(current:null);intent=(WritingIntentPageViewModel)((ViewResult)await controller.Intent(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; - Check(intent.Display!.IsChapterOnly&&intent.Display.ChapterWorkflow!.Goal==goal,"A verified chapter with no mapped scene can show its own saved chapter intent"); + Beat(current:null);page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; + Check(!page.Display!.HasScene,"A chapter without a mapped scene does not invent scene reference data"); Beat();onRead=()=>{revision++;Beat(current:99);}; page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; Check(!page.Display!.HasScene,"A Word cursor/revision change during server loading cannot render the earlier cursor as current"); Beat();Check(await controller.ContextScene(1,2,2,20,instance,session) is ConflictObjectResult,"Native partial requests reject mappings that change during data loading");onRead=null; Beat();allowed=false; Check(await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session) is ForbidResult,"Native Context launch authorises the book before resolving or displaying its scene");allowed=true; - Check(await controller.Intent(1,2,null,null,null,instanceId:Guid.NewGuid(),sessionId:session) is ViewResult missing&&((WritingIntentPageViewModel)missing.Model!).Display!.HasScene==false,"Exact document selection cannot fall back to another connected Word instance"); + page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:Guid.NewGuid(),sessionId:session)).Model!; + Check(!page.Display!.HasScene,"Exact document selection cannot fall back to another connected Word instance"); Check(await controller.Context(1,2,null,null,null,instanceId:instance) is BadRequestObjectResult,"Incomplete native session identity is rejected"); } } diff --git a/PlotLine/Controllers/NativeWorkspaceController.cs b/PlotLine/Controllers/NativeWorkspaceController.cs index 5b33224c..96ce515a 100644 --- a/PlotLine/Controllers/NativeWorkspaceController.cs +++ b/PlotLine/Controllers/NativeWorkspaceController.cs @@ -15,7 +15,7 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB public async Task Workspace(int bookId,Guid? instanceId,Guid? sessionId,string view="book") { var structure=await access.GetBookStructureAsync(bookId,Author);if(structure==null)return Forbid();var book=await books.GetAsync(bookId);if(book==null)return NotFound(); - if(view is "context" or "intent") return RedirectToAction(view=="context"?"Context":"Intent","Writing",new{projectId=book.ProjectID,bookId,instanceId,sessionId,embedded=true}); + if(view is "context" or "intent") return RedirectToAction("Context","Writing",new{projectId=book.ProjectID,bookId,instanceId,sessionId,embedded=true}); return View(new NativeWorkspaceModel(bookId,book.ProjectID,book.BookDisplayTitle,instanceId,sessionId,view is "context" or "intent"?view:"book",await reviews.List(Author,bookId),structure.Chapters)); } [HttpGet("presence")] diff --git a/PlotLine/Controllers/WordCompanionController.cs b/PlotLine/Controllers/WordCompanionController.cs index 69853c37..db7ca1b6 100644 --- a/PlotLine/Controllers/WordCompanionController.cs +++ b/PlotLine/Controllers/WordCompanionController.cs @@ -16,7 +16,7 @@ public sealed class WordCompanionController( IWordCompanionService wordCompanion, IWordCompanionPresenceService presence, IHubContext followHub, - ILogger logger) : ControllerBase + ILogger logger, ContextWorkspaceNotifications? contextNotifications = null) : ControllerBase { [HttpGet("projects")] public Task GetProjects() => wordCompanion.ListProjectsAsync(); @@ -86,6 +86,7 @@ public sealed class WordCompanionController( public async Task SyncScene(int bookId, WordCompanionSyncSceneRequest request) { var response = await wordCompanion.SyncSceneAsync(bookId, request); + if (response != null && contextNotifications != null) await contextNotifications.Invalidate(RequireUserId(), bookId); return response is null ? BadRequest() : Ok(response); } @@ -93,6 +94,7 @@ public sealed class WordCompanionController( public async Task SyncManuscript(int bookId, WordCompanionSyncManuscriptRequest request) { var response = await wordCompanion.SyncManuscriptAsync(bookId, request); + if (response != null && contextNotifications != null) await contextNotifications.Invalidate(RequireUserId(), bookId); return response is null ? BadRequest() : Ok(response); } @@ -100,6 +102,7 @@ public sealed class WordCompanionController( public async Task UpdateSceneLinks(int sceneId, WordCompanionUpdateSceneLinksRequest request) { var response = await wordCompanion.UpdateSceneLinksAsync(sceneId, request); + if (response != null && contextNotifications != null) await contextNotifications.Invalidate(RequireUserId(), null); return response is null ? BadRequest() : Ok(response); } @@ -107,6 +110,7 @@ public sealed class WordCompanionController( public async Task UpdateWordCount(int sceneId, WordCompanionUpdateWordCountRequest request) { var response = await wordCompanion.UpdateWordCountAsync(sceneId, request); + if (response != null && contextNotifications != null) await contextNotifications.Invalidate(RequireUserId(), null); return response is null ? BadRequest() : Ok(response); } @@ -121,6 +125,7 @@ public sealed class WordCompanionController( public async Task UpdateRuntimeSceneWordCount(WordCompanionRuntimeSceneWordCountRequest request) { var response = await wordCompanion.UpdateRuntimeSceneWordCountAsync(request); + if (response != null && contextNotifications != null) await contextNotifications.Invalidate(RequireUserId(), null); return response is null ? BadRequest() : Ok(response); } @@ -167,6 +172,7 @@ public sealed class WordCompanionController( response.Position }); + if (contextNotifications != null) await contextNotifications.Position(RequireUserId()); return Ok(response); } diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index f44c6b97..5f47541e 100644 --- a/PlotLine/Controllers/WritingController.cs +++ b/PlotLine/Controllers/WritingController.cs @@ -18,7 +18,6 @@ public sealed class WritingController( IStoryContextService storyContext, IRelationshipMapService relationshipMap, IFloorPlanService floorPlans, - IWriterWorkspaceService writerWorkspace, ILogger logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null) : Controller { [HttpGet("Context")] @@ -34,63 +33,8 @@ public sealed class WritingController( documentGuid.HasValue); if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest("Choose one complete Word document session."); - var nativeLaunch=!pinned&&(instanceId.HasValue||sessionId.HasValue); - NativeWritingTarget? target=null; - if(nativeLaunch) - { - if(!bookId.HasValue||companion==null)return BadRequest("A linked book is required."); - var structure=await companion.GetBookStructureAsync(bookId.Value,WritingUser); - if(structure==null)return Forbid(); - target=await NativeTarget(bookId,instanceId,sessionId); - var chapter=structure.Chapters.FirstOrDefault(c=>c.ChapterId==target?.ChapterId); - if(target?.SceneId is int current&&chapter?.Scenes.Any(x=>x.SceneId==current)!=true)target=null; - if(target?.ChapterId!=null&&chapter==null)target=null; - chapterId=target?.ChapterId;sceneId=target?.SceneId; - } - if(!nativeLaunch&&!sceneId.HasValue&&bookId.HasValue&&companion!=null) { - var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); - sceneId=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault()?.SceneId; - } - var display = sceneId.HasValue - ? await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual context") - : WaitingContextDisplay(projectId, bookId, documentGuid); - - if(nativeLaunch&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId))) - { - sceneId=null;chapterId=null;target=null; - display=WaitingContextDisplay(projectId,bookId,documentGuid); - } - if(nativeLaunch&&display!=null)display.FollowStatus=target!=null&&sceneId.HasValue?"Following Word":"Word mapping pending · choose a saved scene to browse manually"; - if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue){display.EmptyTitle="No saved scene selected";display.EmptyMessage="This is a scoped saved-data view, not live Word following. Select a saved scene in PlotDirector; local markers or AI suggestions do not create saved context.";}} - var model = new WritingContextPageViewModel - { - ProjectID = display?.Context?.Position.ProjectId ?? projectId, - BookID = display?.Context?.Position.BookId ?? bookId, - ChapterID = chapterId, - SceneID = sceneId, - DocumentGuid = documentGuid, - Display = display ?? MissingContextDisplay(projectId, bookId, sceneId) - }; - - model.WorkingContext = ReferenceContext(model.ProjectID, model.BookID, - model.Display?.Context?.Position.ChapterId, - model.Display?.Context?.Position.SceneId, pinned, nativeLaunch ? target : null); - return View(model); - } - - [HttpGet("Intent")] - public async Task Intent(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null) - { - ViewData["NativeSnapshot"] = pinned;ViewData["WritingEmbedded"]=embedded;ViewData["WordInstance"]=instanceId;ViewData["WordSession"]=sessionId; - logger.LogInformation( - "Opening Writing Intent. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID} DocumentGuidPresent={DocumentGuidPresent}", - projectId, - bookId, - chapterId, - sceneId, - documentGuid.HasValue); - - if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest("Choose one complete Word document session."); + if (projectId.HasValue && (projectAccess == null || !await projectAccess.CanAccessProjectAsync(projectId.Value))) return Forbid(); + if (bookId.HasValue && (companion == null || await companion.GetBookStructureAsync(bookId.Value, WritingUser) == null)) return Forbid(); var nativeLaunch=!pinned&&(instanceId.HasValue||sessionId.HasValue); NativeWritingTarget? target=null; if(nativeLaunch) @@ -106,82 +50,84 @@ public sealed class WritingController( } if(!nativeLaunch&&!sceneId.HasValue&&!chapterId.HasValue&&bookId.HasValue&&companion!=null) { var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); - var first=structure?.Chapters.FirstOrDefault(c=>c.Scenes.Count>0)??structure?.Chapters.FirstOrDefault(); - chapterId=first?.ChapterId;sceneId=first?.Scenes.FirstOrDefault()?.SceneId; + sceneId=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault()?.SceneId; } - var display = sceneId.HasValue || chapterId.HasValue - ? await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual intent") - : WaitingIntentDisplay(projectId, bookId, documentGuid); + var display = sceneId.HasValue + ? await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual context") + : WaitingContextDisplay(projectId, bookId, documentGuid); if(nativeLaunch&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId))) { sceneId=null;chapterId=null;target=null; - display=WaitingIntentDisplay(projectId,bookId,documentGuid); + display=WaitingContextDisplay(projectId,bookId,documentGuid); } - if(nativeLaunch&&display!=null)display.FollowStatus=target!=null&&(sceneId.HasValue||chapterId.HasValue)?"Following Word":"Word mapping pending · choose a saved scene to browse manually"; - if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue&&!chapterId.HasValue){display.EmptyTitle="No saved writing objective selected";display.EmptyMessage="Choose a saved chapter or scene in PlotDirector. Set its goal/purpose explicitly; this view does not invent or automatically save intent.";}} - var model = new WritingIntentPageViewModel + if(nativeLaunch&&display!=null)display.FollowStatus=target!=null&&sceneId.HasValue?"Following Word":"Word mapping pending · choose a saved scene to browse manually"; + if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue){display.EmptyTitle="No saved scene selected";display.EmptyMessage="This is a scoped saved-data view, not live Word following. Select a saved scene in PlotDirector; local markers or AI suggestions do not create saved context.";}} + if (sceneId.HasValue && display?.HasScene != true && !nativeLaunch) return NotFound(); + var model = new WritingContextPageViewModel { - ProjectID = display?.Context?.Position.ProjectId ?? display?.ChapterWorkflow?.Project.ProjectID ?? projectId, - BookID = display?.Context?.Position.BookId ?? display?.ChapterWorkflow?.Book.BookID ?? bookId, + ProjectID = display?.Context?.Position.ProjectId ?? projectId, + BookID = display?.Context?.Position.BookId ?? bookId, ChapterID = chapterId, SceneID = sceneId, DocumentGuid = documentGuid, - Display = display ?? MissingIntentDisplay(projectId, bookId, chapterId, sceneId) + Display = display ?? MissingContextDisplay(projectId, bookId, sceneId) }; + if (model.BookID.HasValue && companion != null && model.Display != null && model.Display.SceneOptions.Count == 0) + { + var structure = await companion.GetBookStructureAsync(model.BookID.Value, WritingUser); + model.Display.SceneOptions = structure?.Chapters.SelectMany(chapter => chapter.Scenes.Select(scene => + new SelectListItem($"{chapter.Title} / {scene.Title}", scene.SceneId.ToString(), scene.SceneId == model.SceneID))).ToList() ?? []; + } model.WorkingContext = ReferenceContext(model.ProjectID, model.BookID, - model.Display?.Context?.Position.ChapterId ?? model.Display?.ChapterWorkflow?.Chapter.ChapterID, + model.Display?.Context?.Position.ChapterId, model.Display?.Context?.Position.SceneId, pinned, nativeLaunch ? target : null); return View(model); } - [HttpGet("Context/Scene")] - public async Task ContextScene(int? projectId, int? bookId, int? chapterId, int? sceneId,Guid? instanceId=null,Guid? sessionId=null) + // Compatibility only: no Intent shell, registration or follow controller remains. + [HttpGet("Intent"), HttpGet("Intent/Scene")] + public IActionResult Intent(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, + bool pinned = false, bool embedded = false, Guid? instanceId = null, Guid? sessionId = null) { - if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest(); - var nativeRequest=instanceId.HasValue||sessionId.HasValue; - var target=nativeRequest?await NativeTarget(bookId,instanceId,sessionId):null; - if(nativeRequest&&(target==null||target.SceneId!=sceneId||(chapterId.HasValue&&target.ChapterId!=chapterId)))return Conflict(new{message="Word position changed or is awaiting verification."}); - if (!sceneId.HasValue) - { - logger.LogWarning("Writing Context partial requested without SceneID. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID}", projectId, bookId, chapterId); - return PartialView("~/Views/Writing/_WritingContextContent.cshtml", WaitingContextDisplay(projectId, bookId, null)); - } - - var model = await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene"); - if(nativeRequest&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))return Conflict(new{message="Word position changed while context was loading."}); - if (model?.HasScene == true) - { - return PartialView("~/Views/Writing/_WritingContextContent.cshtml", model); - } - - logger.LogWarning("Writing Context could not resolve scene. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID}", projectId, bookId, chapterId, sceneId); - return PartialView("~/Views/Writing/_WritingContextContent.cshtml", MissingContextDisplay(projectId, bookId, sceneId)); + if (!ModelState.IsValid || InvalidNativeSelection(instanceId, sessionId)) return BadRequest(); + return RedirectToAction(nameof(Context), new { projectId, bookId, chapterId, sceneId, documentGuid, pinned, embedded, instanceId, sessionId }); } - [HttpGet("Intent/Scene")] - public async Task IntentScene(int? projectId, int? bookId, int? chapterId, int? sceneId,Guid? instanceId=null,Guid? sessionId=null) + [HttpGet("Context/Tabs/overview")] + public Task ContextScene(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId = null, Guid? sessionId = null) + => RenderContextTab("_WritingContextOverview", projectId, bookId, chapterId, sceneId, instanceId, sessionId); + + [HttpGet("Context/Tabs/characters")] + public Task ContextCharacters(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId = null, Guid? sessionId = null) + => RenderContextTab("_WritingContextPeople", projectId, bookId, chapterId, sceneId, instanceId, sessionId); + + private async Task RenderContextTab(string partial, int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId, Guid? sessionId) { - if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest(); - var nativeRequest=instanceId.HasValue||sessionId.HasValue; - var target=nativeRequest?await NativeTarget(bookId,instanceId,sessionId):null; - if(nativeRequest&&(target==null||target.SceneId!=sceneId||(chapterId.HasValue&&target.ChapterId!=chapterId)))return Conflict(new{message="Word position changed or is awaiting verification."}); - if (!sceneId.HasValue && !chapterId.HasValue) - { - logger.LogWarning("Writing Intent partial requested without ChapterID or SceneID. ProjectID={ProjectID} BookID={BookID}", projectId, bookId); - return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", WaitingIntentDisplay(projectId, bookId, null)); - } + if (!ModelState.IsValid || sceneId is not > 0 || InvalidNativeSelection(instanceId, sessionId)) return BadRequest(); + var nativeRequest = instanceId.HasValue; + var target = nativeRequest ? await NativeTarget(bookId, instanceId, sessionId) : null; + if (nativeRequest && (target == null || target.SceneId != sceneId || (chapterId.HasValue && target.ChapterId != chapterId))) + return Conflict(new { message = "Word position changed or is awaiting verification." }); + var model = await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene"); + if (nativeRequest && !SameNativeTarget(target, await NativeTarget(bookId, instanceId, sessionId))) + return Conflict(new { message = "Word position changed while context was loading." }); + if (model?.HasScene != true) return NotFound(); + if (projectAccess == null || !await projectAccess.CanAccessProjectAsync(model.Context!.Position.ProjectId)) return Forbid(); + ViewData["ContextTabPartial"] = partial; + return PartialView("_ContextTab", model); + } - var model = await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene"); - if(nativeRequest&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))return Conflict(new{message="Word position changed while context was loading."}); - if (model is not null && (model.HasScene || model.HasChapter)) - { - return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", model); - } - - logger.LogWarning("Writing Intent could not resolve chapter/scene. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID}", projectId, bookId, chapterId, sceneId); - return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", MissingIntentDisplay(projectId, bookId, chapterId, sceneId)); + [HttpGet("Context/Position")] + public async Task ContextPosition([FromServices] IWordCompanionPresenceService office, int? bookId, int? projectId) + { + if (!ModelState.IsValid) return BadRequest(); + if (bookId.HasValue && (companion == null || await companion.GetBookStructureAsync(bookId.Value, WritingUser) == null)) return Forbid(); + if (projectId.HasValue && (projectAccess == null || !await projectAccess.CanAccessProjectAsync(projectId.Value))) return Forbid(); + var status = await office.GetStatusAsync(WritingUser); + var position = status.IsConnected && status.DocumentOpen ? status.CurrentStoryPosition : null; + return Ok(new { connected = status.IsConnected && status.DocumentOpen, position }); } private static WriterContext? ReferenceContext(int? project, int? book, int? chapter, int? scene, bool pinned, NativeWritingTarget? native) @@ -256,53 +202,6 @@ public sealed class WritingController( }; } - private async Task BuildIntentDisplayAsync(int? projectId, int? bookId, int? chapterId, int? sceneId, string followStatus) - { - StoryContextViewModel? context = null; - if (sceneId.HasValue) - { - context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId,forWriting:true,includeNarrative:false); - if (context?.Scene is null||chapterId.HasValue&&context.Position.ChapterId!=chapterId) - { - return null; - } - } - - var resolvedChapterId = context?.Position.ChapterId ?? chapterId; - var chapterWorkflow = resolvedChapterId.HasValue - ? await writerWorkspace.GetChapterWorkflowAsync(resolvedChapterId.Value) - : null; - - if (chapterWorkflow is not null) - { - if(projectAccess==null||!await projectAccess.CanAccessProjectAsync(chapterWorkflow.Project.ProjectID))return null; - if (projectId.HasValue && chapterWorkflow.Project.ProjectID != projectId.Value) - { - return null; - } - - if (bookId.HasValue && chapterWorkflow.Book.BookID != bookId.Value) - { - return null; - } - } - - if (context is null && chapterWorkflow is null) - { - return null; - } - - return new WritingIntentDisplayViewModel - { - Context = context, - ChapterWorkflow = chapterWorkflow, - FollowStatus = followStatus, - SceneOptions = context?.Scene is not null - ? await ContextSceneOptions(context.Scene) - : BuildSceneOptions(chapterWorkflow) - }; - } - [HttpGet("Context/Map")] public async Task ContextMap(int projectId,int bookId,int sceneId,int? mapId,[FromServices] MapRepository maps,[FromServices] IMapStoryService storyMaps,[FromServices] IProjectAccessService permissions,[FromServices] IBookRepository books) { @@ -396,17 +295,6 @@ public sealed class WritingController( .ToList(); } - private static IReadOnlyList BuildSceneOptions(ChapterWorkflowViewModel? chapterWorkflow) - { - return chapterWorkflow?.Scenes - .Select(x => new SelectListItem( - $"Scene {x.SceneNumber:g}: {x.SceneTitle}", - x.SceneID.ToString())) - .OrderBy(x => x.Text) - .ToList() - ?? []; - } - private static WritingContextDisplayViewModel WaitingContextDisplay(int? projectId, int? bookId, Guid? documentGuid) => new() { FollowStatus = "No current Word scene received", @@ -414,13 +302,6 @@ public sealed class WritingController( EmptyMessage = MissingScopeMessage(projectId, bookId, documentGuid, "Context") }; - private static WritingIntentDisplayViewModel WaitingIntentDisplay(int? projectId, int? bookId, Guid? documentGuid) => new() - { - FollowStatus = "No current Word scene received", - EmptyTitle = "No current Word scene received", - EmptyMessage = MissingScopeMessage(projectId, bookId, documentGuid, "Intent") - }; - private static WritingContextDisplayViewModel MissingContextDisplay(int? projectId, int? bookId, int? sceneId) => new() { FollowStatus = "Context unavailable", @@ -428,13 +309,6 @@ public sealed class WritingController( EmptyMessage = $"PlotDirector could not load context for scene {sceneId?.ToString() ?? "unknown"} in project {projectId?.ToString() ?? "unknown"}, book {bookId?.ToString() ?? "unknown"}." }; - private static WritingIntentDisplayViewModel MissingIntentDisplay(int? projectId, int? bookId, int? chapterId, int? sceneId) => new() - { - FollowStatus = "Intent unavailable", - EmptyTitle = "No writing intent is available", - EmptyMessage = $"PlotDirector could not load writing intent for chapter {chapterId?.ToString() ?? "unknown"}, scene {sceneId?.ToString() ?? "none"} in project {projectId?.ToString() ?? "unknown"}, book {bookId?.ToString() ?? "unknown"}." - }; - private static string MissingScopeMessage(int? projectId, int? bookId, Guid? documentGuid, string screen) { if (bookId.HasValue) diff --git a/PlotLine/Hubs/NativeCompanionPresenceHub.cs b/PlotLine/Hubs/NativeCompanionPresenceHub.cs index 277b4940..01796024 100644 --- a/PlotLine/Hubs/NativeCompanionPresenceHub.cs +++ b/PlotLine/Hubs/NativeCompanionPresenceHub.cs @@ -2,7 +2,7 @@ using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; namespace PlotLine.Hubs; -// Cookie-authenticated invalidation only. No navigation/Word commands or client-chosen groups. +// Cookie-authenticated native and Context notifications. No Word commands or client-chosen groups. [Authorize] public sealed class NativeCompanionPresenceHub:Hub { diff --git a/PlotLine/Hubs/WordCompanionFollowHub.cs b/PlotLine/Hubs/WordCompanionFollowHub.cs index 58f0d90e..cb9b40b8 100644 --- a/PlotLine/Hubs/WordCompanionFollowHub.cs +++ b/PlotLine/Hubs/WordCompanionFollowHub.cs @@ -11,14 +11,13 @@ namespace PlotLine.Hubs; [Authorize] public sealed class WordCompanionFollowHub( IWordCompanionPresenceService presence, - IWritingWorkspacePresenceService writingPresence, IOnboardingRepository onboarding, IManuscriptScanPreviewStore scanStore, IOnboardingService onboardingService, IOnboardingBuildRepository onboardingBuilds, ILogger logger, PlotLine.Services.NativeCompanion.NativeManuscriptCapture? nativeCapture=null, - PlotLine.Services.NativeCompanion.NativePresenceStore? nativePresence=null,IBookRepository? nativeBooks=null,IWordCompanionRepository? nativeAccess=null) : Hub + PlotLine.Services.NativeCompanion.NativePresenceStore? nativePresence=null,IBookRepository? nativeBooks=null,IWordCompanionRepository? nativeAccess=null,ContextWorkspaceNotifications? contextNotifications=null) : Hub { public override async Task OnConnectedAsync() { @@ -53,7 +52,7 @@ public sealed class WordCompanionFollowHub( registration.LinkedBookID, registration.DocumentOpen); await Clients.Group(PresenceGroup(userId)).SendAsync("WordCompanionPresenceChanged", status); - await BroadcastWritingWorkspaceStatusAsync(userId, registration.LinkedProjectID, registration.LinkedBookID); + if(contextNotifications!=null)await contextNotifications.Position(userId); return status; } @@ -68,63 +67,10 @@ public sealed class WordCompanionFollowHub( heartbeat.LinkedBookID, heartbeat.DocumentOpen); await Clients.Group(PresenceGroup(userId)).SendAsync("WordCompanionPresenceChanged", status); - await BroadcastWritingWorkspaceStatusAsync(userId, heartbeat.LinkedProjectID, heartbeat.LinkedBookID); + if(contextNotifications!=null)await contextNotifications.Position(userId); return status; } - public async Task WatchWritingWorkspace(WritingWorkspaceScope scope) - { - var userId = RequireUserId(); - await Groups.AddToGroupAsync(Context.ConnectionId, PresenceGroup(userId)); - logger.LogInformation( - "Writing workspace watched. UserID={UserID} ProjectID={ProjectID} BookID={BookID}", - userId, - scope.ProjectID, - scope.BookID); - return await WritingWorkspaceStatusAsync(userId, scope); - } - - public async Task RegisterWritingWindow(WritingWindowRegistration registration) - { - var userId = RequireUserId(); - await Groups.AddToGroupAsync(Context.ConnectionId, PresenceGroup(userId)); - var status = await writingPresence.RegisterAsync(userId, Context.ConnectionId, registration, await CombinedPresence(userId)); - logger.LogInformation( - "Writing window registered. UserID={UserID} Role={Role} ProjectID={ProjectID} BookID={BookID} Route={Route}", - userId, - registration.WritingRole, - registration.ProjectID, - registration.BookID, - registration.CurrentRoute); - await Clients.Group(PresenceGroup(userId)).SendAsync("WritingWorkspacePresenceChanged", status); - return status; - } - - public async Task WritingWindowHeartbeat(WritingWindowHeartbeat heartbeat) - { - var userId = RequireUserId(); - var status = await writingPresence.HeartbeatAsync(userId, Context.ConnectionId, heartbeat, await CombinedPresence(userId)); - await Clients.Group(PresenceGroup(userId)).SendAsync("WritingWorkspacePresenceChanged", status); - return status; - } - - public async Task RequestWritingWindowFocus(WritingWorkspaceScope scope, string role) - { - var userId = RequireUserId(); - var connectionId = await writingPresence.GetConnectionIdForRoleAsync(userId, scope, role); - if (!string.IsNullOrWhiteSpace(connectionId)) - { - await Clients.Client(connectionId).SendAsync("WritingWorkspaceFocusRequested", new - { - WritingRole = WritingWorkspaceRoles.Normalise(role), - scope.ProjectID, - scope.BookID - }); - } - - return await WritingWorkspaceStatusAsync(userId, scope); - } - public Task StartOnboardingManuscriptScan()=>StartManuscriptScan(false); public Task StartParagraphManuscriptScan()=>StartManuscriptScan(true); private async Task StartManuscriptScan(bool paragraphs) @@ -418,13 +364,11 @@ public sealed class WordCompanionFollowHub( public override async Task OnDisconnectedAsync(Exception? exception) { - int? disconnectedUserId = null; var status = await presence.DisconnectAsync(Context.ConnectionId); if (status is not null) { - disconnectedUserId = status.UserID; await Clients.Group(PresenceGroup(status.UserID)).SendAsync("WordCompanionPresenceChanged", status); - await BroadcastWritingWorkspaceStatusAsync(status.UserID, status.LinkedProjectID, status.LinkedBookID); + if(contextNotifications!=null)await contextNotifications.Position(status.UserID); var failedScans = await scanStore.FailRunningForUserAsync( status.UserID, "The Word Companion disconnected before the scan finished. Reopen Word and try again."); @@ -434,14 +378,6 @@ public sealed class WordCompanionFollowHub( } } - var writingStatus = await writingPresence.DisconnectAsync( - Context.ConnectionId, - disconnectedUserId.HasValue ? await presence.GetStatusAsync(disconnectedUserId.Value) : null); - if (writingStatus is not null) - { - await Clients.Group(PresenceGroup(writingStatus.UserID)).SendAsync("WritingWorkspacePresenceChanged", writingStatus); - } - await base.OnDisconnectedAsync(exception); } @@ -455,19 +391,6 @@ public sealed class WordCompanionFollowHub( } return await presence.GetStatusAsync(userId); } - private async Task WritingWorkspaceStatusAsync(int userId, WritingWorkspaceScope scope) - => await writingPresence.GetStatusAsync(userId, scope, await CombinedPresence(userId)); - - private async Task BroadcastWritingWorkspaceStatusAsync(int userId, int? projectId, int? bookId) - { - var workspaceStatus = await WritingWorkspaceStatusAsync(userId, new WritingWorkspaceScope - { - ProjectID = projectId, - BookID = bookId - }); - await Clients.Group(PresenceGroup(userId)).SendAsync("WritingWorkspacePresenceChanged", workspaceStatus); - } - private int RequireUserId() => TryGetUserId(out var userId) ? userId : throw new HubException("Sign in to use the Word Companion."); diff --git a/PlotLine/Models/WritingWorkspacePresenceModels.cs b/PlotLine/Models/WritingWorkspacePresenceModels.cs deleted file mode 100644 index 8ac92a2f..00000000 --- a/PlotLine/Models/WritingWorkspacePresenceModels.cs +++ /dev/null @@ -1,76 +0,0 @@ -namespace PlotLine.Models; - -public static class WritingWorkspaceRoles -{ - public const string None = "None"; - public const string Launcher = "Launcher"; - public const string Context = "Context"; - public const string Intent = "Intent"; - - public static string Normalise(string? role) - { - var value = (role ?? string.Empty).Trim(); - return value.Equals(Launcher, StringComparison.OrdinalIgnoreCase) ? Launcher - : value.Equals(Context, StringComparison.OrdinalIgnoreCase) ? Context - : value.Equals(Intent, StringComparison.OrdinalIgnoreCase) ? Intent - : None; - } -} - -public sealed class WritingWorkspaceScope -{ - public int? ProjectID { get; init; } - public int? BookID { get; init; } -} - -public sealed class WritingWindowRegistration -{ - public string? BrowserWindowID { get; init; } - public int? ProjectID { get; init; } - public int? BookID { get; init; } - public string? CurrentRoute { get; init; } - public string? WritingRole { get; init; } - public string? DisplayLabel { get; init; } -} - -public sealed class WritingWindowHeartbeat -{ - public string? BrowserWindowID { get; init; } - public int? ProjectID { get; init; } - public int? BookID { get; init; } - public string? CurrentRoute { get; init; } - public string? WritingRole { get; init; } - public string? DisplayLabel { get; init; } -} - -public sealed class WritingWindowPresence -{ - public string BrowserWindowID { get; init; } = string.Empty; - public int UserID { get; init; } - public int? ProjectID { get; init; } - public int? BookID { get; init; } - public string CurrentRoute { get; init; } = string.Empty; - public string WritingRole { get; init; } = WritingWorkspaceRoles.None; - public string? DisplayLabel { get; init; } - public bool IsActive { get; init; } - public DateTime ConnectedUtc { get; init; } - public DateTime LastSeenUtc { get; init; } -} - -public sealed class WritingWorkspaceStatus -{ - public int UserID { get; init; } - public int? ProjectID { get; init; } - public int? BookID { get; init; } - public bool WordCompanionConnected { get; init; } - public bool WordDocumentOpen { get; init; } - public int? WordProjectID { get; init; } - public int? WordBookID { get; init; } - public StoryPosition? CurrentStoryPosition { get; init; } - public IReadOnlyList Windows { get; init; } = []; - public WritingWindowPresence? Launcher { get; init; } - public WritingWindowPresence? Context { get; init; } - public WritingWindowPresence? Intent { get; init; } - public bool ContextOpen => Context?.IsActive == true; - public bool IntentOpen => Intent?.IsActive == true; -} diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 0eb4d612..f9482b58 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -29,6 +29,7 @@ public class Program { options.Filters.Add(); options.Filters.Add(); + options.Filters.Add(); options.Filters.Add(); }); builder.Services.AddSignalR(options => @@ -287,7 +288,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); - builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); diff --git a/PlotLine/Services/ContextReferenceInvalidationFilter.cs b/PlotLine/Services/ContextReferenceInvalidationFilter.cs new file mode 100644 index 00000000..af4458e7 --- /dev/null +++ b/PlotLine/Services/ContextReferenceInvalidationFilter.cs @@ -0,0 +1,19 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +namespace PlotLine.Services; + +// Existing editor saves invalidate reference reads; no capture, analysis or navigation is started. +public sealed class ContextReferenceInvalidationFilter(ContextWorkspaceNotifications notifications, ICurrentUserService currentUser) : IAsyncActionFilter +{ + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + var result = await next(); + var controller = context.RouteData.Values["controller"]?.ToString(); + if (controller == "Writer" && context.RouteData.Values["action"]?.ToString() != "SaveChapterGoal") return; + if (!HttpMethods.IsPost(context.HttpContext.Request.Method) || controller is not ("Scenes" or "Writer") || + currentUser.UserId is not int user || result.Exception != null || !context.ModelState.IsValid) return; + if (result.Result is ForbidResult or ChallengeResult) return; + var status = result.Result switch { ObjectResult value => value.StatusCode ?? 200, StatusCodeResult value => value.StatusCode, _ => 200 }; + if (status < 400) await notifications.Invalidate(user); + } +} diff --git a/PlotLine/Services/ContextWorkspaceNotifications.cs b/PlotLine/Services/ContextWorkspaceNotifications.cs new file mode 100644 index 00000000..f0010070 --- /dev/null +++ b/PlotLine/Services/ContextWorkspaceNotifications.cs @@ -0,0 +1,16 @@ +using Microsoft.AspNetCore.SignalR; +using PlotLine.Hubs; +namespace PlotLine.Services; + +// Presentation hints only. A notification failure must never turn a durable save into a failed write. +public sealed class ContextWorkspaceNotifications(IHubContext hub, ILogger logger) +{ + public Task Position(int user) => Send(user, "ContextPositionChanged", new { }); + public Task Invalidate(int user, int? bookId = null, int? chapterId = null, int? sceneId = null) + => Send(user, "ContextInvalidated", new { bookId, chapterId, sceneId }); + private async Task Send(int user, string name, object hint) + { + try { await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync(name, hint); } + catch (Exception exception) { logger.LogWarning("Context notification unavailable: {Category}", exception.GetType().Name); } + } +} diff --git a/PlotLine/Services/Manuscript/ParagraphManuscriptService.cs b/PlotLine/Services/Manuscript/ParagraphManuscriptService.cs index ffa6d33a..239aac88 100644 --- a/PlotLine/Services/Manuscript/ParagraphManuscriptService.cs +++ b/PlotLine/Services/Manuscript/ParagraphManuscriptService.cs @@ -4,7 +4,7 @@ using PlotDirector.Companion.Protocol.Manuscript; using PlotLine.Data; using PlotLine.Models; namespace PlotLine.Services.Manuscript; -public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository repository,IWordCompanionRepository access,IBookRepository books,IOnboardingBuildRepository imports,IManuscriptTextStatisticsService statistics,IConfiguration configuration,ILogger? logger=null) +public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository repository,IWordCompanionRepository access,IBookRepository books,IOnboardingBuildRepository imports,IManuscriptTextStatisticsService statistics,IConfiguration configuration,ILogger? logger=null,PlotLine.Services.ContextWorkspaceNotifications? contextNotifications=null) { public bool Enabled=>configuration.GetValue("Features:ParagraphManuscripts"); private void RequireFeature(){if(!Enabled)throw new InvalidOperationException("Paragraph synchronisation is not enabled on this server.");} @@ -110,6 +110,7 @@ public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository re ParagraphManuscriptEngine.Validate(state);if(state.Chapters.Count>0)state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,expected+1).ToList();var result=chapter.HasValue?await repository.SaveChapterWithActivity(user,state,expected,request,chapter.Value,activitySession??Guid.Empty):await repository.Save(user,state,expected,request); // Reuse deterministic continuity/statistics; never schedule whole-book AI. try{if(chapter.HasValue)await statistics.RecalculateChapterAsync(chapter.Value);else await statistics.RecalculateBookAsync(state.BookId);}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or InvalidOperationException){logger?.LogWarning("Manuscript revision {Revision} committed; derived statistics require refresh ({FailureKind}).",result.Revision,e.GetType().Name);} + if(contextNotifications!=null)await contextNotifications.Invalidate(user,state.BookId,chapter); return result; } } diff --git a/PlotLine/Services/WordCompanionPresenceMonitor.cs b/PlotLine/Services/WordCompanionPresenceMonitor.cs index 717f6482..91851ce7 100644 --- a/PlotLine/Services/WordCompanionPresenceMonitor.cs +++ b/PlotLine/Services/WordCompanionPresenceMonitor.cs @@ -1,14 +1,13 @@ using Microsoft.AspNetCore.SignalR; using PlotLine.Hubs; -using PlotLine.Models; namespace PlotLine.Services; public sealed class WordCompanionPresenceMonitor( IWordCompanionPresenceService presence, - IWritingWorkspacePresenceService writingPresence, IManuscriptScanPreviewStore scanStore, - IHubContext hub) : BackgroundService + IHubContext hub, + ContextWorkspaceNotifications? contextNotifications = null) : BackgroundService { private static readonly TimeSpan ActiveScanHeartbeatGrace = TimeSpan.FromMinutes(30); @@ -23,41 +22,17 @@ public sealed class WordCompanionPresenceMonitor( scanStore.HasRecentRunningScanForUserAsync(userId, ActiveScanHeartbeatGrace)); foreach (var status in offlineStatuses) { - await hub.Clients - .Group(PresenceGroup(status.UserID)) + await hub.Clients.Group(WordCompanionFollowHub.PresenceGroup(status.UserID)) .SendAsync("WordCompanionPresenceChanged", status, stoppingToken); - var workspaceStatus = await writingPresence.GetStatusAsync(status.UserID, new WritingWorkspaceScope - { - ProjectID = status.LinkedProjectID, - BookID = status.LinkedBookID - }, status); - await hub.Clients - .Group(PresenceGroup(status.UserID)) - .SendAsync("WritingWorkspacePresenceChanged", workspaceStatus, stoppingToken); - var failedScans = await scanStore.FailRunningForUserAsync( - status.UserID, + if (contextNotifications != null) await contextNotifications.Position(status.UserID); + var failedScans = await scanStore.FailRunningForUserAsync(status.UserID, "The Word Companion disconnected before the scan finished. Reopen Word and try again."); foreach (var failedScan in failedScans) - { - await hub.Clients - .Group(PresenceGroup(status.UserID)) + await hub.Clients.Group(WordCompanionFollowHub.PresenceGroup(status.UserID)) .SendAsync("OnboardingScanFailed", failedScan, stoppingToken); - } - } - } - - var staleWorkspaceStatuses = await writingPresence.MarkStaleOfflineAsync(presence.GetStatusAsync); - foreach (var workspaceStatus in staleWorkspaceStatuses) - { - await hub.Clients - .Group(PresenceGroup(workspaceStatus.UserID)) - .SendAsync("WritingWorkspacePresenceChanged", workspaceStatus, stoppingToken); } } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { } } - - private static string PresenceGroup(int userId) => $"word-companion-presence:{userId}"; } diff --git a/PlotLine/Services/WritingWorkspacePresenceService.cs b/PlotLine/Services/WritingWorkspacePresenceService.cs deleted file mode 100644 index d42396f5..00000000 --- a/PlotLine/Services/WritingWorkspacePresenceService.cs +++ /dev/null @@ -1,218 +0,0 @@ -using System.Collections.Concurrent; -using PlotLine.Models; - -namespace PlotLine.Services; - -public interface IWritingWorkspacePresenceService -{ - Task RegisterAsync(int userId, string connectionId, WritingWindowRegistration registration, WordCompanionPresenceStatus wordStatus); - Task HeartbeatAsync(int userId, string connectionId, WritingWindowHeartbeat heartbeat, WordCompanionPresenceStatus wordStatus); - Task DisconnectAsync(string connectionId, WordCompanionPresenceStatus? wordStatus); - Task GetStatusAsync(int userId, WritingWorkspaceScope scope, WordCompanionPresenceStatus wordStatus); - Task> MarkStaleOfflineAsync(Func> wordStatusForUser); - Task GetConnectionIdForRoleAsync(int userId, WritingWorkspaceScope scope, string role); -} - -public sealed class WritingWorkspacePresenceService : IWritingWorkspacePresenceService -{ - private static readonly TimeSpan ActiveTimeout = TimeSpan.FromSeconds(45); - private readonly ConcurrentDictionary windowsById = new(StringComparer.Ordinal); - private readonly ConcurrentDictionary windowIdsByConnection = new(StringComparer.Ordinal); - - public Task RegisterAsync(int userId, string connectionId, WritingWindowRegistration registration, WordCompanionPresenceStatus wordStatus) - { - var now = DateTime.UtcNow; - var windowId = Clean(registration.BrowserWindowID); - if (windowId is null) - { - windowId = Guid.NewGuid().ToString("N"); - } - - var record = windowsById.AddOrUpdate( - WindowKey(userId, windowId), - _ => new WindowRecord - { - BrowserWindowID = windowId, - UserID = userId, - ConnectedUtc = now - }, - (_, existing) => existing); - - Apply(record, connectionId, registration.ProjectID, registration.BookID, registration.CurrentRoute, registration.WritingRole, registration.DisplayLabel, now); - windowIdsByConnection[connectionId] = WindowKey(userId, windowId); - return Task.FromResult(BuildStatus(userId, new WritingWorkspaceScope { ProjectID = record.ProjectID, BookID = record.BookID }, wordStatus)); - } - - public Task HeartbeatAsync(int userId, string connectionId, WritingWindowHeartbeat heartbeat, WordCompanionPresenceStatus wordStatus) - { - var registration = new WritingWindowRegistration - { - BrowserWindowID = heartbeat.BrowserWindowID, - ProjectID = heartbeat.ProjectID, - BookID = heartbeat.BookID, - CurrentRoute = heartbeat.CurrentRoute, - WritingRole = heartbeat.WritingRole, - DisplayLabel = heartbeat.DisplayLabel - }; - return RegisterAsync(userId, connectionId, registration, wordStatus); - } - - public Task DisconnectAsync(string connectionId, WordCompanionPresenceStatus? wordStatus) - { - if (!windowIdsByConnection.TryRemove(connectionId, out var key) - || !windowsById.TryGetValue(key, out var record) - || !string.Equals(record.ConnectionID, connectionId, StringComparison.Ordinal)) - { - return Task.FromResult(null); - } - - record.IsActive = false; - record.ConnectionID = string.Empty; - var status = BuildStatus(record.UserID, new WritingWorkspaceScope { ProjectID = record.ProjectID, BookID = record.BookID }, wordStatus ?? new WordCompanionPresenceStatus { UserID = record.UserID }); - return Task.FromResult(status); - } - - public Task GetStatusAsync(int userId, WritingWorkspaceScope scope, WordCompanionPresenceStatus wordStatus) - => Task.FromResult(BuildStatus(userId, scope, wordStatus)); - - public async Task> MarkStaleOfflineAsync(Func> wordStatusForUser) - { - var now = DateTime.UtcNow; - var changedScopes = new Dictionary(StringComparer.Ordinal); - foreach (var record in windowsById.Values) - { - if (!record.IsActive || now - record.LastSeenUtc <= ActiveTimeout) - { - continue; - } - - record.IsActive = false; - if (!string.IsNullOrWhiteSpace(record.ConnectionID)) - { - windowIdsByConnection.TryRemove(record.ConnectionID, out _); - record.ConnectionID = string.Empty; - } - - changedScopes[ScopeKey(record.UserID, record.ProjectID, record.BookID)] = (record.UserID, record.ProjectID, record.BookID); - } - - var statuses = new List(); - foreach (var scope in changedScopes.Values) - { - var wordStatus = await wordStatusForUser(scope.UserID); - statuses.Add(BuildStatus(scope.UserID, new WritingWorkspaceScope { ProjectID = scope.ProjectID, BookID = scope.BookID }, wordStatus)); - } - - return statuses; - } - - public Task GetConnectionIdForRoleAsync(int userId, WritingWorkspaceScope scope, string role) - { - var normalRole = WritingWorkspaceRoles.Normalise(role); - var now = DateTime.UtcNow; - var record = ActiveWindows(userId, scope, now) - .Where(window => string.Equals(window.WritingRole, normalRole, StringComparison.Ordinal)) - .OrderByDescending(window => window.LastSeenUtc) - .FirstOrDefault(); - return Task.FromResult(record?.ConnectionID); - } - - private static void Apply(WindowRecord record, string connectionId, int? projectId, int? bookId, string? route, string? role, string? displayLabel, DateTime now) - { - record.ConnectionID = connectionId; - record.ProjectID = Positive(projectId); - record.BookID = Positive(bookId); - record.CurrentRoute = Clean(route) ?? "/"; - record.WritingRole = WritingWorkspaceRoles.Normalise(role); - record.DisplayLabel = Clean(displayLabel); - record.IsActive = true; - record.LastSeenUtc = now; - } - - private WritingWorkspaceStatus BuildStatus(int userId, WritingWorkspaceScope scope, WordCompanionPresenceStatus wordStatus) - { - var now = DateTime.UtcNow; - var windows = ActiveWindows(userId, scope, now) - .Select(ToPresence) - .OrderBy(window => window.WritingRole) - .ThenByDescending(window => window.LastSeenUtc) - .ToList(); - - return new WritingWorkspaceStatus - { - UserID = userId, - ProjectID = Positive(scope.ProjectID) ?? Positive(wordStatus.LinkedProjectID), - BookID = Positive(scope.BookID) ?? Positive(wordStatus.LinkedBookID), - WordCompanionConnected = wordStatus.IsConnected, - WordDocumentOpen = wordStatus.DocumentOpen, - WordProjectID = wordStatus.LinkedProjectID, - WordBookID = wordStatus.LinkedBookID, - CurrentStoryPosition = wordStatus.CurrentStoryPosition, - Windows = windows, - Launcher = LatestRole(windows, WritingWorkspaceRoles.Launcher), - Context = LatestRole(windows, WritingWorkspaceRoles.Context), - Intent = LatestRole(windows, WritingWorkspaceRoles.Intent) - }; - } - - private IEnumerable ActiveWindows(int userId, WritingWorkspaceScope scope, DateTime now) - { - var projectId = Positive(scope.ProjectID); - var bookId = Positive(scope.BookID); - return windowsById.Values.Where(record => - record.UserID == userId - && record.IsActive - && now - record.LastSeenUtc <= ActiveTimeout - && (!projectId.HasValue || record.ProjectID == projectId) - && (!bookId.HasValue || record.BookID == bookId)); - } - - private static WritingWindowPresence? LatestRole(IReadOnlyList windows, string role) - => windows - .Where(window => string.Equals(window.WritingRole, role, StringComparison.Ordinal)) - .OrderByDescending(window => window.LastSeenUtc) - .FirstOrDefault(); - - private static WritingWindowPresence ToPresence(WindowRecord record) - => new() - { - BrowserWindowID = record.BrowserWindowID, - UserID = record.UserID, - ProjectID = record.ProjectID, - BookID = record.BookID, - CurrentRoute = record.CurrentRoute, - WritingRole = record.WritingRole, - DisplayLabel = record.DisplayLabel, - IsActive = record.IsActive, - ConnectedUtc = record.ConnectedUtc, - LastSeenUtc = record.LastSeenUtc - }; - - private static string? Clean(string? value) - { - var cleaned = (value ?? string.Empty).Trim(); - return string.IsNullOrWhiteSpace(cleaned) ? null : cleaned; - } - - private static int? Positive(int? value) - => value is > 0 ? value.Value : null; - - private static string WindowKey(int userId, string windowId) => $"{userId}:{windowId}"; - - private static string ScopeKey(int userId, int? projectId, int? bookId) => $"{userId}:{projectId ?? 0}:{bookId ?? 0}"; - - private sealed class WindowRecord - { - public string BrowserWindowID { get; init; } = string.Empty; - public int UserID { get; init; } - public string ConnectionID { get; set; } = string.Empty; - public int? ProjectID { get; set; } - public int? BookID { get; set; } - public string CurrentRoute { get; set; } = "/"; - public string WritingRole { get; set; } = WritingWorkspaceRoles.None; - public string? DisplayLabel { get; set; } - public bool IsActive { get; set; } - public DateTime ConnectedUtc { get; init; } - public DateTime LastSeenUtc { get; set; } - } -} diff --git a/PlotLine/Views/NativeWorkspace/Workspace.cshtml b/PlotLine/Views/NativeWorkspace/Workspace.cshtml index 515e9163..1ed28b6d 100644 --- a/PlotLine/Views/NativeWorkspace/Workspace.cshtml +++ b/PlotLine/Views/NativeWorkspace/Workspace.cshtml @@ -6,8 +6,8 @@

Saved workspace · waiting for a current Word scene

Checking Companion presence…

-

Connection diagnostics only. Open Context or Intent to follow the manuscript and navigate saved scenes.

- +

Connection diagnostics only. Open Context to follow the manuscript and navigate saved scenes.

+ @if(Model.Mode=="book"){

AI chapter suggestions

Generated by PlotDirector’s existing chapter-analysis service. Review titles and summaries before any import. Successful chapters remain available for 30 days.

diff --git a/PlotLine/Views/WordCompanionHost/Index.cshtml b/PlotLine/Views/WordCompanionHost/Index.cshtml index 9f6fce6a..76d0200a 100644 --- a/PlotLine/Views/WordCompanionHost/Index.cshtml +++ b/PlotLine/Views/WordCompanionHost/Index.cshtml @@ -123,7 +123,7 @@
- +
diff --git a/PlotLine/Views/Writer/Legacy.cshtml b/PlotLine/Views/Writer/Legacy.cshtml index 0a6fb880..fe0da210 100644 --- a/PlotLine/Views/Writer/Legacy.cshtml +++ b/PlotLine/Views/Writer/Legacy.cshtml @@ -25,7 +25,7 @@
@if(!string.IsNullOrWhiteSpace(Model.Book?.CoverThumbnailPath)){Cover of @bookTitle}else{}

@(Model.Journey?"Writing Journey":showWorkspace?"Workflow":"Legacy writing tools")

@(showWorkspace?"Scene queues":bookTitle)

@(Model.Journey?"Accepted activity and the work ahead.":"Continue your manuscript, review your work, or choose what comes next.")

-
Companion Checking…Connection & Display Setup
+
@if(TempData["WriterWorkspaceMessage"] is string message){

@message

} @if(TempData["WriterWorkspaceError"] is string error){} @@ -95,13 +95,7 @@ else @if(Model.WritingSchedule.TodayTasks.Count>0){
Today's planned writing · @Model.WritingSchedule.TodayTasks.Count tasks@foreach(var task in Model.WritingSchedule.TodayTasks){
@task.SceneTitle@task.TaskType · @task.EstimatedMinutes estimated minutes
}

Task completion is author-declared, not measured writing time.

} -
Word Companion & Display Setup -

Open Context and Intent as reference windows. Linked Word controls appear when a document is connected. Display placement depends on browser permission and popup support; moving Word itself is controlled by Windows.

-
Selected book Waiting for Word
Context Checking…
Intent Checking…
Layout Adaptive
-

Choose reference windows or detect displays.

-
-
-
+
Word Companion and Context

Open independent Context windows. Choose single, side-by-side or stacked panes inside each window.

@section Scripts { diff --git a/PlotLine/Views/Writer/_WriterWrite.cshtml b/PlotLine/Views/Writer/_WriterWrite.cshtml index fa5cc2f0..e8ba7c51 100644 --- a/PlotLine/Views/Writer/_WriterWrite.cshtml +++ b/PlotLine/Views/Writer/_WriterWrite.cshtml @@ -28,13 +28,13 @@ else{

Work-session evidence is private to the book owner. Your chapter and scene tools remain available.

} diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index af49ca58..96c54757 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -1,52 +1,46 @@ @model WritingContextPageViewModel +@using System.Text.Json @{ - if(ViewData["WritingEmbedded"] is true) Layout="_WritingCompanionLayout"; - ViewData["Title"] = "Writing Context"; - ViewData["ProjectSection"] = "Writer"; + Layout = "_WritingCompanionLayout"; + ViewData["Title"] = "Context"; + var position = Model.Display?.Context?.Position; + var tabs = new[] { + new { id = "overview", displayName = "Overview", endpoint = Url.Action("ContextScene", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "reference", refreshGuard = "defer-while-dirty-or-busy" }, + new { id = "characters", displayName = "Characters in Scene", endpoint = Url.Action("ContextCharacters", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "reference", refreshGuard = "defer-while-dirty-or-busy" } + }; } - - - -
+
- -
-

Writing Context

-

Writing Context

-
- @(Model.Display?.FollowStatus ?? "Connected, waiting for scene") -
- + data-word-instance="@ViewData["WordInstance"]" data-word-session="@ViewData["WordSession"]"> + +
+

Context

+ + + +

@(Model.Display?.FollowStatus ?? "Waiting for a saved scene")

- -
- -
+ +
+ @for(var pane = 0; pane < 2; pane++) { + @if(pane == 1){} + + } +
- @section Scripts { - - - - - - - + } diff --git a/PlotLine/Views/Writing/Intent.cshtml b/PlotLine/Views/Writing/Intent.cshtml deleted file mode 100644 index 520c6dc5..00000000 --- a/PlotLine/Views/Writing/Intent.cshtml +++ /dev/null @@ -1,51 +0,0 @@ -@model WritingIntentPageViewModel -@{ - if(ViewData["WritingEmbedded"] is true) Layout="_WritingCompanionLayout"; - ViewData["Title"] = "Writing Intent"; - ViewData["ProjectSection"] = "Writer"; -} - -
- -
-
-

Writing Intent

-

Writing Intent

-
-
- @(Model.Display?.FollowStatus ?? "Connected, waiting for scene") -
-
- @(ViewData["NativeSnapshot"] is true ? "Saved PlotDirector snapshot · manual navigation · no automatic save" : "Writing Workspace") -
-
- -
- -
-
- -@section Scripts { - - - - - -} diff --git a/PlotLine/Views/Writing/_ContextTab.cshtml b/PlotLine/Views/Writing/_ContextTab.cshtml new file mode 100644 index 00000000..39ec7d2a --- /dev/null +++ b/PlotLine/Views/Writing/_ContextTab.cshtml @@ -0,0 +1,5 @@ +@model WritingContextDisplayViewModel +
+

@Model.Context?.Scene?.SceneTitle

+ +
diff --git a/PlotLine/Views/Writing/_WritingContextContent.cshtml b/PlotLine/Views/Writing/_WritingContextContent.cshtml deleted file mode 100644 index 38483bb1..00000000 --- a/PlotLine/Views/Writing/_WritingContextContent.cshtml +++ /dev/null @@ -1,93 +0,0 @@ -@model WritingContextDisplayViewModel -@{ - var scene = Model.Context?.Scene; - var position = Model.Context?.Position; - var sequence=Model.SceneOptions.ToList(); - var current=sequence.FindIndex(x=>x.Value==scene?.SceneID.ToString()); -} - -
- @if (scene is null) - { -
-

Context

-

@Model.EmptyTitle

-

@Model.EmptyMessage

-
- } - else - { -
-
-

@scene.Project?.ProjectName

-

@scene.SceneTitle

-

- @scene.Book?.BookDisplayTitle - - Chapter @(scene.Chapter?.ChapterNumber.ToString("0.##")) - - Scene @(scene.SceneNumber.ToString("0.##")) - @if(current>=0){· Manuscript scene @(current+1) of @sequence.Count} -

-
-
-
- - -
- - - Open Scene -
-
- - - -
- - - -
- -
- - - - -
- } -
diff --git a/PlotLine/Views/Writing/_WritingIntentContent.cshtml b/PlotLine/Views/Writing/_WritingIntentContent.cshtml deleted file mode 100644 index 02bcc80e..00000000 --- a/PlotLine/Views/Writing/_WritingIntentContent.cshtml +++ /dev/null @@ -1,121 +0,0 @@ -@model WritingIntentDisplayViewModel -@{ - var scene = Model.Context?.Scene; - var position = Model.Context?.Position; - var workflow = Model.ChapterWorkflow; - var chapter = workflow?.Chapter ?? Model.Context?.Chapter; - var book = workflow?.Book ?? Model.Context?.Book; - var project = workflow?.Project ?? Model.Context?.Project; - var projectId = position?.ProjectId ?? project?.ProjectID; - var bookId = position?.BookId ?? book?.BookID; - var chapterId = position?.ChapterId ?? chapter?.ChapterID; - var sceneId = position?.SceneId; -} - -
- @if (!Model.HasChapter && scene is null) - { -
-

Intent

-

@Model.EmptyTitle

-

@Model.EmptyMessage

-
- } - else - { -
-
-

@project?.ProjectName

-

@(scene?.SceneTitle ?? $"Chapter {chapter?.ChapterNumber:g}: {chapter?.ChapterTitle}")

-

- @book?.BookDisplayTitle - @if (chapter is not null) - { - - Chapter @(chapter.ChapterNumber.ToString("0.##")) - } - @if (scene is not null) - { - - Scene @(scene.SceneNumber.ToString("0.##")) - } -

- @if (Model.IsChapterOnly) - { -

No current scene. Showing chapter intent.

- } - else if (scene is not null && string.IsNullOrWhiteSpace(scene.Summary) && string.IsNullOrWhiteSpace(scene.ScenePurposeNotes) && !scene.ChecklistItems.Any()) - { -

No scene-specific plan. Showing chapter intent.

- } -
-
- @if (chapter is not null) - { - - - } - - - @if (scene is not null) - { - Edit Scene - } - else if (chapter is not null) - { - Edit Chapter Plan - } -
-
- - - -
-
- -
- - - - - -
- } -
diff --git a/PlotLine/wwwroot/css/context-workspace.css b/PlotLine/wwwroot/css/context-workspace.css new file mode 100644 index 00000000..74481b39 --- /dev/null +++ b/PlotLine/wwwroot/css/context-workspace.css @@ -0,0 +1,34 @@ +/* The parent owns the viewport. Each pane owns its scrolling and container sizing. */ +body.writing-embedded:has([data-context-workspace]) { height:100dvh; display:flex; flex-direction:column; overflow:hidden; padding:.5rem; } +body:has([data-context-workspace])>.writing-window-bar { flex:none; } +.context-workspace { flex:1; min-height:0; min-width:0; display:flex; flex-direction:column; gap:.5rem; color:var(--plotline-ink); } +.context-toolbar,.context-navigation,.context-pane-toolbar { display:flex; flex-wrap:wrap; align-items:center; gap:.5rem; min-width:0; } +.context-toolbar h1 { font-size:1.25rem; margin:0 auto 0 0; } +.context-toolbar label,.context-pane-toolbar label { display:flex; gap:.5rem; align-items:center; min-width:0; } +.context-toolbar p { flex-basis:100%; margin:0; font-size:.85rem; overflow-wrap:anywhere; } +.context-navigation label { flex:1 1 16rem; min-width:0; display:flex; gap:.5rem; align-items:center; } +.context-navigation select { min-width:0; width:100%; } +.context-panes { --context-first:50%; flex:1; min-height:0; min-width:0; display:grid; overflow:hidden; } +.context-panes[data-layout=single] { grid-template-columns:minmax(0,1fr); grid-template-rows:minmax(0,1fr); } +.context-panes[data-layout=columns] { grid-template-columns:minmax(0,var(--context-first)) .75rem minmax(0,1fr); grid-template-rows:minmax(0,1fr); } +.context-panes[data-layout=rows] { grid-template-rows:minmax(0,var(--context-first)) .75rem minmax(0,1fr); grid-template-columns:minmax(0,1fr); } +.context-pane { min-width:0; min-height:0; display:flex; flex-direction:column; overflow:hidden; border:1px solid var(--plotline-line); border-radius:.6rem; background:var(--plotline-panel); } +.context-pane[hidden],[data-context-divider][hidden] { display:none; } +.context-pane-toolbar { flex:none; padding:.5rem; border-bottom:1px solid var(--plotline-line); } +.context-pane-toolbar label { width:100%; } +.context-pane-toolbar select { flex:1; min-width:0; } +.context-pane-status { flex:none; font-size:.82rem; margin:0; padding:0 .65rem; overflow-wrap:anywhere; } +.context-pane-content { flex:1; min-height:0; min-width:0; overflow:auto; padding:.65rem; container-type:inline-size; scrollbar-gutter:stable; overflow-wrap:anywhere; } +.context-pane-content .writing-context-grid,.context-pane-content .writing-context-people-grid { grid-template-columns:minmax(0,1fr); gap:.65rem; } +.context-pane-content .writing-context-card--hero,.context-pane-content .writing-context-card--wide { grid-column:auto; } +.context-pane-content .writing-context-card { padding:.8rem; } +.context-pane-content .writing-context-empty { min-height:0; padding:1rem; } +.context-pane-content .writing-context-facts { grid-template-columns:minmax(0,.4fr) minmax(0,1fr); } +.context-pane-content img { max-width:100%; } +.context-pane-content nav { flex-wrap:wrap; } +[data-context-divider] { touch-action:none; cursor:col-resize; border-radius:.3rem; background:var(--plotline-line); margin:.15rem; } +[data-layout=rows]>[data-context-divider] { cursor:row-resize; } +[data-context-divider]:focus-visible { outline:3px solid var(--plotline-accent); outline-offset:-3px; } +@container (min-width:700px) { .context-pane-content .writing-context-grid,.context-pane-content .writing-context-people-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } .context-pane-content .writing-context-card--hero,.context-pane-content .writing-context-card--wide { grid-column:span 2; } } +@container (max-width:320px) { .context-pane-content .writing-context-facts { grid-template-columns:minmax(0,1fr); gap:.2rem; } .context-pane-content .writing-context-facts dd { margin-bottom:.5rem; } } +@media(max-height:500px) { .context-toolbar,.context-navigation { gap:.25rem; } .context-toolbar p { font-size:.75rem; } } diff --git a/PlotLine/wwwroot/css/site.css b/PlotLine/wwwroot/css/site.css index 96db8001..feb55289 100644 --- a/PlotLine/wwwroot/css/site.css +++ b/PlotLine/wwwroot/css/site.css @@ -3,46 +3,6 @@ html { min-height: 100%; } -.writing-context-page { - min-height: calc(100vh - 8rem); - color: var(--plotline-ink); -} - -.writing-context-shell-header, -.writing-context-scene-header { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 1.5rem; - margin-bottom: 1rem; -} - -.writing-context-shell-header h1, -.writing-context-scene-header h2 { - margin: 0; -} - -.writing-context-status { - display: inline-flex; - align-items: center; - gap: .5rem; - padding: .4rem .65rem; - border: 1px solid var(--plotline-line); - border-radius: 999px; - background: var(--plotline-panel); - color: var(--plotline-muted); - font-size: .9rem; - white-space: nowrap; -} - -.writing-context-status-dot { - width: .55rem; - height: .55rem; - border-radius: 50%; - background: #2f8f63; - box-shadow: 0 0 0 .18rem rgba(47, 143, 99, .15); -} - .writing-context-empty { min-height: 42vh; display: grid; @@ -54,57 +14,6 @@ html { background: var(--plotline-panel); } -.writing-context-scene-header { - padding: 1rem 0 1.2rem; - border-bottom: 1px solid var(--plotline-line); -} - -.writing-context-scene-header p { - margin: .35rem 0 0; - color: var(--plotline-muted); -} - -.writing-context-scene-actions { - display: grid; - grid-template-columns: minmax(18rem, 28rem) auto; - gap: .5rem; - align-items: end; -} - -.writing-context-scene-actions label { - grid-column: 1 / -1; - margin: 0; - color: var(--plotline-muted); - font-size: .82rem; - font-weight: 700; -} - -.writing-context-tabs { - display: flex; - flex-wrap: wrap; - gap: .35rem; - margin: 1rem 0; -} - -.writing-context-tabs button { - border: 1px solid var(--plotline-line); - border-radius: .4rem; - background: var(--plotline-panel); - color: var(--plotline-ink); - padding: .55rem .85rem; - font-weight: 700; -} - -.writing-context-tabs button.active { - background: var(--plotline-accent); - border-color: var(--plotline-accent); - color: #fff; -} - -.writing-context-tab-panel[hidden] { - display: none; -} - .writing-context-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); @@ -301,12 +210,6 @@ html { } @media (max-width: 900px) { - .writing-context-shell-header, - .writing-context-scene-header { - display: grid; - } - - .writing-context-scene-actions, .writing-context-grid, .writing-context-grid--overview, .writing-context-grid--place { @@ -4412,20 +4315,6 @@ body.dragging-location [data-drag-type="location"] { font-weight: 700; } -.writing-workspace-role-indicator { - display: inline-flex; - align-items: center; - gap: 0.5rem; - padding: 0.4rem 0.65rem; - border: 1px solid rgba(47, 111, 99, 0.22); - border-radius: 999px; - background: var(--plotline-soft); - color: var(--plotline-accent-dark); - font-size: 0.9rem; - font-weight: 700; - white-space: nowrap; -} - .writer-queue-card { border: 1px solid var(--plotline-line); border-radius: 12px; @@ -7684,25 +7573,18 @@ html[data-standalone="true"] .plotline-shell.location-workspace-shell { .cover-navigation:focus-visible { outline: 3px solid var(--bs-primary); outline-offset: -3px; } /* Independent writing screens: reuse existing renderers without nested application chrome. */ -.writing-embedded{margin:0;padding:.75rem;min-width:0}.writing-embedded .writing-context-page{width:100%;max-width:none;margin:0}.writing-embedded .writing-context-shell-header{padding:.35rem 0;gap:.5rem}.native-writing-workspace #native-story-workspace{height:calc(100vh - 17rem)!important;min-height:26rem}.native-writing-workspace>h1{font-size:1.25rem}.writing-context-tools{display:flex;flex-wrap:wrap;gap:.65rem;align-items:center}.writing-context-tools strong{flex-basis:100%}@media(max-width:720px){.native-writing-workspace #native-story-workspace{height:70vh!important}.writing-context-scene-header{flex-wrap:wrap}.writing-context-tools a{max-width:100%;overflow-wrap:anywhere}} +.writing-embedded{margin:0;padding:.75rem;min-width:0}.native-writing-workspace #native-story-workspace{height:calc(100vh - 17rem)!important;min-height:26rem}.native-writing-workspace>h1{font-size:1.25rem}.writing-context-tools{display:flex;flex-wrap:wrap;gap:.65rem;align-items:center}.writing-context-tools strong{flex-basis:100%}@media(max-width:720px){.native-writing-workspace #native-story-workspace{height:70vh!important}.writing-context-tools a{max-width:100%;overflow-wrap:anywhere}} .plot-weave-guide{padding:.6rem .8rem}.plot-weave-guide summary{cursor:pointer;font-weight:600}.plot-weave-focus{outline:3px solid var(--bs-primary,#735369);outline-offset:4px}.plot-map-toolbar{flex-wrap:wrap;gap:.6rem} -/* Dedicated reference/objective workspaces: theme tokens stay owned by the PWA. */ -.writing-context-page {max-width:1600px;margin-inline:auto;overflow-wrap:anywhere;} -.writing-context-tabs {position:sticky;top:0;z-index:3;background:var(--plotline-panel);padding:.5rem;border-radius:.7rem;} -.writing-context-tabs button:focus-visible,.intent-evidence-card summary:focus-visible {outline:3px solid var(--plotline-accent);outline-offset:3px;} +/* Dedicated reference/objective workspaces: theme tokens stay owned by the PWA. */.intent-evidence-card summary:focus-visible {outline:3px solid var(--plotline-accent);outline-offset:3px;} .writing-reference-desk {margin-block:1rem;} .writing-context-card p:last-child {margin-bottom:0;} -.writing-context-shell-header .eyebrow {margin-bottom:.2rem;} -.writing-context-shell-header h1 {font-size:1.5rem;} -.writing-context-scene-header h2 {font-size:clamp(1.25rem,2vw,1.8rem);} .intent-evidence-card {padding:.85rem;margin-block:.65rem;border:1px solid var(--plotline-line);border-radius:.6rem;background:var(--plotline-panel);} .intent-evidence-card summary {cursor:pointer;line-height:1.6;} .intent-evidence-card blockquote {padding:.75rem;border-inline-start:3px solid var(--plotline-accent);white-space:pre-wrap;} .intent-decision-actions {display:flex;gap:.5rem;flex-wrap:wrap;margin-block:.75rem;} -.writing-embedded .writing-context-page {min-height:100vh;padding:1rem;} -@media(max-width:900px){.writing-context-grid,.writing-context-grid--overview,.writing-context-grid--place{grid-template-columns:minmax(0,1fr);}.writing-context-card--hero,.writing-context-card--wide{grid-column:auto;}.writing-context-scene-header,.writing-context-shell-header{flex-wrap:wrap;gap:.65rem;}.writing-context-scene-actions{width:100%;grid-template-columns:minmax(0,1fr) auto;}.writing-context-status{white-space:normal;}.writing-context-empty{padding:1.25rem;min-height:30vh;}} +@media(max-width:900px){.writing-context-grid,.writing-context-grid--overview,.writing-context-grid--place{grid-template-columns:minmax(0,1fr);}.writing-context-card--hero,.writing-context-card--wide{grid-column:auto;}.writing-context-empty{padding:1.25rem;min-height:30vh;}} /* Dedicated windows own the viewport; the story pane fills the remaining height. */ .writing-embedded:has(>#native-workspace){padding:0;} @@ -7715,16 +7597,6 @@ html[data-standalone="true"] .plotline-shell.location-workspace-shell { button.pd-presence{font:inherit;cursor:pointer;background:transparent;border:0;color:var(--plotline-ink)} .writing-connection-dialog{width:min(36rem,calc(100vw - 2rem));max-height:85dvh;overflow:auto;border:1px solid var(--plotline-line);border-radius:1rem;padding:1.3rem;background:var(--plotline-panel);color:var(--plotline-ink);box-shadow:0 1rem 4rem #0005} .writing-connection-dialog::backdrop{background:#0006} -.writing-embedded .writing-context-page{min-height:calc(100dvh - 3rem);padding:.7rem;} -.writing-context-shell-header{align-items:center;margin-bottom:.6rem;gap:.5rem} -.writing-context-scene-header{gap:.75rem;margin-bottom:.6rem;align-items:center} -.writing-context-scene-header h2{font-size:clamp(1.1rem,2vw,1.6rem);overflow-wrap:anywhere} -.writing-context-scene-header p{margin-bottom:.3rem} -.writing-scene-step{display:flex;gap:.4rem;grid-column:1/-1;justify-content:flex-end} -.writing-context-tabs{flex-wrap:wrap;gap:.3rem} -.writing-context-scene-actions{min-width:0;max-width:28rem} -.writing-context-scene-actions select{min-width:0;max-width:100%} -@media(max-width:700px){.writing-context-scene-actions{width:100%;max-width:none}.writing-scene-step{justify-content:flex-start}.writing-context-tabs button{padding:.4rem .65rem}.writing-context-page .writing-context-scene-header{display:block}} .writing-chart-controls,.writing-plot-filters{display:flex;flex-wrap:wrap;gap:.6rem;align-items:center;margin:.5rem 0}.writing-plot-filters label{display:flex;align-items:center;gap:.35rem;font-size:.85rem}.writing-chart-controls label{display:flex;align-items:center;gap:.5rem} .writing-story-scroll{overflow:auto;max-width:100%;border:1px solid var(--plotline-line);border-radius:.7rem;position:relative;isolation:isolate} .writing-story-chart{--scene-width:64px;position:relative;width:calc(160px + var(--scene-count)*var(--scene-width));min-height:8rem;padding:.5rem 0;background:var(--plotline-panel)} @@ -7735,7 +7607,4 @@ button.pd-presence{font:inherit;cursor:pointer;background:transparent;border:0;c .writing-floor-scroll{overflow:auto;max-width:100%;max-height:65dvh;outline-offset:3px}.writing-floor-scroll .writing-context-floor{width:calc(var(--floor-cols)*2.8rem*var(--floor-zoom,1));min-height:calc(var(--floor-rows)*2.8rem*var(--floor-zoom,1));max-width:none}.writing-context-floor-block.is-current-room{outline:3px solid var(--plotline-accent);outline-offset:-3px;background:color-mix(in srgb,var(--plotline-accent) 15%,var(--plotline-panel))}.writing-floor-zoom{display:flex;gap:.5rem;align-items:center;margin:.4rem 0} .writing-context-map{width:100%;height:clamp(18rem,55dvh,50rem);border:1px solid var(--plotline-line);border-radius:.7rem;background:var(--plotline-panel);touch-action:none;cursor:grab}.writing-context-map g.is-scene-place>circle,.writing-context-map g.is-scene-place>path{stroke:var(--plotline-accent);stroke-width:5}.writing-context-map g.is-explored>circle,.writing-context-map g.is-explored>path{stroke:var(--plotline-ink);stroke-width:5}.writing-context-map text{pointer-events:none}.writing-context-map g:focus-visible{outline:none;filter:drop-shadow(0 0 6px var(--plotline-accent))} .writing-chart-controls>label,.writing-plot-filters label{max-width:100%;min-width:0;flex-wrap:wrap;overflow-wrap:anywhere}.writing-chart-controls select{min-width:0;max-width:100%} -.writing-context-scene-actions>label{grid-column:1;grid-row:1;margin:0;align-self:center}.writing-context-scene-actions>.writing-scene-step{grid-column:2;grid-row:1;white-space:nowrap}.writing-context-scene-actions>select{grid-column:1;grid-row:2}.writing-context-scene-actions>a{grid-column:2;grid-row:2;white-space:nowrap} -.writing-context-scene-actions{grid-template-columns:minmax(0,1fr) auto;width:min(27rem,100%)}.writing-context-page input[type=range],.writing-context-page input[type=checkbox]{accent-color:var(--plotline-accent)} -html[data-standalone="true"] .writing-context-tabs{top:var(--pd-sticky-height,0px)} [data-word-book-links][hidden],[data-word-document-picker][hidden]{display:none!important} diff --git a/PlotLine/wwwroot/js/context-workspace.js b/PlotLine/wwwroot/js/context-workspace.js new file mode 100644 index 00000000..85ca6645 --- /dev/null +++ b/PlotLine/wwwroot/js/context-workspace.js @@ -0,0 +1,255 @@ +(() => { + 'use strict'; + const root = document.querySelector('[data-context-workspace]'); + if (!root || root.contextController) return; + const registry = new Map(JSON.parse(root.querySelector('[data-context-tabs]').textContent).map(tab => [tab.id, tab])); + const scopes = ['None', 'Book', 'Chapter', 'Scene', 'Paragraph']; + const fields = ['projectId', 'bookId', 'chapterId', 'sceneId', 'paragraphId']; + const number = value => Number.isSafeInteger(Number(value)) && Number(value) > 0 ? Number(value) : null; + const uuid = () => crypto.randomUUID(); + const status = root.querySelector('[data-context-status]'); + const grid = root.querySelector('[data-context-panes]'); + const divider = root.querySelector('[data-context-divider]'); + const layoutSelect = root.querySelector('[data-context-layout]'); + const sceneSelect = root.querySelector('[data-context-scene]'); + const pinned = root.dataset.followMode === 'snapshot'; + const scope = { projectId:number(root.dataset.scopeProjectId), bookId:number(root.dataset.scopeBookId) }; + let position = { ...scope, chapterId:number(root.dataset.chapterId), sceneId:number(root.dataset.sceneId), paragraphId:null }; + let nativeLeases = [], generation = 0, stopped = false, connection, connectionStarting = false, recoveryGeneration = 0; + let navigationRequest, manualGeneration = 0, recoveryPending = false, recoveryAgain = false; + const requests = new Map(); + const lifecycles = { reference: { mount() {}, dispose() {} }, ...(window.PlotDirectorContextLifecycles || {}) }; + const read = (storage,key) => { try { return storage.getItem(key); } catch { return null; } }; + const write = (storage,key,value) => { try { storage.setItem(key,value); } catch { /* UI storage is optional. */ } }; + let windowId = new URL(location.href).searchParams.get('contextWindow') || read(sessionStorage,'plotdirector.context.window.v1'); + if (!/^[a-f0-9-]{36}$/i.test(windowId || '')) windowId = uuid(); + try { if (window.opener?.document.querySelector('[data-context-workspace]')?.contextController?.windowId === windowId) windowId = uuid(); } catch { } + const defaults = () => ({ version:1, layout:'single', ratio:.5, selectedDocument:'', panes:[{tab:'overview',views:{}},{tab:'characters',views:{}}] }); + const stateKey = () => `plotdirector.context.v1.${root.dataset.user}.${windowId}`; + let state; + try { state=JSON.parse(read(localStorage,stateKey())); } catch { } + if (state?.version !== 1 || !Array.isArray(state.panes) || state.panes.length !== 2) state=defaults(); + if (!['single','columns','rows'].includes(state.layout)) state.layout='single'; + state.ratio = Number.isFinite(state.ratio) ? Math.max(.2,Math.min(.8,state.ratio)) : .5; + state.panes=state.panes.map((pane,i)=>({tab:registry.has(pane?.tab)?pane.tab:defaults().panes[i].tab,views:pane?.views && typeof pane.views==='object'?pane.views:{}})); + let selectedDocument = root.dataset.wordInstance && root.dataset.wordSession ? `${root.dataset.wordInstance}/${root.dataset.wordSession}` : state.selectedDocument || ''; + let nativeKey = '', unavailable = false; + const save = () => { state.selectedDocument=selectedDocument; write(sessionStorage,'plotdirector.context.window.v1',windowId); write(localStorage,stateKey(),JSON.stringify(state)); }; + const panes = [...root.querySelectorAll('[data-context-pane]')].map((element,index)=>({ element,index,select:element.querySelector('[data-context-tab]'),host:element.querySelector('[data-context-pane-content]'),status:element.querySelector('[data-context-pane-status]'),records:new Map(),revision:0 })); + const current = pane => pane.records.get(state.panes[pane.index].tab); + const visible = pane => pane.index===0 || state.layout!=='single'; + const guarded = record => record && (record.dirty || record.busy || lifecycles[record.tab.lifecycle]?.canRefresh?.(record.node,record)===false); + function remember(pane) { + const record=pane.host.contextRecord; if(!record)return; + record.scroll={top:pane.host.scrollTop,left:pane.host.scrollLeft}; + state.panes[pane.index].views[record.tab.id]=record.scroll; + } + function dispose(record) { if(record?.mounted){lifecycles[record.tab.lifecycle]?.dispose?.(record.node);record.mounted=false;} } + function mount(pane,record) { + if(record.node.parentNode!==pane.host){dispose(pane.host.contextRecord);pane.host.replaceChildren(record.node);pane.host.contextRecord=record;} + if(!record.mounted){lifecycles[record.tab.lifecycle]?.mount?.(record.node,{paneId:pane.index,windowId,position:{...position}});record.mounted=true;} + const scroll=record.scroll||state.panes[pane.index].views[record.tab.id]; + if(scroll){pane.host.scrollTop=Number(scroll.top)||0;pane.host.scrollLeft=Number(scroll.left)||0;} + } + function cancelRequests() { for(const item of requests.values())item.controller.abort();requests.clear(); } + function fragment(html) { + const doc=new DOMParser().parseFromString(html,'text/html'); + if(/]|]|]/i.test(html)||doc.body.children.length!==1||!doc.body.firstElementChild.matches('[data-context-tab-fragment]')) throw Error('Invalid reference response. Sign in again if your session expired.'); + return doc.body.firstElementChild; + } + async function fetchTab(tab) { + const url=new URL(tab.endpoint,location.origin); + for(const field of fields)if(position[field]!=null)url.searchParams.set(field,position[field]); + if(position.instanceId&&position.sessionId&&!pinned){url.searchParams.set('instanceId',position.instanceId);url.searchParams.set('sessionId',position.sessionId);} + const key=`${generation}:${url.href}`; + if(!requests.has(key)){ + const controller=new AbortController(); + const timer=setTimeout(()=>controller.abort(),20000); + const promise=fetch(url,{signal:controller.signal,cache:'no-store',credentials:'same-origin',headers:{'X-Requested-With':'XMLHttpRequest'}}).then(async response=>{ + if(response.redirected||response.status===401||response.status===403)throw Error('Sign in again with access to this book.'); + if(response.status===409)throw Error('Word mapping changed or is awaiting verification. Saved information remains available.'); + if(!response.ok)throw Error('Saved reference unavailable. Check book access and choose a saved scene, or retry.'); + return await response.text(); + }).finally(()=>{clearTimeout(timer);if(requests.get(key)?.controller===controller)requests.delete(key);}); + requests.set(key,{controller,promise}); + } + return requests.get(key).promise; + } + async function refreshPane(pane) { + if(!visible(pane))return; + const tab=registry.get(state.panes[pane.index].tab); + let record=pane.records.get(tab.id); + if(!record){record={tab,stale:true,node:null,dirty:false,busy:false};pane.records.set(tab.id,record);} + if(guarded(record)){pane.status.textContent='Updates available · this panel is still editing or busy at its previous position.';return;} + if(!record.stale&&record.node){mount(pane,record);pane.status.textContent='';return;} + const level=scopes.indexOf(tab.scope); + if(level>=3&&!position.sceneId){ + dispose(pane.host.contextRecord);pane.host.contextRecord=null;pane.host.replaceChildren(); + pane.host.removeAttribute('aria-busy');pane.status.textContent='No verified current scene. Choose a saved scene to browse.';return; + } + const request=++pane.revision, epoch=generation; + pane.status.textContent=record.node?'Updating saved information…':'Loading saved information…';pane.host.setAttribute('aria-busy','true'); + try { + const html=await fetchTab(tab); + if(stopped||epoch!==generation||request!==pane.revision||state.panes[pane.index].tab!==tab.id||!visible(pane))return; + if(guarded(record)){pane.status.textContent='Updates available · refresh deferred while editing or busy.';return;} + const node=fragment(html); + if(position.sceneId&&Number(node.dataset.sceneId)!==position.sceneId)throw Error('Reference position changed. Refresh saved data to retry.'); + const focused=pane.host.contains(document.activeElement)?document.activeElement:null; + const focusHref=focused?.closest('a')?.getAttribute('href'); + remember(pane);dispose(record);record.node=node;record.stale=false;record.position={...position}; + mount(pane,record); + if(focusHref&&document.hasFocus())[...pane.host.querySelectorAll('a')].find(link=>link.getAttribute('href')===focusHref)?.focus({preventScroll:true}); + pane.status.textContent=unavailable?'Saved reference · live Word position unavailable.':''; + } catch(error) { + if(epoch!==generation||request!==pane.revision||stopped)return; + pane.status.textContent=error.name==='AbortError'?'Reference request interrupted. Use Refresh saved data to retry.':error.message; + if(record.node)mount(pane,record); + } finally { if(request===pane.revision)pane.host.removeAttribute('aria-busy'); } + } + const scopeChanged = (tab,before,after) => { + const level=scopes.indexOf(tab.scope); + if(level<=0)return false; + const count=level===1?2:level===2?3:level===3?4:5; + return fields.slice(0,count).some(field=>before[field]!==after[field]); + }; + function invalidate(hint={}) { + if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId)return; + generation++;cancelRequests(); + for(const pane of panes){for(const record of pane.records.values()){ + if(record.tab.contentRefresh==='none')continue; + // Scene projections can depend on established earlier records: book-level is conservative. + record.stale=true; + }void refreshPane(pane);} + } + function setPosition(next,force=false) { + if((scope.bookId&&number(next.bookId)!==scope.bookId)||(scope.projectId&&number(next.projectId)&&number(next.projectId)!==scope.projectId))return; + const normalized={...scope,...next,bookId:number(next.bookId)||scope.bookId,chapterId:number(next.chapterId),sceneId:number(next.sceneId),paragraphId:next.paragraphId||null}; + const before=position; + if(!force&&JSON.stringify(before)===JSON.stringify(normalized))return; + position=normalized;generation++;cancelRequests(); + sceneSelect.value=position.sceneId||''; + root.querySelector('[data-context-editor]').href=position.sceneId?`/Scenes/Edit/${position.sceneId}`:'/Writer'; + for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');for(const record of pane.records.values())if(force||scopeChanged(record.tab,before,position))record.stale=true;void refreshPane(pane);} + } + async function recoverOffice(force=false) { + if(pinned||selectedDocument||nativeLeases.some(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)))return; + if(recoveryPending){recoveryAgain ||= force;return;} + recoveryPending=true;const epoch=recoveryGeneration; + try { + const url=new URL('/Writing/Context/Position',location.origin);for(const [key,value]of Object.entries(scope))if(value)url.searchParams.set(key,value); + const response=await fetch(url,{cache:'no-store',signal:AbortSignal.timeout(8000),headers:{'X-Requested-With':'XMLHttpRequest'}}); + if(!response.ok||response.redirected)throw Error();const packet=await response.json(); + if(epoch!==recoveryGeneration||selectedDocument||nativeLeases.some(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)))return; + const office=packet.position; + window.PlotDirector?.wordNotifications?.connection('office',packet.connected); + const indicator=document.querySelector('[data-word-companion-presence]');if(indicator)indicator.dataset.officeConnected=String(packet.connected); + if(packet.connected&&office){unavailable=false;status.textContent='Following Word · saved reference data';setPosition(office,force);} + else {unavailable=true;status.textContent='Word disconnected · saved scene browsing remains available';if(force)invalidate();} + } catch {if(epoch===recoveryGeneration){unavailable=true;status.textContent='Word status unavailable · saved reference remains available';if(force)invalidate();}} + finally {recoveryPending=false;if(recoveryAgain){recoveryAgain=false;void recoverOffice(true);}} + } + function followNative(leases,force=false) { + nativeLeases=leases.filter(l=>Date.parse(l.expires)>Date.now());recoveryGeneration++; + const available=nativeLeases.filter(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)); + const active=available.filter(l=>l.active); + 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){ + if(selectedDocument||available.length){unavailable=true;nativeKey='';status.textContent=available.length>1&&!selectedDocument?'Choose a Word document using the connection indicator':'Selected Word document disconnected · saved reference remains available';generation++;cancelRequests();for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');if(current(pane))current(pane).stale=true;pane.status.textContent='Live position unavailable · displayed reference may be stale.';}return;} + nativeKey='';void recoverOffice(force);return; + } + if(lease.wordSaved!==true||lease.positionVerified===false||!lease.sceneId){ + unavailable=true;nativeKey='';generation++;cancelRequests();for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');if(current(pane))current(pane).stale=true;pane.status.textContent='Displayed reference is saved data · current Word scene is unavailable.';} + status.textContent=lease.positionMessage||'Save Word and verify its scene mapping · saved reference remains available';return; + } + unavailable=false; + const key=[lease.instanceId,lease.sessionId,lease.manuscriptId,lease.revision,lease.snapshotRevision,lease.chapterId,lease.sceneId].join(':'); + const changed=nativeKey!==key;nativeKey=key; + status.textContent='Following Word · saved reference data'; + // Observed revision alone is not accepted content. It only causes position verification. + setPosition({ ...scope,bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:Number(lease.sceneId),instanceId:lease.instanceId,sessionId:lease.sessionId },force||leases.reconnected); + if(changed&&lease.mappingCurrent)invalidate({bookId:lease.bookId}); + } + function applyLayout() { + grid.dataset.layout=state.layout;layoutSelect.value=state.layout; + panes[1].element.hidden=state.layout==='single';divider.hidden=state.layout==='single'; + divider.setAttribute('aria-orientation',state.layout==='rows'?'horizontal':'vertical'); + const size=state.layout==='rows'?grid.clientHeight:grid.clientWidth; + const minimum=state.layout==='rows'?120:220; + const edge=Math.min(.45,minimum/Math.max(size-12,1)); + const ratio=Math.max(edge,Math.min(1-edge,state.ratio)); + grid.style.setProperty('--context-first',`calc((100% - .75rem) * ${ratio})`); + divider.setAttribute('aria-valuenow',String(Math.round(ratio*100))); + divider.setAttribute('aria-valuemin',String(Math.round(edge*100)));divider.setAttribute('aria-valuemax',String(Math.round((1-edge)*100))); + for(const pane of panes){pane.select.value=state.panes[pane.index].tab;if(visible(pane))void refreshPane(pane);else{pane.revision++;dispose(current(pane));}} + save(); + } + function resize(ratio) { state.ratio=Math.max(.2,Math.min(.8,ratio));applyLayout(); } + let dragging=false; + divider.addEventListener('pointerdown',event=>{if(event.button!==0)return;dragging=true;divider.setPointerCapture(event.pointerId);event.preventDefault();}); + divider.addEventListener('pointermove',event=>{if(!dragging)return;const box=grid.getBoundingClientRect();resize(state.layout==='rows'?(event.clientY-box.top)/box.height:(event.clientX-box.left)/box.width);}); + for(const type of ['pointerup','pointercancel','lostpointercapture'])divider.addEventListener(type,()=>dragging=false); + divider.addEventListener('keydown',event=>{const keys=state.layout==='rows'?['ArrowUp','ArrowDown']:['ArrowLeft','ArrowRight'];if(![...keys,'Home','End'].includes(event.key))return;event.preventDefault();resize(event.key==='Home'?.2:event.key==='End'?.8:state.ratio+(event.key===keys[0]?-.05:.05));}); + layoutSelect.addEventListener('change',()=>{panes.forEach(remember);state.layout=layoutSelect.value;applyLayout();}); + for(const pane of panes){ + pane.select.value=state.panes[pane.index].tab; + pane.select.addEventListener('change',()=>{ + if(guarded(current(pane))){pane.select.value=state.panes[pane.index].tab;pane.status.textContent='Finish or cancel editing before changing tools.';return;} + remember(pane);dispose(current(pane));pane.revision++;state.panes[pane.index].tab=pane.select.value;save();void refreshPane(pane); + }); + pane.host.addEventListener('scroll',()=>{remember(pane);save();},{passive:true}); + pane.element.addEventListener('context-panel-state',event=>{ + const record=current(pane);if(!record)return;record.dirty=!!event.detail?.dirty;record.busy=!!event.detail?.busy;if(!guarded(record)&&record.stale)void refreshPane(pane); + }); + } + async function navigate(sceneId,sendWord=false) { + const id=number(sceneId);if(!id)return; + const manual=++manualGeneration;navigationRequest?.abort(); + setPosition({...scope,chapterId:null,sceneId:id},true);status.textContent=pinned?'Saved PlotDirector snapshot · manual selection':'Saved scene selected'; + if(!sendWord||pinned||!scope.bookId)return; + navigationRequest=new AbortController(); + const token=document.querySelector('[data-word-sync-form] [name=__RequestVerificationToken]')?.value; + const body=new URLSearchParams({bookId:scope.bookId,sceneId:id,navigationId:uuid(),__RequestVerificationToken:token||''}); + if(selectedDocument){const [instanceId,sessionId]=selectedDocument.split('/');body.set('instanceId',instanceId);body.set('sessionId',sessionId);} + try{const response=await fetch('/Writing/Context/Navigate',{method:'POST',body,signal:navigationRequest.signal,headers:{'X-Requested-With':'XMLHttpRequest'}});const packet=await response.json();if(manual===manualGeneration)status.textContent=packet.message||'Saved scene selected';}catch(error){if(error.name!=='AbortError'&&manual===manualGeneration)status.textContent='Saved scene selected · Word navigation unavailable';} + } + sceneSelect.addEventListener('change',event=>void navigate(sceneSelect.value,event.isTrusted)); + for(const [selector,step]of [['[data-context-previous]',-1],['[data-context-next]',1]])root.querySelector(selector).addEventListener('click',event=>{const at=[...sceneSelect.options].findIndex(o=>Number(o.value)===position.sceneId);const next=sceneSelect.options[at+step];if(next?.value)void navigate(next.value,event.isTrusted);}); + root.querySelector('[data-context-new]').addEventListener('click',()=>window.PlotDirectorWritingWorkspace.openContext({...position,pinned})); + root.querySelector('[data-context-refresh]').addEventListener('click',()=>invalidate()); + window.addEventListener('native-companion-presence',event=>{if(!pinned)followNative(event.detail||[],!!event.detail?.reconnected);}); + window.addEventListener('plotdirector:word-document-selected',event=>{if(pinned)return;selectedDocument=event.detail||'';nativeKey='';save();followNative(nativeLeases,true);}); + window.addEventListener('plotdirector:word-return-to-current',()=>{if(!pinned){nativeKey='';followNative(nativeLeases,true);}}); + function wakeStatus(reconnected=false){window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status',{detail:{reconnected}}));} + async function startConnection(){ + if(stopped||connectionStarting||!connection||connection.state&&connection.state!=='Disconnected')return; + connectionStarting=true; + try{await connection.start();wakeStatus(true);void recoverOffice(true);}catch{status.textContent='Context notifications disconnected · retrying; saved browsing remains available';}finally{connectionStarting=false;} + } + if(!pinned&&window.signalR){ + connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build(); + connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));wakeStatus();}); + connection.on('ContextPositionChanged',()=>void recoverOffice()); + connection.on('ContextInvalidated',hint=>{invalidate(hint);wakeStatus();}); + connection.onreconnecting(()=>status.textContent='Context notifications reconnecting · saved reference may be stale'); + connection.onreconnected(()=>{wakeStatus(true);void recoverOffice(true);invalidate();}); + connection.onclose(()=>status.textContent='Context notifications disconnected · saved browsing remains available'); + void startConnection(); + } + const timer=pinned?null:setInterval(()=>{void startConnection();void recoverOffice();},15000); + document.addEventListener('visibilitychange',()=>{if(!document.hidden&&!pinned){void startConnection();wakeStatus(true);void recoverOffice(true);}}); + window.addEventListener('pageshow',event=>{if(event.persisted)location.reload();}); + // Duplicated browser tabs clone both URL and session storage. The live owner answers claims. + const pageToken=uuid();let channel; + if(window.BroadcastChannel){channel=new BroadcastChannel(`plotdirector.context.identity.${root.dataset.user}`);channel.onmessage=event=>{ + const message=event.data;if(message.id!==windowId||message.token===pageToken)return; + if(message.kind==='claim')channel.postMessage({kind:'occupied',id:windowId,token:pageToken,target:message.token}); + if(message.kind==='occupied'&&message.target===pageToken){windowId=uuid();panes.forEach(pane=>{dispose(current(pane));pane.revision++;pane.records.clear();pane.host.replaceChildren();});state=defaults();selectedDocument=root.dataset.wordInstance&&root.dataset.wordSession?`${root.dataset.wordInstance}/${root.dataset.wordSession}`:'';save();const url=new URL(location.href);url.searchParams.set('contextWindow',windowId);history.replaceState(null,'',url);applyLayout();} + };channel.postMessage({kind:'claim',id:windowId,token:pageToken});} + const observer=new ResizeObserver(()=>applyLayout());observer.observe(grid); + root.contextController={ get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,registerLifecycle:(name,hooks)=>lifecycles[name]=hooks }; + window.addEventListener('pagehide',()=>{stopped=true;panes.forEach(pane=>{remember(pane);dispose(current(pane));});save();cancelRequests();navigationRequest?.abort();clearInterval(timer);observer.disconnect();channel?.close();void connection?.stop();}); + save();applyLayout(); + if(pinned)status.textContent='Saved PlotDirector snapshot · manual selection · live follow disabled'; +})(); diff --git a/PlotLine/wwwroot/js/native-companion-status.js b/PlotLine/wwwroot/js/native-companion-status.js index 48619486..2a87b29f 100644 --- a/PlotLine/wwwroot/js/native-companion-status.js +++ b/PlotLine/wwwroot/js/native-companion-status.js @@ -23,7 +23,7 @@ documents?.addEventListener('change',()=>{documents.dataset.userSelected='true';window.dispatchEvent(new CustomEvent('plotdirector:word-document-selected',{detail:documents.value}));const button=details.querySelector('[data-word-return-to-current]');if(button)button.disabled=true;void update();}); function renderDetails(leases) { if(!details)return; - const workspace=document.querySelector('[data-writing-context],[data-writing-intent]'),scopeBook=Number(workspace?.dataset.scopeBookId); + const workspace=document.querySelector('[data-context-workspace]'),scopeBook=Number(workspace?.dataset.scopeBookId); const selectable=leases.filter(l=>l.wordAvailable&&(!scopeBook||Number(l.bookId)===scopeBook)); details.querySelector('[data-word-connection-description]').textContent=workspace&&scopeBook&&!selectable.length?'No live Word document is linked to this book. Saved scenes remain available; use Companion to change a manuscript’s book association.':root.title; const previousLabel=documents.selectedOptions[0]?.textContent||'Selected manuscript'; @@ -65,6 +65,6 @@ else if(seen)offline('Word disconnected or stale');else if(text.textContent==='Checking Word…')offline('Word disconnected'); }leases.reconnected=reconnect;root.nativePresence=leases;renderDetails(leases);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases})); }catch{window.dispatchEvent(new CustomEvent('writer-word-state',{detail:{unavailable:true}}));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();let timer;const startTimer=()=>{clearInterval(timer);timer=setInterval(()=>{reconnectHub();void update();},15000);};startTimer();window.addEventListener('pageshow',event=>{if(event.persisted){startTimer();reconnectHub();void update(true);}});document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer));window.addEventListener('plotdirector:refresh-word-status',()=>void update()); - if(window.signalR){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));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();});} + let reconnectHub=()=>{};void update();let timer;const startTimer=()=>{clearInterval(timer);timer=setInterval(()=>{reconnectHub();void update();},15000);};startTimer();window.addEventListener('pageshow',event=>{if(event.persisted){startTimer();reconnectHub();void update(true);}});document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer));window.addEventListener('plotdirector:refresh-word-status',event=>void update(!!event.detail?.reconnected)); + if(window.signalR&&!document.querySelector('[data-context-workspace]')){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));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/native-companion-workspace.js b/PlotLine/wwwroot/js/native-companion-workspace.js index 9da1267c..17a9c06d 100644 --- a/PlotLine/wwwroot/js/native-companion-workspace.js +++ b/PlotLine/wwwroot/js/native-companion-workspace.js @@ -1,11 +1,11 @@ (() => { 'use strict'; const root=document.querySelector('#native-workspace');if(!root)return; - // Context/Intent use Writing's existing fragment workspace directly, never an embedded document. + // Open independent Context windows with the selected authenticated document session. const sessions=root.querySelector('#native-session'),status=root.querySelector('#native-presence-status'),scene=root.querySelector('#native-current-scene'); const scope={projectID:Number(root.dataset.project),bookID:Number(root.dataset.book)}; let selected=root.dataset.instance&&root.dataset.session?root.dataset.instance+'/'+root.dataset.session:'',pending=false; - root.querySelectorAll('[data-native-open-role]').forEach(button=>button.addEventListener('click',()=>window.PlotDirectorWritingWorkspace?.openRoleWindow(button.dataset.nativeOpenRole,scope))); + root.querySelectorAll('[data-native-open-role]').forEach(button=>button.addEventListener('click',()=>window.PlotDirectorWritingWorkspace?.openContext({...scope,...(selected?{instanceId:selected.split('/')[0],sessionId:selected.split('/')[1]}:{})}))); sessions?.addEventListener('change',()=>{selected=sessions.value;void update();}); async function update(){ if(pending||document.hidden)return;pending=true; diff --git a/PlotLine/wwwroot/js/word-companion-host.js b/PlotLine/wwwroot/js/word-companion-host.js index f7400763..f77b92cd 100644 --- a/PlotLine/wwwroot/js/word-companion-host.js +++ b/PlotLine/wwwroot/js/word-companion-host.js @@ -92,7 +92,7 @@ const cleanDialogSceneCount = document.querySelector("[data-clean-dialog-scene-count]"); const openWritingWorkspaceButton = document.querySelector("[data-open-writing-workspace]"); const openWritingContextButton = document.querySelector("[data-open-writing-context]"); - const openWritingIntentButton = document.querySelector("[data-open-writing-intent]"); + const plotDirectorSceneDetails = document.querySelector("[data-plotdirector-scene-details]"); const plotDirectorSceneTitle = document.querySelector("[data-plotdirector-scene-title]"); const plotDirectorRevisionStatus = document.querySelector("[data-plotdirector-revision-status]"); @@ -1366,15 +1366,9 @@ bookId: selectedPresenceBookId() }); - const writingWindowName = (role) => { - const scope = writingWorkspaceScope(); - const suffix = scope.bookId ? `Book_${scope.bookId}` : scope.projectId ? `Project_${scope.projectId}` : "General"; - return `PlotDirector${role}_${suffix}`; - }; - const writingWorkspaceUrl = (target) => { const scope = writingWorkspaceScope(); - const url = new URL(target === "workspace" ? "/Writer" : `/Writing/${target}`, window.location.origin); + const url = new URL("/Writing/Context", window.location.origin); const chapterId = Number.isInteger(resolvedChapterId) && resolvedChapterId > 0 ? resolvedChapterId : detectedChapterAnchorId; @@ -1385,23 +1379,24 @@ if (scope.projectId) { url.searchParams.set("projectId", scope.projectId); } - if (scope.bookId && target !== "workspace") { + if (scope.bookId) { url.searchParams.set("bookId", scope.bookId); } - if (chapterId && target !== "workspace") { + if (chapterId) { url.searchParams.set("chapterId", chapterId); } - if (sceneId && target !== "workspace") { + if (sceneId) { url.searchParams.set("sceneId", sceneId); } - if (documentGuid && target !== "workspace") { + if (documentGuid) { url.searchParams.set("documentGuid", documentGuid); } + url.searchParams.set("contextWindow", crypto.randomUUID()); return `${url.pathname}${url.search}`; }; const openWritingWindow = (target) => { - const role = target === "context" ? "Context" : target === "intent" ? "Intent" : "Workspace"; + const role = "Context"; const url = writingWorkspaceUrl(target); console.info("[Word Companion] Opening writing screen.", { target, @@ -1412,7 +1407,7 @@ sceneId: resolvedSceneId || detectedSceneAnchorId || null, documentGuidPresent: !!currentDocumentGuid() }); - const opened = window.open(url, writingWindowName(role)); + const opened = window.open(url, "_blank"); if (opened) { opened.focus(); } else { @@ -6581,7 +6576,7 @@ cleanUnlinkWordDocumentButton?.addEventListener("click", cleanAndUnlinkWordDocument); openWritingWorkspaceButton?.addEventListener("click", () => openWritingWindow("workspace")); openWritingContextButton?.addEventListener("click", () => openWritingWindow("context")); - openWritingIntentButton?.addEventListener("click", () => openWritingWindow("intent")); + createPlotDirectorChapterButton?.addEventListener("click", createPlotDirectorChapter); linkExistingChapterButton?.addEventListener("click", openLinkExistingChapterDialog); linkChapterSearch?.addEventListener("input", renderLinkChapterOptions); diff --git a/PlotLine/wwwroot/js/writing-context-components.js b/PlotLine/wwwroot/js/writing-context-components.js deleted file mode 100644 index 90fa2a6a..00000000 --- a/PlotLine/wwwroot/js/writing-context-components.js +++ /dev/null @@ -1,50 +0,0 @@ -(() => { - 'use strict'; - const root=document.querySelector('[data-writing-context]');if(!root)return; - function explore(host,index){host.querySelectorAll('[data-context-scene-card]').forEach(card=>card.hidden=Number(card.dataset.contextSceneCard)!==index);const range=host.querySelector('[data-context-scrubber]');if(range)range.value=String(index);} - function refresh(host){ - if(host.querySelector('[data-context-plot-cards]')){window.PlotDirectorContextPlots?.refresh(host);return;} - window.PlotDirectorContextMap?.refresh(host); - const current=root.querySelector('[data-writing-context-fragment]')?.dataset.sceneId; - const currentColumn=[...host.querySelectorAll('[data-context-chart-scene]')].find(node=>node.dataset.contextChartScene===current); - host.querySelectorAll('[data-context-chart-scene]').forEach(node=>node.setAttribute('aria-current',node===currentColumn?'location':'false')); - const index=Number(currentColumn?.dataset.sceneIndex),chart=host.querySelector('[data-context-chart]'); - const spacing=host.querySelector('[data-context-spacing]');if(spacing&&chart)chart.style.setProperty('--scene-width',spacing.value+'px'); - const marker=host.querySelector('[data-context-current-marker]');if(marker){marker.hidden=!currentColumn;if(currentColumn)marker.style.left=`calc(160px + (${index} + .5) * var(--scene-width,64px))`;} - host.querySelectorAll('[data-context-line-filter]').forEach(input=>{const lane=host.querySelector(`[data-context-line="${input.dataset.contextLineFilter}"]`);if(lane)lane.hidden=!input.checked;}); - const metric=host.querySelector('[data-context-metric-select]');host.querySelectorAll('[data-context-metric]').forEach(panel=>panel.hidden=metric&&panel.dataset.contextMetric!==metric.value); - if(host.dataset.explored&&host.querySelector('[data-context-scrubber]'))explore(host,Number(host.querySelector('[data-context-scrubber]').value)); - const currentSignature=current+':'+index; - if(currentColumn&&(!host.dataset.explored||host.dataset.currentSignature!==currentSignature)&&host.dataset.exploring!=='true'){ - host.dataset.explored='true';explore(host,index);host.dataset.centerPending='true'; - } - host.dataset.currentSignature=currentSignature; - if(host.dataset.centerPending&&!host.closest('[data-writing-context-panel]')?.hidden){center(host);delete host.dataset.centerPending;} - - } - function center(host){const marker=host.querySelector('[data-context-current-marker]'),scroll=host.querySelector('.writing-story-scroll');if(marker&&!marker.hidden&&scroll)scroll.scrollLeft=Math.max(0,marker.offsetLeft-scroll.clientWidth/2);} - async function load(host){ - if(host.dataset.loaded||host.dataset.loading)return; - host.dataset.loading='true';host.setAttribute('aria-busy','true');const requestedUrl=host.dataset.componentUrl;host.style.minHeight=host.clientHeight+'px'; - let loading=host.querySelector('[data-writing-loading]');if(!loading){loading=document.createElement('p');loading.dataset.writingLoading='';loading.className='small text-muted';loading.setAttribute('role','status');host.prepend(loading);}loading.textContent='Loading saved information…'; - try{ - const response=await fetch(host.dataset.componentUrl,{signal:AbortSignal.timeout(15000),headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok||response.redirected)throw Error(); - const fragment=window.PlotDirectorWritingFollow.fragmentFromHtml(await response.text(),'[data-writing-component-fragment]'); - if(!host.isConnected||host.dataset.componentUrl!==requestedUrl)return;root.dispatchEvent(new CustomEvent('writing-view-before-refresh'));host.replaceChildren(fragment);host.dataset.loaded='true';window.PlotDirectorContextMap?.mount(host);root.dispatchEvent(new CustomEvent('writing-component-loaded'));refresh(host); - }catch{if(host.isConnected&&host.dataset.componentUrl===requestedUrl){const p=document.createElement('p');p.textContent='Saved information could not be loaded. Your current scene is unchanged.';const retry=document.createElement('button');retry.type='button';retry.className='btn btn-sm btn-outline-secondary';retry.textContent='Retry';retry.addEventListener('click',()=>void load(host));host.replaceChildren(p,retry);}} - finally{delete host.dataset.loading;host.removeAttribute('aria-busy');host.style.minHeight='';if(host.isConnected&&host.dataset.componentUrl!==requestedUrl)update();} - } - function update(){for(const zoom of root.querySelectorAll('[data-context-floor-zoom]')){const floor=zoom.closest('article').querySelector('.writing-context-floor');if(floor)floor.style.setProperty('--floor-zoom',Number(zoom.value)/100);} - for(const host of root.querySelectorAll('[data-writing-component]')){if(!host.closest('[data-writing-context-panel]')?.hidden)void load(host);if(host.dataset.loaded)refresh(host);}} - root.addEventListener('writing-view-activated',update);root.addEventListener('writing-fragment-ready',update); - for(const event of ['wheel','pointerdown','keydown'])root.addEventListener(event,e=>{const scroll=e.target.closest('.writing-story-scroll');if(scroll){const host=scroll.closest('[data-writing-component]');if(host)host.dataset.exploring='true';}},{passive:true}); - root.addEventListener('input',event=>{if(event.target.matches('[data-context-floor-zoom]')){update();return;}const host=event.target.closest('[data-writing-component]');if(!host)return;if(event.target.matches('[data-context-scrubber]')){host.dataset.exploring='true';explore(host,Number(event.target.value));}else refresh(host);}); - root.addEventListener('change',event=>{const host=event.target.closest('[data-writing-component]');if(host)refresh(host);}); - root.addEventListener('click',event=>{const host=event.target.closest('[data-writing-component]');if(!host)return; - const target=event.target.closest('button');if(!target)return; - 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;}} - }); -})(); diff --git a/PlotLine/wwwroot/js/writing-context.js b/PlotLine/wwwroot/js/writing-context.js deleted file mode 100644 index e03015c3..00000000 --- a/PlotLine/wwwroot/js/writing-context.js +++ /dev/null @@ -1,17 +0,0 @@ -(() => { - window.PlotDirectorWritingFollow?.initialize({ - rootSelector: "[data-writing-context]", - contentSelector: "[data-writing-context-content]", - fragmentSelector: "[data-writing-context-fragment]", - statusTextSelector: "[data-writing-context-status-text]", - tabSelector: "[data-writing-context-tab]", - panelSelector: "[data-writing-context-panel]", - selectSelector: "[data-writing-context-scene-select]", - tabDataKey: "writingContextTab", - panelDataKey: "writingContextPanel", - storageKey: "plotdirector.writingContext.activeTab", - defaultTab: "overview", - defaultEndpoint: "/Writing/Context/Scene", - source: "WritingContext" - }); -})(); diff --git a/PlotLine/wwwroot/js/writing-follow.js b/PlotLine/wwwroot/js/writing-follow.js deleted file mode 100644 index e24e52bc..00000000 --- a/PlotLine/wwwroot/js/writing-follow.js +++ /dev/null @@ -1,439 +0,0 @@ -(() => { - const defaults = { - rootSelector: "", - contentSelector: "", - fragmentSelector: "", - statusTextSelector: "", - tabSelector: "", - panelSelector: "", - selectSelector: "", - tabDataKey: "", - panelDataKey: "", - storageKey: "", - defaultTab: "", - defaultEndpoint: "", - source: "WritingMode", - allowChapterOnly: false, - waitingStatus: "Connected, waiting for scene", - updatingStatus: "Updating", - disconnectedStatus: "Word not connected" - }; - - const parsePositiveInt = (value) => { - const parsed = Number.parseInt(value || "", 10); - return Number.isInteger(parsed) && parsed > 0 ? parsed : null; - }; - - const fragmentFromHtml = (html, selector) => { - const parsed = new DOMParser().parseFromString(html, 'text/html'); - const fragment = parsed.body.firstElementChild; - if (/]|]|]/i.test(html) || !fragment?.matches(selector) || parsed.body.children.length !== 1) throw new Error('Expected a writing fragment, received a full page or invalid response'); - return fragment; - }; - - const initialize = (options) => { - const config = { ...defaults, ...options }; - const root = document.querySelector(config.rootSelector); - if (!root) { - return null; - } - - const contentHost = root.querySelector(config.contentSelector); - const statusText = root.querySelector(config.statusTextSelector); - const endpoint = root.dataset.contextUrl || config.defaultEndpoint; - const scopedProjectId = parsePositiveInt(root.dataset.scopeProjectId); - const scopedBookId = parsePositiveInt(root.dataset.scopeBookId); - let currentFragment = contentHost?.querySelector(config.fragmentSelector); - let currentSceneId = parsePositiveInt(currentFragment?.dataset.sceneId); - let currentChapterId = parsePositiveInt(currentFragment?.dataset.chapterId); - let loadingSceneId = null; - let loadingChapterId = null; - let requestGeneration = 0; - let pendingRequest = null, pendingNativeRequest = false, navigationRequest = null; - let manualGeneration=0; - let selectedDocument = root.dataset.wordInstance && root.dataset.wordSession ? root.dataset.wordInstance + '/' + root.dataset.wordSession : ''; - let nativePositionKey = '', nativeWasConnected = false, nativeLeases = []; - const viewState = new Map(), viewNodeIds=new WeakMap();let viewNodeSequence=0; - const viewIdentity=node=>{if(!viewNodeIds.has(node))viewNodeIds.set(node,++viewNodeSequence);return viewNodeIds.get(node);}; - const saveView = () => { - contentHost?.querySelectorAll('[data-writing-view-state]').forEach(node => viewState.set(node.dataset.writingViewState, { value: node.value, checked: node.checked, instance:viewIdentity(node), manualPan:node.dataset.contextManualPan, left: node.scrollLeft, top: node.scrollTop, viewBox: node.getAttribute("viewBox") })); - }; - const restoreView = () => { - contentHost?.querySelectorAll('[data-writing-view-state]').forEach(node => { - const state = viewState.get(node.dataset.writingViewState); if (!state||state.instance===viewIdentity(node)) return; - if (node.matches('select') && [...node.options].some(o => o.value === state.value) || node.matches('input')) node.value = state.value; - if (node.matches('input[type=checkbox]')) node.checked = state.checked; - node.scrollLeft = state.left; node.scrollTop = state.top; - if(state.viewBox&&node.tagName.toLowerCase()==="svg"){node.setAttribute("viewBox",state.viewBox);if(state.manualPan==='true')node.dataset.contextManualPan='true';else delete node.dataset.contextManualPan;} - state.instance=viewIdentity(node); - }); - root.dispatchEvent(new CustomEvent('writing-fragment-ready')); - }; - - root.addEventListener("writing-component-loaded",restoreView); - root.addEventListener("writing-view-before-refresh",saveView); - - const setStatus = (value) => { - if (statusText && value && statusText.textContent!==value) { - statusText.textContent = value; - } - }; - - const setEmptyState = (title, message) => { - const empty = contentHost?.querySelector(".writing-context-empty"); - const heading = empty?.querySelector("h2"); - const copy = empty?.querySelector("p:last-child"); - if (heading && title) { - heading.textContent = title; - } - if (copy && message) { - copy.textContent = message; - } - }; - - const noCurrentSceneMessage = () => { - const bits = []; - if (scopedProjectId) bits.push(`project ${scopedProjectId}`); - if (scopedBookId) bits.push(`book ${scopedBookId}`); - const scope = bits.length ? ` for ${bits.join(", ")}` : ""; - return `No current Word scene has been received${scope}. Reopen this screen from Word Companion after the manuscript scene is detected, or choose a scene manually.`; - }; - - const registerWorkspaceRole = () => { - if (root.dataset.followMode === "snapshot") return; - const role = config.source === "WritingContext" - ? window.PlotDirectorWritingWorkspace?.roles?.context - : config.source === "WritingIntent" - ? window.PlotDirectorWritingWorkspace?.roles?.intent - : null; - if (!role || !window.PlotDirectorWritingWorkspace?.registerWindow) { - return; - } - - const fragment = contentHost?.querySelector(config.fragmentSelector); - void window.PlotDirectorWritingWorkspace.registerWindow({ - projectID: fragment?.dataset.projectId || root.dataset.scopeProjectId, - bookID: fragment?.dataset.bookId || root.dataset.scopeBookId, - writingRole: role, - displayLabel: config.source === "WritingContext" ? "Writing Context" : "Writing Intent" - }).catch(() => null); - }; - - const storyPositionFromWorkspaceStatus = (status) => { - const position = status?.currentStoryPosition || status?.CurrentStoryPosition; - if (!position) { - return null; - } - - return window.PlotDirectorStoryPosition?.normalise(position, "WordCompanion") || position; - }; - - const readStoredTab = () => { - try { - return localStorage.getItem(config.storageKey) || config.defaultTab; - } catch { - return config.defaultTab; - } - }; - - let selectedTab=readStoredTab(); - - const activeTab = () => { - const active = contentHost?.querySelector(`${config.tabSelector}.active`)?.dataset[config.tabDataKey]; - return active || readStoredTab(); - }; - - const activateTab = (tabName) => { - const requested = tabName || config.defaultTab; - const nextTab=[...contentHost.querySelectorAll(config.tabSelector)].some(button=>button.dataset[config.tabDataKey]===requested)?requested:config.defaultTab; - selectedTab=nextTab; - contentHost?.querySelectorAll(config.tabSelector).forEach((button) => { - const active = button.dataset[config.tabDataKey] === nextTab; - button.classList.toggle("active", active); - button.setAttribute("aria-selected", String(active)); - button.setAttribute("role","tab");button.tabIndex=active?0:-1; - }); - contentHost?.querySelectorAll(config.panelSelector).forEach((panel) => { - const active = panel.dataset[config.panelDataKey] === nextTab; - panel.classList.toggle("active", active); - panel.hidden = !active; - }); - try { - localStorage.setItem(config.storageKey, nextTab); - root.dispatchEvent(new CustomEvent("writing-view-activated")); - } catch { - // Remembering the selected tab is a convenience only. - } - }; - - const wireFragment = () => { - activateTab(selectedTab); - const fragment = contentHost?.querySelector(config.fragmentSelector); - const fragmentStatus = fragment?.dataset.followStatus; - if (fragmentStatus) { - setStatus(root.dataset.followMode === "snapshot" ? "Saved PlotDirector snapshot — manual selection" : fragmentStatus); - } - registerWorkspaceRole(); - - const fragmentSceneId = parsePositiveInt(fragment?.dataset.sceneId); - if (fragmentSceneId) { - currentSceneId = fragmentSceneId; - } - - const fragmentChapterId = parsePositiveInt(fragment?.dataset.chapterId); - if (fragmentChapterId) { - currentChapterId = fragmentChapterId; - } - - contentHost?.querySelectorAll(config.tabSelector).forEach((button) => { - button.addEventListener("click", () => activateTab(button.dataset[config.tabDataKey])); - button.closest('nav')?.setAttribute('role','tablist'); - button.addEventListener('keydown',event=>{ - if(!['ArrowLeft','ArrowRight','Home','End'].includes(event.key))return; - event.preventDefault();const tabs=[...contentHost.querySelectorAll(config.tabSelector)],at=tabs.indexOf(button); - const index=event.key==='Home'?0:event.key==='End'?tabs.length-1:(at+(event.key==='ArrowRight'?1:-1)+tabs.length)%tabs.length; - activateTab(tabs[index].dataset[config.tabDataKey]);tabs[index].focus({preventScroll:true}); - }); - }); - - 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, 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, navigationId:crypto.randomUUID(), __RequestVerificationToken: token}); - if (selectedDocument) { const [instanceId, sessionId] = selectedDocument.split('/'); body.set('instanceId', instanceId); body.set('sessionId', sessionId); } - const beforeNavigation=nativePositionKey; - try { - navigationRequest=new AbortController(); - const response = await fetch('/Writing/Context/Navigate', { method: 'POST', body, signal:navigationRequest.signal, headers: {'X-Requested-With':'XMLHttpRequest'} }); - const result = await response.json(); - 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,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) { - return; - } - - const fragment = contentHost?.querySelector(config.fragmentSelector); - void loadPosition({ - source: config.source, - projectId: parsePositiveInt(fragment?.dataset.projectId), - bookId: parsePositiveInt(fragment?.dataset.bookId), - chapterId - }); - }); - }; - - const inScope = (position) => { - if (scopedProjectId && position.projectId !== scopedProjectId) { - return false; - } - - if (scopedBookId && position.bookId && position.bookId !== scopedBookId) { - return false; - } - - return true; - }; - - 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))) { - return; - } - - if (hasScene && position.sceneId === currentSceneId && (loadingChapterId !== null || (loadingSceneId !== null && position.sceneId !== loadingSceneId))) { - ++requestGeneration; pendingRequest?.abort(); pendingRequest = null; - loadingSceneId = null; loadingChapterId = null; setStatus(root.dataset.followMode === "snapshot" ? "Saved PlotDirector snapshot — manual selection" : "Following Word"); return; - } - if (!hasScene && currentSceneId === null && position.chapterId === currentChapterId && (loadingChapterId !== null || loadingSceneId !== null)) { - ++requestGeneration; pendingRequest?.abort(); pendingRequest = null; - loadingSceneId = null; loadingChapterId = null; setStatus(root.dataset.followMode === "snapshot" ? "Saved PlotDirector snapshot — manual selection" : "Following Word"); return; - } - if (hasScene && (position.sceneId === currentSceneId || position.sceneId === loadingSceneId)) { - return; - } - - if (!hasScene && ((currentSceneId === null && position.chapterId === currentChapterId) || position.chapterId === loadingChapterId)) { - return; - } - - const generation = ++requestGeneration; - pendingRequest?.abort(); - const controller = new AbortController(); - pendingRequest = controller; - pendingNativeRequest = position.source === 'WordCompanion'; - loadingSceneId = hasScene ? position.sceneId : null; - loadingChapterId = !hasScene ? position.chapterId : null; - setStatus(config.updatingStatus); - const url = new URL(endpoint, window.location.origin); - if (position.projectId) url.searchParams.set("projectId", position.projectId); - if (position.bookId) url.searchParams.set("bookId", position.bookId); - if (position.chapterId) url.searchParams.set("chapterId", position.chapterId); - if (hasScene) url.searchParams.set("sceneId", position.sceneId); - if(position.source==='WordCompanion'&&position.instanceId&&position.sessionId){url.searchParams.set('instanceId',position.instanceId);url.searchParams.set('sessionId',position.sessionId);} - - try { - console.info(`[${config.source}] Loading writing position.`, position); - const response = await fetch(url, { signal: controller.signal, headers: { "X-Requested-With": "XMLHttpRequest" } }); - if(response.status===409&&position.source==='WordCompanion'){ - if(generation===requestGeneration)setStatus('Word mapping is awaiting verification · saved scene remains available'); - return; - } - if (!response.ok || response.redirected) { - throw new Error(`${config.source} request failed: ${response.status}`); - } - - const html = await response.text(); - if (generation !== requestGeneration) return; - // 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=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]')) { - const replacement=[...fragment.querySelectorAll('[data-writing-stable-panel]')].find(p=>p.dataset.writingStablePanel===panel.dataset.writingStablePanel); - if(replacement){ - if(panel.dataset.writingComponent==='map'&&panel.dataset.componentUrl!==replacement.dataset.componentUrl){panel.dataset.componentUrl=replacement.dataset.componentUrl;delete panel.dataset.loaded;} - replacement.replaceWith(panel); - } - } - contentHost.replaceChildren(fragment); - currentFragment = fragment; - currentSceneId = hasScene ? position.sceneId : null; - if (hasChapter) { - currentChapterId = position.chapterId; - } - wireFragment(); - activateTab(tab); - if(root.dataset.followMode!=="snapshot")setStatus(position.source==="WordCompanion"?"Following Word":"Saved scene"); - restoreView(); - if(focused?.isConnected)focused.focus({preventScroll:true}); - else if(focusedTab)[...contentHost.querySelectorAll(config.tabSelector)].find(button=>button.dataset[config.tabDataKey]===focusedTab)?.focus({preventScroll:true}); - else if(focusedSelect)contentHost.querySelector(config.selectSelector)?.focus({preventScroll:true}); - window.scrollTo(scroll.x, scroll.y); - } catch (error) { - if (generation !== requestGeneration || error?.name === "AbortError") return; - console.warn(`${config.source} could not update.`, error); - setStatus("Context unavailable"); - setEmptyState( - config.source === "WritingIntent" ? "No writing intent is available" : "No Story Intelligence context is available", - `PlotDirector could not load ${config.source === "WritingIntent" ? "intent" : "context"} for the selected Word position. Check that the scene belongs to this project/book and that import data exists.` - ); - } finally { - if (generation === requestGeneration) { - loadingSceneId = null; - loadingChapterId = null; - pendingRequest = null;pendingNativeRequest = false; - } - } - }; - - const suspendNativeRequest = () => { - if(!pendingNativeRequest)return; - ++requestGeneration;pendingRequest?.abort();pendingRequest=null;pendingNativeRequest=false; - loadingSceneId=null;loadingChapterId=null; - }; - const followNative = (leases) => { - nativeLeases = leases; - if(leases.reconnected)nativeWasConnected=false; - const available = leases.filter(l => Date.parse(l.expires) > Date.now() && l.wordAvailable && (!scopedBookId || Number(l.bookId) === scopedBookId)); - if(!available.length&&document.querySelector('[data-word-companion-presence]')?.dataset.officeConnected==='true'){nativeWasConnected=false;nativePositionKey='';return;} - const active = available.filter(l => l.active); - 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) { suspendNativeRequest();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.manuscriptId, lease.revision, lease.chapterId, lease.sceneId, lease.wordSaved].join(':'); - if ((!lease.sceneId && !(config.allowChapterOnly && lease.chapterId)) || lease.wordSaved !== true || lease.positionVerified === false) { suspendNativeRequest();nativeWasConnected = true; nativePositionKey = key; setStatus(lease.positionMessage?lease.positionMessage+' · saved scene remains available':lease.wordSaved===false?'Save Word before verifying its scene mapping · saved scene remains available':'Word scene mapping is awaiting verification · saved scene remains available'); return; } - if (!nativeWasConnected || key !== nativePositionKey || (!pendingRequest && Number(lease.sceneId)!==currentSceneId)) { - nativeWasConnected = true; nativePositionKey = key; - void loadPosition({source:'WordCompanion',instanceId:lease.instanceId,sessionId:lease.sessionId,projectId:scopedProjectId || parsePositiveInt(currentFragment?.dataset.projectId),bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:lease.sceneId?Number(lease.sceneId):null}); - setStatus('Following Word'); - } - }; - if (root.dataset.followMode !== 'snapshot') { - window.addEventListener('native-companion-presence', event => followNative(event.detail || [])); - window.addEventListener('plotdirector:word-return-to-current',()=>{nativePositionKey='';nativeWasConnected=false;followNative(nativeLeases);}); - window.addEventListener('plotdirector:word-document-selected', event => { selectedDocument = event.detail || ''; nativePositionKey = ''; nativeWasConnected = false; followNative(nativeLeases); }); - } - - 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); - }); - - if (typeof window.PlotDirectorWritingWorkspace?.watchWorkspace === 'function') { - const acceptWorkspace = async status => { - if(selectedDocument||nativeLeases.some(l=>l.wordAvailable&&Date.parse(l.expires)>Date.now()&&(!scopedBookId||Number(l.bookId)===scopedBookId)))return; - const position=storyPositionFromWorkspaceStatus(status); - if(position?.sceneId || config.allowChapterOnly&&position?.chapterId)await loadPosition(position); - }; - void window.PlotDirectorWritingWorkspace.watchWorkspace({projectID:scopedProjectId,bookID:scopedBookId}).then(acceptWorkspace).catch(()=>{if(!nativeWasConnected)setStatus(config.disconnectedStatus);}); - document.addEventListener('plotdirector:writing-workspace-reconnected',event=>void acceptWorkspace(event.detail)); - } else if (window.signalR) { - const connection = new signalR.HubConnectionBuilder() - .withUrl("/hubs/word-companion-follow") - .withAutomaticReconnect() - .build(); - - connection.on("storyPositionChanged", (payload) => { - window.PlotDirectorStoryPosition?.publishChanged(payload, payload?.source || payload?.Source || "WordCompanion"); - }); - - connection.start() - .then(async () => { - const status = await connection.invoke("WatchWritingWorkspace", { - projectID: scopedProjectId, - bookID: scopedBookId - }).catch(() => null); - const position = storyPositionFromWorkspaceStatus(status); - if (position?.sceneId || (config.allowChapterOnly && position?.chapterId)) { - await loadPosition(position); - } - - if (!currentSceneId && !(config.allowChapterOnly && currentChapterId)) { - setStatus("No current Word scene received"); - setEmptyState("No current Word scene received", noCurrentSceneMessage()); - } - }) - .catch((error) => { - if(nativeWasConnected)return; - console.warn(`${config.source} follow connection unavailable.`, error); - setStatus(config.disconnectedStatus); - setEmptyState( - "Word Companion connection unavailable", - `This ${config.source === "WritingIntent" ? "Intent" : "Context"} screen could not connect to the Word Companion session. Reopen it from Word Companion, or use the manual scene controls.` - ); - }); - } else { - setStatus(config.disconnectedStatus); - setEmptyState( - "Word Companion connection unavailable", - "SignalR did not load for this screen, so live Word updates are unavailable. Use a URL with project/book/scene IDs or the manual scene controls." - ); - } - - 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 }; - }; - - window.PlotDirectorWritingFollow = { initialize, fragmentFromHtml }; -})(); diff --git a/PlotLine/wwwroot/js/writing-intent.js b/PlotLine/wwwroot/js/writing-intent.js deleted file mode 100644 index 1c894f96..00000000 --- a/PlotLine/wwwroot/js/writing-intent.js +++ /dev/null @@ -1,18 +0,0 @@ -(() => { - window.PlotDirectorWritingFollow?.initialize({ - rootSelector: "[data-writing-intent]", - contentSelector: "[data-writing-intent-content]", - fragmentSelector: "[data-writing-intent-fragment]", - statusTextSelector: "[data-writing-intent-status-text]", - tabSelector: "[data-writing-intent-tab]", - panelSelector: "[data-writing-intent-panel]", - selectSelector: "[data-writing-intent-scene-select]", - tabDataKey: "writingIntentTab", - panelDataKey: "writingIntentPanel", - storageKey: "plotdirector.writingIntent.activeTab", - defaultTab: "plan", - defaultEndpoint: "/Writing/Intent/Scene", - source: "WritingIntent", - allowChapterOnly: true - }); -})(); diff --git a/PlotLine/wwwroot/js/writing-workspace-launcher.js b/PlotLine/wwwroot/js/writing-workspace-launcher.js index 56ba77f8..909b3683 100644 --- a/PlotLine/wwwroot/js/writing-workspace-launcher.js +++ b/PlotLine/wwwroot/js/writing-workspace-launcher.js @@ -1,277 +1,10 @@ (() => { - const root = document.querySelector("[data-writing-workspace-launcher]"); - const workspace = window.PlotDirectorWritingWorkspace; - if (!root || !workspace) { - return; - } - - const statusNodes = { - book: root.querySelector("[data-writing-workspace-book]"), - word: root.querySelector("[data-writing-workspace-word]"), - context: root.querySelector("[data-writing-workspace-context]"), - intent: root.querySelector("[data-writing-workspace-intent]"), - layout: root.querySelector("[data-writing-workspace-layout]"), - message: root.querySelector("[data-writing-workspace-message]") - }; - const startButton = root.querySelector("[data-start-writing-workspace]"); - const detectDisplaysButton = root.querySelector("[data-detect-writing-displays]"); - const contextDisplaySelect = root.querySelector("[data-writing-context-display]"); - const intentDisplaySelect = root.querySelector("[data-writing-intent-display]"); - const contextButton = root.querySelector("[data-open-writing-context]"); - const intentButton = root.querySelector("[data-open-writing-intent]"); - const focusContextButton = root.querySelector("[data-focus-writing-context]"); - const focusIntentButton = root.querySelector("[data-focus-writing-intent]"); - const fallbackScope = workspace.scopeFrom({ - projectID: root.dataset.projectId, - bookID: root.dataset.bookId - }); - const savedDisplays=workspace.readPreferences?.() || {}; - if(contextDisplaySelect&&savedDisplays.contextDisplay){if([...contextDisplaySelect.options].some(o=>o.value===savedDisplays.contextDisplay))contextDisplaySelect.value=savedDisplays.contextDisplay;else contextDisplaySelect.dataset.pendingDisplay=savedDisplays.contextDisplay;} - if(intentDisplaySelect&&savedDisplays.intentDisplay){if([...intentDisplaySelect.options].some(o=>o.value===savedDisplays.intentDisplay))intentDisplaySelect.value=savedDisplays.intentDisplay;else intentDisplaySelect.dataset.pendingDisplay=savedDisplays.intentDisplay;} - for(const select of [contextDisplaySelect,intentDisplaySelect])select?.addEventListener('change',()=>{select.dataset.userChanged='true';delete select.dataset.pendingDisplay;workspace.savePreferences?.(selectedDisplayPreferences());}); - let activeScope = { ...fallbackScope }; - let latestStatus = null; - let latestScreenInfo = null; - - const text = (node, value) => { - if (node) node.textContent = value; - }; - - const statusText = (status, role) => { - const match = (status?.windows || []).find((windowPresence) => - String(windowPresence.writingRole || windowPresence.WritingRole || "").toLowerCase() === role.toLowerCase() - && (!activeScope.bookID || Number(windowPresence.bookID || windowPresence.BookID) === activeScope.bookID)); - if (!match) return "Not open"; - const id = match.browserWindowID || match.BrowserWindowID || ""; - return id === workspace.getBrowserWindowId() ? "This window" : "Open"; - }; - - const setMessage = (message) => text(statusNodes.message, message || ""); - - const selectedDisplayPreferences = () => ({ - contextDisplay: contextDisplaySelect?.dataset.pendingDisplay || contextDisplaySelect?.value || "left", - intentDisplay: intentDisplaySelect?.dataset.pendingDisplay || intentDisplaySelect?.value || "right" - }); - - const displayLabel = (display, fallback) => { - if (!display) return fallback; - const position = Number.isFinite(display.left) ? `${display.left}, ${display.top}` : ""; - return `${display.label || fallback}${position ? ` (${position})` : ""}`; - }; - - const updateDisplayOptions = (screenInfo) => { - latestScreenInfo = screenInfo; - const screens = screenInfo?.screens || []; - if (!contextDisplaySelect || !intentDisplaySelect || !screens.length) { - return; - } - - const currentContext = contextDisplaySelect.dataset.userChanged?contextDisplaySelect.value:savedDisplays.contextDisplay||contextDisplaySelect.value; - const currentIntent = intentDisplaySelect.dataset.userChanged?intentDisplaySelect.value:savedDisplays.intentDisplay||intentDisplaySelect.value; - const baseContext = [ - ["left", "Left display"], - ["primary", "Primary display"], - ["right", "Right display"] - ]; - const baseIntent = [ - ["right", "Right display"], - ["primary", "Primary display"], - ["left", "Left display"] - ]; - const physicalOptions = screens.map((screen, index) => [ - screen.key, - `${index + 1}: ${displayLabel(screen, "Display")}` - ]); - const fill = (select, options, previous) => { - select.replaceChildren(); - [...options, ...physicalOptions].forEach(([value, label]) => { - const option = document.createElement("option"); - option.value = value; - option.textContent = label; - select.append(option); - }); - if ([...select.options].some((option) => option.value === previous)) { - select.value = previous; - } - }; - fill(contextDisplaySelect, baseContext, currentContext); - fill(intentDisplaySelect, baseIntent, currentIntent); - }; - - let nativePresence = document.querySelector('#native-companion-status')?.nativePresence; - const renderCompanion = () => { - if (root.dataset.compactWriter !== "true" || !nativePresence) return; - if (document.querySelector('#native-companion-status')?.dataset.nativeAuthority === 'false') return; - const linked = nativePresence.some(lease => lease.wordAvailable && Number(lease.bookId) === fallbackScope.bookID); - text(statusNodes.word, nativePresence.connectionState === 'Connected' - ? (linked ? 'Connected · linked manuscript open' : 'Connected · no linked manuscript open') - : (nativePresence.connectionState === 'Disconnected' ? 'Disconnected' : nativePresence.connectionState)); - }; - window.addEventListener('native-companion-presence', event => { nativePresence = event.detail; renderCompanion(); }); - const render = (status = latestStatus) => { - const incomingScope = workspace.statusScope(status); - if (status && ((activeScope.projectID && incomingScope.projectID && activeScope.projectID !== incomingScope.projectID) - || (activeScope.bookID && incomingScope.bookID && activeScope.bookID !== incomingScope.bookID))) { - // Presence broadcasts cover all this author's books. They must not change - // the workspace chosen here by a canonical position or explicit command. - if(root.dataset.compactWriter === "true"){if(startButton)startButton.hidden=true;root.dataset.linkedDocument="false";} - text(statusNodes.word, status.wordCompanionConnected || status.WordCompanionConnected ? "Linked manuscript open" : "No linked manuscript open"); - renderCompanion(); - return; - } - if (root.dataset.compactWriter === "true") { - const connected = Boolean(status?.wordCompanionConnected || status?.WordCompanionConnected); - const linked = connected && Boolean(status?.wordDocumentOpen || status?.WordDocumentOpen) && Number(status?.wordBookID || status?.WordBookID) === activeScope.bookID; - if(startButton) startButton.hidden = !linked; - root.dataset.linkedDocument = String(linked); - } - latestStatus = status; - activeScope = workspace.statusScope(status, activeScope); - text(statusNodes.book, activeScope.bookID ? `Book ${activeScope.bookID}` : "Waiting for book"); - text(statusNodes.word, status?.wordCompanionConnected || status?.WordCompanionConnected ? "Linked manuscript open" : "No linked manuscript open"); - if(root.dataset.compactWriter === "true" && (status?.wordCompanionConnected || status?.WordCompanionConnected) && root.dataset.linkedDocument !== "true") text(statusNodes.word,"Connected · no linked document"); - renderCompanion(); - text(statusNodes.context, statusText(status, "Context")); - text(statusNodes.intent, statusText(status, "Intent")); - const contextOpen = statusText(status, "Context") !== "Not open"; - const intentOpen = statusText(status, "Intent") !== "Not open"; - if (focusContextButton) focusContextButton.hidden = !contextOpen; - if (focusIntentButton) focusIntentButton.hidden = !intentOpen; - if (contextButton) contextButton.textContent = contextOpen ? "Focus Context" : "Open Context"; - if (intentButton) intentButton.textContent = intentOpen ? "Focus Intent" : "Open Intent"; - }; - - const refresh = async () => { - try { - render(await workspace.watchWorkspace(activeScope)); - } catch (error) { - setMessage("Writing workspace presence is unavailable."); - console.debug("Writing workspace presence unavailable.", error); - } - }; - - const openOrFocus = async (role) => { - const scope = workspace.statusScope(latestStatus, activeScope); - if (!scope.bookID) { - setMessage("Open a linked Word manuscript or focus a book before opening writing windows."); - return; - } - - const screenInfo = latestScreenInfo || await workspace.getScreenLayout(false, selectedDisplayPreferences()); - updateDisplayOptions(screenInfo); - const targetDisplay = role === workspace.roles.context - ? screenInfo.layout?.contextDisplay - : screenInfo.layout?.intentDisplay; - 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(); - }; - - detectDisplaysButton?.addEventListener("click", async () => { - detectDisplaysButton.disabled = true; - setMessage("Detecting displays..."); - try { - const screenInfo = await workspace.getScreenLayout(true, selectedDisplayPreferences()); - updateDisplayOptions(screenInfo); - const count = screenInfo.screens?.length || 0; - text(statusNodes.layout, screenInfo.layout?.mode || "single-screen"); - if (count > 0) { - setMessage(`Detected ${count} display${count === 1 ? "" : "s"}. Choose target displays, then start or reapply the workspace.`); - } else if (screenInfo.permission === "denied") { - setMessage("Display permission was denied. PlotDirector will reuse named windows, but your browser may open them on the current monitor."); - } else { - setMessage("Display detection is unavailable in this browser. PlotDirector will reuse named windows without monitor placement."); - } - } catch (error) { - console.debug("Display detection failed.", error); - setMessage("Display detection failed. The workspace can still open using named windows."); - } finally { - detectDisplaysButton.disabled = false; - } - }); - - startButton?.addEventListener("click", async () => { - 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() - }); - updateDisplayOptions(result.screenInfo); - if (!result.ok) { - setMessage(result.message || `Pop-up blocked for ${result.blocked?.join(", ") || "a writing window"}. Use the explicit open buttons.`); - } else { - const contextDisplay = displayLabel(result.screenInfo?.layout?.contextDisplay, "selected display"); - const intentDisplay = displayLabel(result.screenInfo?.layout?.intentDisplay, "selected display"); - setMessage(`Workspace requested: Context on ${contextDisplay}, Intent on ${intentDisplay}. If your browser ignores placement, use Focus instead of opening more copies.`); - } - text(statusNodes.layout, result.screenInfo?.layout?.mode || "single-screen"); - await refresh(); - } catch (error) { - console.debug("Unable to start writing workspace.", error); - setMessage("Writing workspace could not be started. Use the direct open buttons."); - } finally { - startButton.disabled = false; - } - }); - - 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."); - }); - intentDisplaySelect?.addEventListener("change", () => { - setMessage("Intent display preference updated. Click Start / Reapply Workspace to use it."); - }); - - document.addEventListener("plotdirector:writing-workspace-status", (event) => render(event.detail)); - document.addEventListener(window.PlotDirectorStoryPosition?.eventName || "plotdirector:story-position-changed", (event) => { - const position = window.PlotDirectorStoryPosition?.normalise?.(event.detail, event.detail?.source || event.detail?.Source) || event.detail; - if (position?.projectId && position?.bookId) { - if(root.dataset.compactWriter === "true" && fallbackScope.bookID && position.bookId !== fallbackScope.bookID) return; - activeScope = { projectID: position.projectId, bookID: position.bookId }; - void workspace.registerWindow({ - ...activeScope, - writingRole: workspace.roles.launcher, - displayLabel: "Writing Workspace" - }).then(render).catch(() => null); - } - }); - - void workspace.registerWindow({ - ...activeScope, - writingRole: workspace.roles.launcher, - displayLabel: "Writing Workspace" - }).then(async (status) => { - render(status); - const screenInfo = await workspace.getScreenLayout(false, selectedDisplayPreferences()); - updateDisplayOptions(screenInfo); - text(statusNodes.layout, screenInfo.layout?.mode || "adaptive"); - }).catch(error => { - text(statusNodes.word, "Status unavailable"); - renderCompanion(); - text(statusNodes.context, "Unavailable"); - text(statusNodes.intent, "Unavailable"); - setMessage("Writing workspace presence is unavailable. Check your connection and retry opening a reference window; other PlotDirector sections remain available."); - console.debug("Writing workspace registration unavailable.", error); + 'use strict'; + const root=document.querySelector('[data-writing-workspace-launcher]');if(!root)return; + root.addEventListener('click',event=>{ + const reference=event.target.closest('[data-focus-reference-link]'); + if(reference){event.preventDefault();const url=new URL(reference.href,location.origin);window.PlotDirectorWritingWorkspace?.openContext(Object.fromEntries(url.searchParams));return;} + const button=event.target.closest('[data-open-writing-context],[data-start-writing-workspace]');if(!button)return; + window.PlotDirectorWritingWorkspace?.openContext({projectId:root.dataset.projectId,bookId:root.dataset.bookId}); }); })(); diff --git a/PlotLine/wwwroot/js/writing-workspace.js b/PlotLine/wwwroot/js/writing-workspace.js index 1d21e450..bf318873 100644 --- a/PlotLine/wwwroot/js/writing-workspace.js +++ b/PlotLine/wwwroot/js/writing-workspace.js @@ -1,397 +1,16 @@ +// Launching is independent of live follow. Only a Context window owns Context notifications. (() => { - const storageKeys = { - windowId: "plotdirector.browserWindowId", - preferences: "plotdirector.writingWorkspace.preferences" - }; - const roles = { - none: "None", - launcher: "Launcher", - context: "Context", - intent: "Intent" - }; - const windowRefs = new Map(); - let connection = null; - let connectionPromise = null; - let heartbeatTimer = null; - 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); - 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); - } - sessionStorage.setItem(ownerKey, owner); - browserWindowId = value; - } catch { - // Keep one identity for this document even when storage is unavailable. - browserWindowId = newWindowId(); - } - return browserWindowId; - }; - - const cleanRole = (role) => { - const value = String(role || "").toLowerCase(); - return value === "launcher" ? roles.launcher - : value === "context" ? roles.context - : value === "intent" ? roles.intent - : roles.none; - }; - - const scopeFrom = (source = {}) => ({ - projectID: parsePositiveInt(source.projectID ?? source.projectId ?? source.ProjectID ?? source.ProjectId), - bookID: parsePositiveInt(source.bookID ?? source.bookId ?? source.BookID ?? source.BookId) - }); - - const scopeMatches = (windowPresence, scope) => { - const projectId = parsePositiveInt(scope?.projectID ?? scope?.projectId); - const bookId = parsePositiveInt(scope?.bookID ?? scope?.bookId); - return (!projectId || parsePositiveInt(windowPresence?.projectID ?? windowPresence?.projectId) === projectId) - && (!bookId || parsePositiveInt(windowPresence?.bookID ?? windowPresence?.bookId) === bookId); - }; - - const roleWindow = (status, role, scope) => (status?.windows || []) - .filter((windowPresence) => cleanRole(windowPresence.writingRole ?? windowPresence.WritingRole) === role && scopeMatches(windowPresence, scope)) - .sort((a, b) => Date.parse(b.lastSeenUtc || b.LastSeenUtc || 0) - Date.parse(a.lastSeenUtc || a.LastSeenUtc || 0))[0] || null; - - const currentRoute = () => `${window.location.pathname}${window.location.search}${window.location.hash}`; - - const statusScope = (status, fallback = {}) => ({ - projectID: parsePositiveInt(status?.projectID ?? status?.projectId ?? fallback.projectID ?? fallback.projectId), - bookID: parsePositiveInt(status?.bookID ?? status?.bookId ?? fallback.bookID ?? fallback.bookId) - }); - - const buildWritingUrl = (role, scope) => { - const url = new URL(role === roles.context ? "/Writing/Context" : "/Writing/Intent", window.location.origin); - url.searchParams.set("embedded","true"); - const projectId = parsePositiveInt(scope?.projectID ?? scope?.projectId); - const bookId = parsePositiveInt(scope?.bookID ?? scope?.bookId); - const position = parsePositiveInt(latestPosition?.bookId ?? latestPosition?.bookID) === bookId ? latestPosition : {}; - if (projectId) url.searchParams.set("projectId", projectId); - if (bookId) url.searchParams.set("bookId", bookId); - else { url.pathname=role === roles.context ? "/Writing/Context" : "/Writing/Intent";url.searchParams.delete("view");url.searchParams.set("embedded","true");url.searchParams.set("pinned","true"); } - if (position.chapterId) url.searchParams.set("chapterId", position.chapterId); - if (position.sceneId) url.searchParams.set("sceneId", position.sceneId); - return `${url.pathname}${url.search}${url.hash}`; - }; - - const stableWindowName = (role, scope) => { - return `PlotDirector${role}`.replace(/[^A-Za-z0-9_]/g, "_"); - }; - - const readPreferences = () => { - try { - return JSON.parse(localStorage.getItem(storageKeys.preferences) || "{}") || {}; - } catch { - return {}; - } - }; - - const savePreferences = (preferences) => { - try { - localStorage.setItem(storageKeys.preferences, JSON.stringify({ ...readPreferences(), ...preferences })); - } catch { - // Layout memory is a convenience only. - } - }; - - const sortScreens = (screens) => [...(screens || [])] - .map((screen, index) => ({ - index, - left: Number(screen.availLeft ?? screen.left ?? 0), - top: Number(screen.availTop ?? screen.top ?? 0), - width: Math.max(320, Number(screen.availWidth ?? screen.width ?? 1200)), - height: Math.max(320, Number(screen.availHeight ?? screen.height ?? 800)), - isPrimary: Boolean(screen.isPrimary), - isInternal: Boolean(screen.isInternal), - key: `screen-${index}`, - label: screen.label || (screen.isPrimary ? "Primary display" : `Display ${index + 1}`) - })) - .sort((a, b) => a.left - b.left || a.top - b.top || a.index - b.index); - - const displayByPreference = (ordered, preference, fallback) => { - const value = String(preference || "").trim().toLowerCase(); - if (value.startsWith("screen-")) { - return ordered.find((screen) => screen.key.toLowerCase() === value) || fallback; - } - if (value === "left") return ordered[0] || fallback; - if (value === "right") return ordered[ordered.length - 1] || fallback; - if (value === "primary") return ordered.find((screen) => screen.isPrimary) || fallback; - if (value === "middle" || value === "centre" || value === "center") return ordered[Math.floor(ordered.length / 2)] || fallback; - return fallback; - }; - - const chooseLayout = (screens, preferences = {}) => { - const ordered = sortScreens(screens); - if (ordered.length >= 3) { - const defaultContext = ordered[0]; - const defaultIntent = ordered[ordered.length - 1]; - return { - mode: "three-screen", - contextDisplay: displayByPreference(ordered, preferences.contextDisplay, defaultContext), - intentDisplay: displayByPreference(ordered, preferences.intentDisplay, defaultIntent), - wordDisplay: ordered[Math.floor(ordered.length / 2)], - displayCount: ordered.length - }; - } - - if (ordered.length === 2) { - const primaryRole = preferences.twoScreenPrimary === "intent" ? roles.intent : roles.context; - const secondary = ordered.find((screen) => !screen.isPrimary) || ordered[1]; - const defaultContext = primaryRole === roles.context ? secondary : ordered[0]; - const defaultIntent = primaryRole === roles.intent ? secondary : ordered[0]; - return { - mode: "two-screen", - contextDisplay: displayByPreference(ordered, preferences.contextDisplay, defaultContext), - intentDisplay: displayByPreference(ordered, preferences.intentDisplay, defaultIntent), - wordDisplay: ordered.find((screen) => screen.isPrimary) || ordered[0], - displayCount: ordered.length - }; - } - - return { - mode: "single-screen", - contextDisplay: ordered[0] || null, - intentDisplay: ordered[0] || null, - wordDisplay: ordered[0] || null, - displayCount: ordered.length - }; - }; - - const popupFeatures = (display) => { - if (!display) { - return `popup=yes,width=${Math.min(1120,Math.max(360,(window.screen?.availWidth||1160)-40))},height=${Math.min(900,Math.max(480,(window.screen?.availHeight||940)-40))}`; - } - - const width = Math.min(display.width, Math.max(360, Math.floor(display.width * 0.92))); - const height = Math.min(display.height, Math.max(480, Math.floor(display.height * 0.92))); - const left = Math.floor(display.left + (display.width - width) / 2); - const top = Math.floor(display.top + (display.height - height) / 2); - return `popup=yes,left=${left},top=${top},width=${width},height=${height}`; - }; - - const getScreenLayout = async (requestPermission, preferences = {}) => { - const mergedPreferences = { ...readPreferences(), ...preferences }; - if (!("getScreenDetails" in window) || typeof window.getScreenDetails !== "function") { - return { supported: false, permission: "unavailable", layout: chooseLayout([], mergedPreferences) }; - } - - try { - if (navigator.permissions?.query && !requestPermission) { - const permission = await navigator.permissions.query({ name: "window-management" }); - if (permission.state !== "granted") { - return { supported: true, permission: permission.state, layout: chooseLayout([], mergedPreferences) }; - } - } - - const details = await window.getScreenDetails(); - const screens = sortScreens(details.screens || []); - return { supported: true, permission: "granted", screens, currentScreen: details.currentScreen, layout: chooseLayout(screens, mergedPreferences) }; - } catch (error) { - return { supported: true, permission: error?.name === "NotAllowedError" ? "denied" : "unavailable", error, layout: chooseLayout([], mergedPreferences) }; - } - }; - - const ensureConnection = async () => { - if (!window.signalR) { - throw new Error("SignalR is unavailable."); - } - if (connectionPromise) { - return connectionPromise; - } - connection = new signalR.HubConnectionBuilder() - .withUrl("/hubs/word-companion-follow") - .withAutomaticReconnect() - .build(); - - // The workspace keeps receiving canonical positions independently of the - // retired global browser-navigation toggle. - connection.on("storyPositionChanged", (payload) => { - window.PlotDirectorStoryPosition?.publishChanged(payload, payload?.source || payload?.Source || "WordCompanion"); - }); - - connection.on("WritingWorkspacePresenceChanged", (status) => { - latestStatus = status; - document.dispatchEvent(new CustomEvent("plotdirector:writing-workspace-status", { bubbles: true, detail: status })); - }); - connection.on("WordCompanionPresenceChanged", (status) => { - latestStatus = latestStatus ? { ...latestStatus, wordCompanionConnected: Boolean(status?.isConnected ?? status?.IsConnected), wordDocumentOpen: Boolean(status?.documentOpen ?? status?.DocumentOpen) } : latestStatus; - document.dispatchEvent(new CustomEvent("plotdirector:writing-workspace-word-status", { bubbles: true, detail: status })); - }); - connection.on("WritingWorkspaceFocusRequested", () => { - try { - window.focus(); - } catch { - // Browser focus restrictions are expected here. - } - }); - connection.onreconnected(() => { - if (registration) { - void registerWindow(registration).then(()=>watchWorkspace(registration)).then(status=>document.dispatchEvent(new CustomEvent("plotdirector:writing-workspace-reconnected",{detail:status}))).catch(()=>{}); - } - }); - - 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; - }; - - const invoke = async (method, ...args) => { - const activeConnection = await ensureConnection(); - return await activeConnection.invoke(method, ...args); - }; - - const registerWindow = async (options) => { - registration = { - browserWindowID: getBrowserWindowId(), - projectID: parsePositiveInt(options.projectID ?? options.projectId), - bookID: parsePositiveInt(options.bookID ?? options.bookId), - currentRoute: currentRoute(), - writingRole: cleanRole(options.writingRole || options.role), - displayLabel: options.displayLabel || "" - }; - latestStatus = await invoke("RegisterWritingWindow", registration); - document.dispatchEvent(new CustomEvent("plotdirector:writing-workspace-status", { bubbles: true, detail: latestStatus })); - if (heartbeatTimer) { - window.clearInterval(heartbeatTimer); - } - heartbeatTimer = window.setInterval(() => { - if (!registration) return; - void invoke("WritingWindowHeartbeat", { ...registration, currentRoute: currentRoute() }).catch(() => null); - }, 15000); - return latestStatus; - }; - - const watchWorkspace = async (scope) => { - latestStatus = await invoke("WatchWritingWorkspace", scopeFrom(scope)); - document.dispatchEvent(new CustomEvent("plotdirector:writing-workspace-status", { bubbles: true, detail: latestStatus })); - return latestStatus; - }; - - const openRoleWindow = (role, scope, display) => { - const url = buildWritingUrl(role, scope); - const name = stableWindowName(role, scope); - const existing=windowRefs.get(name); - if(existing&&!existing.closed){const target=new URL(url,location.origin);if(existing.location.pathname!==target.pathname||new URLSearchParams(existing.location.search).get("bookId")!==target.searchParams.get("bookId"))existing.location.assign(url);existing.focus();return existing;} - const opened = window.open(url, name, popupFeatures(display)); - if (opened) { - windowRefs.set(stableWindowName(role, scope), opened); - try { - opened.focus(); - } catch { - // Focus is best-effort only. - } + 'use strict'; + function openContext(scope={}) { + const url=new URL('/Writing/Context',location.origin); + for(const key of ['projectId','bookId','chapterId','sceneId','instanceId','sessionId','documentGuid']) { + const value=scope[key]??scope[key.replace('Id','ID')];if(value)url.searchParams.set(key,value); } + if(scope.pinned)url.searchParams.set('pinned','true'); + url.searchParams.set('contextWindow',crypto.randomUUID()); + const opened=window.open(url.href,'_blank','popup,width=1100,height=760,resizable=yes,scrollbars=yes'); + if(!opened)window.PlotDirector?.toast?.warning('Allow popups to open a Context window.'); return opened; - }; - - const focusRole = async (role, scope, display = null) => { - const ref = windowRefs.get(stableWindowName(role, scope)); - if (ref && !ref.closed) { - const target=buildWritingUrl(role,scope); - const destination=new URL(target,location.origin); - if(ref.location.pathname!==destination.pathname || new URLSearchParams(ref.location.search).get("bookId")!==destination.searchParams.get("bookId"))ref.location.assign(target); - ref.focus(); - return true; - } - - const opened = window.open(buildWritingUrl(role, scope), stableWindowName(role, scope), popupFeatures(display)); - if (opened) { - windowRefs.set(stableWindowName(role, scope), opened); - opened.focus(); - return true; - } - - const status = await invoke("RequestWritingWindowFocus", scopeFrom(scope), role).catch(() => null); - return !!roleWindow(status, role, scope); - }; - - const startWorkspace = async (scope, options = {}) => { - const cleanScope = scopeFrom(scope); - const status = await watchWorkspace(cleanScope); - const resolvedScope = statusScope(status, cleanScope); - if (!resolvedScope.projectID || !resolvedScope.bookID) { - return { ok: false, message: "Choose a book or open a linked Word manuscript before starting the writing workspace.", status }; - } - - const screenInfo = await getScreenLayout(Boolean(options.requestScreens), options.displayPreferences || {}); - const layout = screenInfo.layout; - const existingContext = roleWindow(status, roles.context, resolvedScope); - const existingIntent = roleWindow(status, roles.intent, resolvedScope); - const opened = []; - const blocked = []; - - if (!existingContext) { - const contextWindow = openRoleWindow(roles.context, resolvedScope, layout.contextDisplay); - (contextWindow ? opened : blocked).push(roles.context); - } else { - await focusRole(roles.context, resolvedScope, layout.contextDisplay); - } - - if (!existingIntent) { - const intentWindow = registration?.writingRole === roles.intent ? window : openRoleWindow(roles.intent, resolvedScope, layout.intentDisplay); - (intentWindow ? opened : blocked).push(roles.intent); - } else { - await focusRole(roles.intent, resolvedScope, layout.intentDisplay); - } - - savePreferences({ lastLayoutMode: layout.mode }); - return { ok: blocked.length === 0, opened, blocked, status: await watchWorkspace(resolvedScope), screenInfo }; - }; - - document.addEventListener(window.PlotDirectorStoryPosition?.eventName || "plotdirector:story-position-changed", (event) => { - latestPosition = window.PlotDirectorStoryPosition?.normalise?.(event.detail, event.detail?.source || event.detail?.Source) || event.detail; - }); - - window.PlotDirectorWritingWorkspace = { - roles, - getBrowserWindowId, - registerWindow, - watchWorkspace, - startWorkspace, - focusRole, - openRoleWindow, - stableWindowName, - buildWritingUrl, - sortScreens, - chooseLayout, - getScreenLayout, - readPreferences, - savePreferences, - scopeFrom, - statusScope - }; + } + window.PlotDirectorWritingWorkspace={openContext}; })();