PlotDirector/Docs/Writer/Unified-Context-Workspace-Foundation-20261121.md

24 KiB
Raw Blame History

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:

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.<account>.<window UUID>. sessionStorage records the current window identity; managed launches pass a fresh contextWindow UUID. Ordinary refresh/navigation restores that window's layout, ratio, both pane selections, selected document and per-tool scroll. No manuscript prose or unsaved form drafts are persisted.

New Context, Writer, native launcher and Office launches open independent windows with a fresh UUID/default single-pane arrangement. Role-wide popup names, role focus selection and global active-tab keys are gone. An opener check plus account-scoped BroadcastChannel identity claims (with a storage-event fallback) detects cloned/duplicated live tabs; the newcomer receives a new identity/default layout. Explicit native document parameters are retained during clone repair. Storage access, including a denied storage getter, is guarded. When persistent storage is unavailable, each document operates with fresh in-memory identity/state; otherwise storage events provide clone recovery when BroadcastChannel is unavailable.

Single mode retains pane two's tool and state. Layouts are Single, Side by side and Stacked. Pointer drag and arrow/Home/End keyboard controls resize the separator; orientation, value and controlled pane IDs are exposed for assistive technology. Ratios are bounded; pane-size constraints are clamped to the available viewport. On very small/zoomed displays users can select stacked or single layout rather than relying on operating-system snapping.

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, generic None/Book/Chapter/Scene/Paragraph hierarchy using test-only registration metadata, hidden staleness, same-scene invalidation, rapid chapter/scene races, dirty/busy deferral, access/session failures, reconnect, native ambiguity/document selection and reload persistence, delayed manual saved reads during unavailable native observations, Office fallback/native precedence, independent windows, cloned storage (BroadcastChannel and storage-event fallback), denied storage, persistence, pinned snapshots and Office/Intent launch compatibility.
  • Browser sizes include 1366×768, 760×768, 683×384 and 480×700 at 125% CSS zoom; shell/card reflow and no document-wide horizontal overflow are checked. The 683×384 viewport approximates the CSS space at 200% on a 1366×768 display.
  • Shared notifications browser checks pass in browser and simulated standalone presentation. Existing Evidence request/cancel/isolation checks remain applicable.
  • Standalone presentation is simulated Chromium qualification. Physical installed-PWA, Windows Word/VSTO and OS-level zoom/assistive-technology acceptance remain manual; these are not claimed as automated physical tests.

Browser suite uses the existing isolated host:

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

Deployed successfully to Development on 21 November 2026 at 22:40 UTC. Production was not accessed or changed.

  • Deployed implementation commit: 868099ec828b938d3c9a2c843b1d4be984073819. This evidence is added in a documentation-only follow-up; application source remains the deployed implementation.
  • Release: /srv/apps/plotdirector-dev/releases/context-foundation-868099e-20261121T224027Z.
  • Rollback application backup: /srv/apps/plotdirector-dev/current-before-context-foundation-868099e-20261121T224027Z. Deployment preserves configured appsettings/environment files, data-protection state, uploads and logs.
  • Active import/queued and processing intelligence/synthesis/enrichment/core-import/marker work guard: passed immediately before service stop; effective database verified as PlotDirector_Development. No migration was applied.
  • plotdirector-dev: active/running after installation. Local HTTP GET and public HTTPS GET both returned 200; public TLS validation was enabled.
  • Deployed assembly: version 1.0.0.0, informational version 1.0.0+868099ec828b938d3c9a2c843b1d4be984073819.
  • Published/deployed DLL SHA-256: fe41f6e131cc8a7152709d80f60064f8b1df47d10172e61e4ab5b638dcaeda27. Context controller JS, Context CSS, native-status JS and Office hosted JS hashes also matched the release publish.
  • Authenticated context-workspace-development.cjs: passed against the actual public Development application with no HTTP/SignalR mocks. Confirmed saved Overview and empty Characters data, exactly one real hub connection, two panes sharing one reference request, an actual Scene editor save invalidating both panes and a second independent Context window, persistence, snapshots with no Context hub connection, native-session mismatch 409, forbidden/mismatched scope rejection, anonymous denial and Intent redirect. The disposable scene title was restored.
  • Journal review from deployment through smoke completion: zero application errors; one HTTPS-redirection middleware warning, “Failed to determine the https port for redirect.” Public reverse-proxy HTTPS and local GET both passed. No unrelated configuration change was made.

Full harness finished with 673 PASS results and exit 0; normal build and Release publish succeeded. Focused browser suites passed: Context foundation, shared notifications, actual Writer/native dialog toast paths (browser and simulated standalone), and explicit Intent Evidence cancellation/isolation. Additional focused Writing integration verified lightweight account-group invalidations and failure-safe notification delivery.

The new opt-in live smoke requires private disposable identity/scope files via PD_CONTEXT_IDENTITY and PD_CONTEXT_SCOPE. It checks the account/database/synthetic project and exact scene title before its bounded editor update; no real author manuscript is used. The existing manual Scene/Create page did not expose a creation form during fixture setup, so a new scene was provisioned through the existing SceneRepository under verified disposable ownership instead of changing unrelated creation UI.

Known limitations

  • Only Overview and Characters in Scene are available. The other eleven feature areas remain dormant pending their requested migrations; full application editors remain available.
  • Context shows authoritative saved reference data. Accepted prose synchronization does not imply completed canonical Story Intelligence analysis, and no analysis is started by refresh.
  • Paragraph scope is supported by the generic registry, but the current common position integration supplies no durable paragraph identity and no paragraph tool is shipped.
  • Browser layout/zoom and standalone presentation were qualified in Chromium; physical Windows Word/VSTO, a genuinely installed PWA and OS/browser zoom plus assistive technology need the manual acceptance below. No physical Word performance claim is made.
  • Managed new-window identities, BroadcastChannel and storage-event clone recovery, and denied-storage in-memory operation are tested. Settings cannot persist when storage is denied.
  • Window/pane settings are local to the account/browser/window identity, not server-roaming preferences. Storage refusal falls back to usable in-memory operation.

Adding a future tab

  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=<saved scene>&bookId=<book> 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.

Persistent companion navigation standard

Context remains open while the author visits full application pages. Every Context feature must delegate main-page navigation through context-main-window.js, using the existing workspace.open registry/interaction contract. Same-origin page links in the Context document are delegated automatically, including refreshed partials and expanded details. New destinations extend the central ContextWorkspaceNavigation read-only route allowlist. Feature-specific discovery, window creation and additional SignalR connections are prohibited.

Context-local interactions (tabs, scene navigation, Hold/Follow, spatial inspection, Show on map/floor plan, edits and placement) remain within Context. Main application Back buttons keep their normal behaviour. See the shared navigation contract for exact destinations, legacy entity commands, launch fallback and browser limits.